/**
 * DocCasePanel — links from a document page to any narrative case files
 * that reference it.
 *
 * No detective surfacing. No evidence/hypothesis/contradiction IDs. Just
 * the cases that drew on this document, presented as story cards.
 */
import Link from "next/link";

interface ReportRow { slug: string; topic: string; topic_pt_br: string | null; opening: string }

export async function DocBureauPanel({ docId }: { docId: string }) {
  const { readdir, readFile } = await import("node:fs/promises");
  const path = await import("node:path");
  const dir = path.join(process.env.CASE_ROOT || "/data/ufo/case", "reports");

  let reports: ReportRow[] = [];
  try {
    const files = await readdir(dir);
    for (const f of files) {
      if (!f.endsWith(".md")) continue;
      const md = await readFile(path.join(dir, f), "utf-8");
      if (!md.includes(docId)) continue;
      const topicMatch = md.match(/topic:\s*"([^"]+)"/);
      const topicPtMatch = md.match(/topic_pt_br:\s*"([^"]+)"/);
      const bodyMatch = md.match(/^---[\s\S]+?\n---\n([\s\S]+)$/);
      const body = bodyMatch?.[1] ?? "";
      // First non-heading paragraph as opening hook.
      const opening = body
        .split("\n")
        .find((l) => l.trim().length > 0 && !l.startsWith("#") && !l.startsWith(">") && !l.startsWith("|") && !l.startsWith("---"))
        ?.slice(0, 240) ?? "";
      reports.push({
        slug: f.replace(/\.md$/, ""),
        topic: topicMatch?.[1] ?? f,
        topic_pt_br: topicPtMatch?.[1] ?? null,
        opening,
      });
    }
  } catch { /* fine — no reports yet */ }

  if (reports.length === 0) {
    return null;
  }

  return (
    <section className="mb-6 rounded-lg border border-[rgba(224,192,128,0.18)] bg-gradient-to-br from-[rgba(224,192,128,0.04)] to-transparent p-4">
      <div className="text-[10px] font-mono text-[#e0c080] uppercase tracking-wider mb-3">
        // Casos narrados que citam este documento
      </div>
      <div className="grid md:grid-cols-2 gap-3">
        {reports.map((r) => (
          <Link
            key={r.slug}
            href={`/c/${r.slug}`}
            className="block rounded border border-[rgba(224,192,128,0.18)] bg-[#0d1220] p-3 hover:bg-[rgba(224,192,128,0.04)]"
          >
            <div className="text-[14px] text-[#e7ecf3] font-medium mb-1">
              {r.topic_pt_br || r.topic}
            </div>
            {r.opening && (
              <div className="text-[11px] text-[#9aa6b8] leading-relaxed line-clamp-3">
                {r.opening}
              </div>
            )}
            <div className="mt-2 text-[10px] font-mono text-[#5a6678]">
              /c/{r.slug} →
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
}
