---

import type { CollectionEntry } from 'astro:content';
import { getCollection, getEntries } from 'astro:content';
import { AuthorSocialLinks } from '@/components/blog/AuthorSocialLinks';
import BlogPostCard from '@/components/blog/BlogPostCard.astro';
import JsonLd from '@/components/JsonLd.astro';
import { PRODUCTION_URL } from '@/consts';
import Blog from '@/layouts/Blog.astro';
import { createProfilePageSchema } from '@/utils/jsonLd/schemas';

export async function getStaticPaths() {
  const authors = await getCollection('authors');
  return authors.map((author) => ({
    params: { author: author.id },
    props: { author },
  }));
}

type Props = {
  author: CollectionEntry<'authors'>;
};

const { author } = Astro.props;

// Get all blog posts by this author
const allPosts = await getCollection('blog');
const authorPosts = allPosts.filter((post) => post.data.authors.some((a) => a.id === author.id));
const sortedPosts = authorPosts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

// Resolve author references for all posts
const postsWithAuthors = await Promise.all(
  sortedPosts.map(async (post) => ({
    ...post,
    authors: await getEntries(post.data.authors),
  }))
);

// Build JSON-LD schema for ProfilePage
const pageUrl = new URL(Astro.url.pathname, PRODUCTION_URL).toString();
const jsonLdSchema = createProfilePageSchema({
  url: pageUrl,
  author,
  posts: authorPosts,
  siteUrl: PRODUCTION_URL.toString(),
});
---

<Blog
  title={[author.data.name, "Blog"]}
  description={`Posts by ${author.data.name} on the Video.js blog`}
>
  <JsonLd slot="head" schema={jsonLdSchema} />
  <header
    class="mx-auto mb-10 grid w-full max-w-3xl grid-cols-1 gap-x-10 md:grid-cols-(--md-grid-cols)"
    style={author.data.avatar
      ? "--md-grid-cols: auto minmax(0, 1fr);"
      : undefined}
  >
    {
      author.data.avatar && (
        <img
          src={author.data.avatar}
          alt={author.data.name}
          class="row-span-3 h-24 w-24 rounded-full border border-current md:h-36 md:w-36"
        />
      )
    }
    <h1 class="mb-1 font-display text-h15 uppercase">{author.data.name}</h1>
    {author.data.bio && <p class="mb-4">{author.data.bio}</p>}
    {
      author.data.socialLinks && (
        <AuthorSocialLinks
          client:idle
          socialLinks={author.data.socialLinks}
          className="flex gap-2"
        />
      )
    }
  </header>
  <section class="mx-auto grid w-full max-w-3xl gap-10">
    {
      postsWithAuthors.map((post) => (
        <BlogPostCard post={post} authors={post.authors} />
      ))
    }
  </section>
</Blog>
