import { getDictionary } from "@/get-dictionary";
import type { Locale } from "@/i18n-config";
import WorkDetailClient from "@/components/WorkDetailClient";
import { notFound } from "next/navigation";
import { getProjects } from "@/app/actions";

// ── Static params for all slug × lang combinations ──
export async function generateStaticParams() {
  const langs: Locale[] = ["en", "tr"];
  const dbProjects = await getProjects();
  
  const slugs = dbProjects.length > 0
    ? dbProjects.map((p) => p.slug)
    : [
        "financeai-dashboard",
        "chainsupply-network",
        "meditrack-mobile",
        "novamart-platform",
      ];

  return langs.flatMap((lang) =>
    slugs.map((slug) => ({ lang, slug }))
  );
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ lang: Locale; slug: string }>;
}) {
  const { lang, slug } = await params;
  const dict = await getDictionary(lang);
  
  const dbProjects = await getProjects();
  const items = dbProjects.length > 0 ? dbProjects : (dict.work.items as any[]);
  const project = items.find((p: any) => p.slug === slug);
  if (!project) return { title: "Not Found" };

  return {
    title: `${project.title} — ${dict.nav.brandName}${dict.nav.brandSub}`,
    description: project.desc,
    alternates: {
      canonical: `/${lang}/work/${slug}`,
    },
  };
}

export default async function WorkDetailPage({
  params,
}: {
  params: Promise<{ lang: Locale; slug: string }>;
}) {
  const { lang, slug } = await params;
  const dict = await getDictionary(lang);
  
  const dbProjects = await getProjects();
  const items = dbProjects.length > 0 ? dbProjects : (dict.work.items as any[]);
  const project = items.find((p: any) => p.slug === slug);

  if (!project) notFound();

  // Determine prev/next
  const currentIdx = items.findIndex((p: any) => p.slug === slug);
  const prev = currentIdx > 0 ? items[currentIdx - 1] : null;
  const next = currentIdx < items.length - 1 ? items[currentIdx + 1] : null;

  return (
    <WorkDetailClient
      lang={lang}
      dict={dict}
      project={project}
      prev={prev}
      next={next}
    />
  );
}
