import type { Metadata } from "next";
import Link from "next/link";
import { listDocuments, readDocument } from "@/lib/wiki";
import { getLocale } from "@/components/locale-toggle";
import { SiteHeader } from "@/components/site-header";
import { BureauNav } from "@/components/bureau-nav";
import { summarize, pickPitch } from "@/lib/doc-summary";
import { DocListFilters } from "@/components/doc-list-filters";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Documentos desclassificados — Arquivo UAP/UFO",
  description:
    "Cada memorando, telegrama e relatório desclassificado do Departamento de Guerra dos EUA sobre UAP/UFO. " +
    "Páginas indexadas, citações vinculadas, busca por texto.",
};

export default async function DocumentsPage() {
  const locale = (await getLocale()) === "en" ? "en" : "pt-br";
  const ids = await listDocuments();
  const summaryLang: "pt" | "en" = locale === "en" ? "en" : "pt";

  const docs = await Promise.all(
    ids.map(async (id) => {
      const f = await readDocument(id);
      return {
        id,
        title: (f?.fm.canonical_title as string) ?? id,
        pages: (f?.fm.page_count as number) ?? 0,
        collection: (f?.fm.collection as string) ?? "uncategorized",
        classification: (f?.fm.highest_classification as string) ?? "—",
        summary: pickPitch(f?.fm as Record<string, unknown> | undefined, summaryLang) ?? (f?.body ? summarize(f.body, summaryLang) : ""),
      };
    }),
  );
  const totalPages = docs.reduce((s, d) => s + d.pages, 0);

  return (
    <div className="min-h-screen">
      <SiteHeader locale={locale} />
      <BureauNav crumbs={[{ label: locale === "en" ? "documents" : "documentos" }]} />

      <div className="mx-auto max-w-7xl px-4 md:px-8 py-10 md:py-14">
        <header className="mb-10">
          <div className="text-[10px] font-mono uppercase tracking-[0.18em] text-[#5a6678] mb-3">
            {locale === "en" ? "// The primary record" : "// O registro primário"}
          </div>
          <h1 className="font-display text-4xl md:text-6xl font-semibold text-[#e7ecf3] leading-tight mb-3">
            {locale === "en" ? "Documents" : "Documentos"}
          </h1>
          <p className="text-lg text-[#9aa6b8] max-w-2xl">
            {locale === "en"
              ? `${ids.length} declassified files · ${totalPages.toLocaleString("pt-BR")} pages · every memo, telegram and report.`
              : `${ids.length} arquivos desclassificados · ${totalPages.toLocaleString("pt-BR")} páginas · cada memorando, telegrama e relatório.`}
          </p>
        </header>

        <DocListFilters docs={docs} />
      </div>
      <noscript>
        <Link href="/" className="hidden">{locale === "en" ? "Home" : "Início"}</Link>
      </noscript>
    </div>
  );
}
