/**
 * GreatestHits — curated list of the most-cited events in the corpus.
 *
 * Shows the top N events by `total_mentions` from public.entities, which
 * surfaces the historical anchors: Kenneth Arnold 1947, Mantell 1948, etc.
 * Each card is an editorial teaser linking to the event entity page.
 */
import Link from "next/link";
import { pgQuery } from "@/lib/retrieval/db";

interface EventRow {
  entity_id: string;
  canonical_name: string;
  total_mentions: number;
}

/**
 * Parse "EV-1947-06-24-kenneth-arnold-sighting" → { year, slug }.
 * Returns null when the entity_id doesn't follow the canonical pattern.
 */
function parseEventId(id: string): { year: number | null; slug: string } {
  const m = id.match(/^EV-(\d{4})-(?:\d{2}|XX)-(?:\d{2}|XX)-(.+)$/i);
  if (!m) return { year: null, slug: id };
  return { year: parseInt(m[1], 10), slug: m[2] };
}

export async function GreatestHits({ locale, limit = 9 }: { locale: "pt-br" | "en"; limit?: number }) {
  const rows = await pgQuery<EventRow>(
    `SELECT entity_id, canonical_name, total_mentions
       FROM public.entities
      WHERE entity_class = 'event'
        AND total_mentions >= 2
        AND canonical_name NOT ILIKE '%unspecified%'
        AND canonical_name NOT ILIKE '%unknown%'
      ORDER BY total_mentions DESC, entity_id ASC
      LIMIT $1`,
    [limit],
  ).catch(() => [] as EventRow[]);

  if (rows.length === 0) return null;

  return (
    <section className="mx-auto max-w-7xl px-4 md:px-8 py-12 md:py-16">
      <div className="flex items-end justify-between mb-6 flex-wrap gap-3">
        <div>
          <div className="text-[10px] font-mono uppercase tracking-[0.18em] text-[#5a6678] mb-2">
            {locale === "en" ? "// The historical record" : "// O registro histórico"}
          </div>
          <h2 className="font-display text-2xl md:text-3xl text-[#e7ecf3]">
            {locale === "en" ? "The incidents the archive keeps returning to" : "Os incidentes que o arquivo não esquece"}
          </h2>
        </div>
        <Link href="/sightings" className="text-[12px] font-mono text-[#e0c080] hover:underline">
          {locale === "en" ? "all sightings →" : "todos os avistamentos →"}
        </Link>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-4">
        {rows.map((r, i) => {
          const { year } = parseEventId(r.entity_id);
          return (
            <Link
              key={r.entity_id}
              href={`/e/events/${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 ?? "—"}
                </span>
                <span className="font-mono text-[10px] text-[#5a6678] tabular-nums">
                  {r.total_mentions} {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>
              <div className="mt-3 text-[11px] font-mono text-[#5a6678]">
                #{(i + 1).toString().padStart(2, "0")}
              </div>
            </Link>
          );
        })}
      </div>
    </section>
  );
}
