---
import Layout from '../../layouts/Layout.astro';
import { getCollection, getEntry } from 'astro:content';
import Comments from "../../components/Comments.astro";
import {getImage} from "astro:assets";
import {siteConfig} from "../../config";
import ReplyViaEmail from "../../components/ReplyViaEmail.astro";
import { ExtractFirstImage } from '../../plugins/extract-images';
import AuthorInfo from "../../components/helper/authors/Info.astro";

export async function getStaticPaths() {
  const blogEntries = await getCollection('posts');
  return blogEntries.map(entry => ({
    params: { slug: entry.slug }, props: { entry },
  }));
}

const { entry } = Astro.props;
const { Content } = await entry.render();
const noscript = siteConfig.noClientJavaScript
const slug = Astro.params.slug;
const authorId = entry.data.author || siteConfig.defaultAuthor.id;

// Get author data
const authorData = await getEntry('authors', authorId);
const authorInfo = authorData ? authorData.data : siteConfig.defaultAuthor;

// get featured image and use it as og:image
// use the custom cover image if it exists, otherwise use the featured image file in the same directory
const featuredImages = import.meta.glob(`/src/content/posts/*/featured.*`,{import:'default',eager:true});
const customFeaturedImage = entry.data.cover?.src
const matchedImage = Object.keys(featuredImages).find(path => path.includes(slug));
let matchedImage_src;
if (matchedImage && !customFeaturedImage) {
    matchedImage_src = await getImage({src: featuredImages[matchedImage], format: 'webp'}) || null;
}
const firstImageURL = await ExtractFirstImage(Content)

const cover = customFeaturedImage || matchedImage_src?.src || firstImageURL || `/post/${slug}/featured.png` || '';
---

<Layout
  title={entry.data.title}
  description={entry.data.description}
  ogImage={cover}
  author={authorInfo.name}
>
      <h1 class="title">{entry.data.title}</h1>
      <AuthorInfo id={authorId} />
      <span class="date">{new Date(entry.data.pubDate).toISOString().split('T')[0]}</span>
      <div class="content">
        <Content />
      </div>

    <div class="extra-post" style="margin-top: 2rem; border-top: 1px solid var(--border-color); padding-top: 1rem;">
    <ReplyViaEmail title={entry.data.title} email={authorInfo.email} />
        <br>
    <a href="/blog">&larr; Back to posts</a>
    {noscript && <h2>Comments</h2> <Comments path={`post/${slug}`} />}
  </div>

</Layout>