/**
 * EntityListPage — shared shell used by /sightings, /witnesses, /objects,
 * /locations, /operations.
 *
 * Pulls entities of a given class, sorted by total_mentions, paginated.
 * Renders a magazine-style index page with a hero header + searchable
 * card grid. No detective branding.
 */
import Link from "next/link";
import { pgQuery } from "@/lib/retrieval/db";
import { SiteHeader } from "@/components/site-header";
import { BureauNav } from "@/components/bureau-nav";
import { getLocale } from "@/components/locale-toggle";

interface EntityRow {
  entity_class: string;
  entity_id: string;
  canonical_name: string;
  aliases: string[] | null;
  total_mentions: number;
  documents_count: number;
}

export interface EntityListPageProps {
  entityClass: "event" | "person" | "uap_object" | "location" | "organization";
  /** URL folder under /e/ — kebab-case plural. */
  folder: "events" | "people" | "uap-objects" | "locations" | "organizations";
  title_en: string;
  title_pt: string;
  subtitle_en: string;
  subtitle_pt: string;
  /** Minimum total_mentions to surface — filters out doc-scoped noise. */
  min_mentions?: number;
  /** Card variant. "magazine" = larger cards with year/icon; "compact" = tabular list. */
  variant?: "magazine" | "compact";
}

function parseEventId(id: string): { year: number | null } {
  const m = id.match(/^EV-(\d{4})-/i);
  return { year: m ? parseInt(m[1], 10) : null };
}

export async function EntityListPage(props: EntityListPageProps) {
  const locale = (await getLocale()) === "en" ? "en" : "pt-br";
  const rows = await pgQuery<EntityRow>(
    `SELECT entity_class, entity_id, canonical_name, aliases,
            total_mentions, documents_count
       FROM public.entities
      WHERE entity_class = $1
        AND total_mentions >= $2
        AND canonical_name !~ '^(unspecified|unknown|n/a|—|UNKNOWN)$'
      ORDER BY total_mentions DESC, canonical_name ASC
      LIMIT 200`,
    [props.entityClass, props.min_mentions ?? 1],
  ).catch(() => [] as EntityRow[]);

  const title = locale === "en" ? props.title_en : props.title_pt;
  const subtitle = locale === "en" ? props.subtitle_en : props.subtitle_pt;
  const variant = props.variant ?? "magazine";

  return (
    <div className="min-h-screen">
      <SiteHeader locale={locale} />
      <BureauNav crumbs={[{ label: title.toLowerCase() }]} />

      <div className="mx-auto max-w-7xl px-4 md:px-8 py-10 md:py-14">
        <header className="mb-10 md:mb-14">
          <div className="text-[10px] font-mono uppercase tracking-[0.18em] text-[#5a6678] mb-3">
            {locale === "en" ? "// The archive" : "// O arquivo"}
          </div>
          <h1 className="font-display text-4xl md:text-6xl font-semibold text-[#e7ecf3] leading-tight mb-3">
            {title}
          </h1>
          <p className="text-lg text-[#9aa6b8] max-w-2xl">{subtitle}</p>
          <p className="text-[11px] font-mono text-[#5a6678] mt-3">
            {rows.length} {locale === "en" ? "entries" : "entradas"}
          </p>
        </header>

        {rows.length === 0 ? (
          <div className="rounded-lg border border-dashed border-[rgba(224,192,128,0.18)] bg-[#0d1220] p-8 text-center">
            <p className="text-[12px] font-mono text-[#9aa6b8]">
              {locale === "en" ? "No entries yet — the corpus is still being indexed." : "Sem entradas ainda — o corpus está sendo indexado."}
            </p>
          </div>
        ) : variant === "magazine" ? (
          <MagazineGrid rows={rows} folder={props.folder} entityClass={props.entityClass} locale={locale} />
        ) : (
          <CompactGrid rows={rows} folder={props.folder} locale={locale} />
        )}
      </div>

      {/* JSON-LD ItemList for GEO */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "CollectionPage",
          name: title,
          description: subtitle,
          numberOfItems: rows.length,
          mainEntity: {
            "@type": "ItemList",
            itemListElement: rows.slice(0, 50).map((r, i) => ({
              "@type": "ListItem",
              position: i + 1,
              name: r.canonical_name,
              url: `${process.env.NEXT_PUBLIC_SITE_URL ?? "https://disclosure.top"}/e/${props.folder}/${r.entity_id}`,
            })),
          },
        }) }}
      />
    </div>
  );
}

function MagazineGrid({
  rows, folder, entityClass, locale,
}: { rows: EntityRow[]; folder: string; entityClass: string; locale: "pt-br" | "en" }) {
  return (
    <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-4">
      {rows.map((r, i) => {
        const year = entityClass === "event" ? parseEventId(r.entity_id).year : null;
        return (
          <Link
            key={r.entity_id}
            href={`/e/${folder}/${r.entity_id}`}
            className="group block rounded-xl border border-[rgba(127,219,255,0.15)] bg-[#0d1220] p-5 hover:border-[#7fdbff]/50 hover:bg-[#10162a] transition-all"
          >
            <div className="flex items-baseline justify-between mb-2">
              <span className="font-mono text-[10px] tracking-[0.14em] uppercase text-[#7fdbff]/70">
                {year ?? `#${(i + 1).toString().padStart(3, "0")}`}
              </span>
              <span className="font-mono text-[10px] text-[#5a6678] tabular-nums">
                {r.total_mentions.toLocaleString("pt-BR")} {locale === "en" ? "mentions" : "menções"}
              </span>
            </div>
            <h3 className="font-display text-lg md:text-xl text-[#e7ecf3] group-hover:text-[#7fdbff] transition-colors leading-snug">
              {r.canonical_name}
            </h3>
            {r.aliases && r.aliases.length > 0 && (
              <div className="mt-2 text-[11px] text-[#5a6678] line-clamp-1">
                {r.aliases.slice(0, 3).join(" · ")}
              </div>
            )}
          </Link>
        );
      })}
    </div>
  );
}

function CompactGrid({
  rows, folder, locale,
}: { rows: EntityRow[]; folder: string; locale: "pt-br" | "en" }) {
  return (
    <div className="rounded-xl border border-[rgba(127,219,255,0.10)] bg-[#0d1220] overflow-hidden">
      <table className="w-full text-[13px]">
        <thead className="text-[10px] font-mono uppercase tracking-wider text-[#5a6678] border-b border-[rgba(127,219,255,0.10)]">
          <tr>
            <th className="text-left px-4 py-3">{locale === "en" ? "name" : "nome"}</th>
            <th className="text-right px-4 py-3">{locale === "en" ? "mentions" : "menções"}</th>
            <th className="text-right px-4 py-3 hidden sm:table-cell">{locale === "en" ? "documents" : "docs"}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.entity_id} className="border-t border-[rgba(127,219,255,0.05)] hover:bg-[rgba(127,219,255,0.03)]">
              <td className="px-4 py-2">
                <Link href={`/e/${folder}/${r.entity_id}`} className="text-[#e7ecf3] hover:text-[#7fdbff]">
                  {r.canonical_name}
                </Link>
              </td>
              <td className="px-4 py-2 text-right font-mono text-[#9aa6b8] tabular-nums">{r.total_mentions.toLocaleString("pt-BR")}</td>
              <td className="px-4 py-2 text-right font-mono text-[#5a6678] tabular-nums hidden sm:table-cell">{r.documents_count}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
