import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AUTHORS_DATA } from "@/lib/authors-data";
import { BLOG_POSTS } from "@/content/blog";
import { blogService } from "@/lib/blog-service";
import { AuthorDetailView } from "@/components/authors/author-detail-view";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  return AUTHORS_DATA.map((author) => ({
    slug: author.slug,
  }));
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const author = AUTHORS_DATA.find((a) => a.slug === slug);

  if (!author) {
    return { title: "Author not found", robots: { index: false, follow: false } };
  }

  // First sentence of the bio — unique per author and short enough for SERPs.
  const firstSentence = author.about.split(". ")[0].trim();
  const shortBio = firstSentence.endsWith(".") ? firstSentence : `${firstSentence}.`;

  return {
    title: `${author.name} — ${author.role}`,
    description: shortBio,
    alternates: { canonical: `/author/${author.slug}` },
    openGraph: {
      title: `${author.name} — ${author.role} at Quto AI`,
      description: shortBio,
      url: `/author/${author.slug}`,
      type: "profile",
    },
  };
}

export default async function AuthorProfilePage({ params }: PageProps) {
  const { slug } = await params;
  const author = AUTHORS_DATA.find((a) => a.slug === slug);

  if (!author) {
    notFound();
  }

  // Real published articles by this author from MongoDB (with fallback)
  let allPosts = BLOG_POSTS;
  try {
    const mongoPosts = await blogService.getPublishedPosts({ limit: 100 });
    if (mongoPosts && mongoPosts.length > 0) {
      allPosts = mongoPosts as any;
    }
  } catch {}

  const authorPosts = allPosts.filter((p) => p.author.name === author.name).map(
    (p) => ({
      slug: p.slug,
      title: p.title,
      category: p.category,
      readTime: p.readTime,
      date: p.publishedDate,
    }),
  );
  const authorWithPosts = { ...author, blogs: authorPosts };

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "ProfilePage",
    mainEntity: {
      "@type": "Person",
      name: author.name,
      jobTitle: author.role,
      description: author.about,
      url: `https://qutoai.com/author/${author.slug}`,
      ...(author.socialLink ? { sameAs: [author.socialLink] } : {}),
      worksFor: {
        "@type": "Organization",
        name: "Quto AI",
        url: "https://qutoai.com",
      },
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <AuthorDetailView author={authorWithPosts} />
    </>
  );
}
