"use client";
import React, { useEffect, useState, useMemo, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { getPreviousNcsPaged } from "@/lib/api/previous-nc.api";
import type {
  PreviousNcRow,
  NcSource,
} from "@/lib/api/types/previous-nc.types";

// Real icons (same icon set as certificate report)
import {
  ArrowLeft,
  RotateCw,
  Printer,
  Download,
  X as XIcon,
  AlertTriangle,
  ScrollText,
  Circle,
  CircleDot,
  CircleSlash,
  Diamond,
  Hexagon,
  Globe2,
  Building,
  Building2,
  ChevronRight,
  Filter as FilterIcon,
  Check,
  Hourglass,
  Users as UsersIcon,
  Clock,
  ClipboardCheck,
  Repeat,
  Sparkles,
  Layers,
  UserCheck,
} from "lucide-react";

// ═══════════════════════════════════════════════════════════════════════
// Design Tokens
// ═══════════════════════════════════════════════════════════════════════

const TOKENS = {
  // Brand
  brand: "#0f766e",
  brandLight: "#14b8a6",
  brandDark: "#0d544c",

  // Neutral scale
  ink: "#0b1220",
  ink2: "#1f2937",
  ink3: "#475569",
  ink4: "#64748b",
  ink5: "#94a3b8",
  line: "#e2e8f0",
  line2: "#f1f5f9",
  bg: "#f6f8fa",
  surface: "#ffffff",

  // Semantic
  success: "#16a34a",
  warning: "#f59e0b",
  danger: "#dc2626",
  info: "#2563eb",

  // NC type accent colors
  major: "#dc2626",
  minor: "#f59e0b",
  observation: "#2563eb",

  // Source accent colors
  qrs: "#6366f1",
  tqs: "#06b6d4",

  // Audit type accent colors (for KPI cards)
  initial: "#8b5cf6",
  surveillance: "#0891b2",
  reassessment: "#db2777",
  otherAudit: "#64748b",

  // Radii & Shadow
  rSm: "6px",
  rMd: "10px",
  rLg: "14px",
  shadow: "0 1px 3px rgba(15,23,42,0.06), 0 8px 24px rgba(15,23,42,0.04)",
  shadowLg: "0 4px 12px rgba(15,23,42,0.08), 0 16px 40px rgba(15,23,42,0.06)",
};

// ═══════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════

const monthName = (m: number) =>
  ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][m];

const todayStr = () =>
  new Date().toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });

const fmt = (n: number) => n.toLocaleString();

const pct = (n: number, total: number) =>
  total > 0 ? `${((n / total) * 100).toFixed(1)}%` : "0%";

const pctNum = (n: number, total: number) =>
  total > 0 ? (n / total) * 100 : 0;

function formatDate(d?: string | Date | null) {
  if (!d) return "—";
  const dt = typeof d === "string" ? new Date(d) : d;
  if (isNaN(dt.getTime())) return "—";
  return dt.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

// ─── Defensive field extractors (mapper-tolerant) ──────────────────────
const pickStr = (v: any): string => {
  if (v == null) return "";
  if (typeof v === "string") return v.trim();
  if (typeof v === "object") {
    return String(v.name ?? v.title ?? v.label ?? v.value ?? "").trim();
  }
  return String(v).trim();
};

function getNcSource(nc: PreviousNcRow): string {
  const x: any = nc;
  return (pickStr(x.source) || "").toUpperCase();
}

function getNcStatus(nc: PreviousNcRow): string {
  const x: any = nc;
  return (pickStr(x.status) || "").toLowerCase();
}

function getNcType(nc: PreviousNcRow): string {
  const x: any = nc;
  return pickStr(x.nc_type) || pickStr(x.ncType) || "";
}

function getNcAuditType(nc: PreviousNcRow): string {
  const x: any = nc;
  return pickStr(x.audit_type) || pickStr(x.auditType) || "";
}

function getNcCompany(nc: PreviousNcRow): string {
  const x: any = nc;
  return (
    pickStr(x.company_name) ||
    pickStr(x.company?.name) ||
    pickStr(x.client?.name) ||
    pickStr(x.company) ||
    ""
  );
}

function getNcAuditor(nc: PreviousNcRow): string {
  const x: any = nc;
  return (
    pickStr(x.created_by_name) ||
    pickStr(x.createdByName) ||
    pickStr(x.auditor_name) ||
    ""
  );
}

function getNcEntriesCount(nc: PreviousNcRow): number {
  const x: any = nc;
  const n = x.entries_count ?? x.entriesCount ?? 0;
  return typeof n === "number" ? n : Number(n) || 0;
}

function getCreatedYearMonth(nc: PreviousNcRow): string {
  if (!nc.created_at) return "";
  const d = new Date(nc.created_at);
  if (isNaN(d.getTime())) return "";
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}

function getCreatedYear(nc: PreviousNcRow): string {
  if (!nc.created_at) return "";
  const d = new Date(nc.created_at);
  if (isNaN(d.getTime())) return "";
  return String(d.getFullYear());
}

function formatMonthOption(ym: string): string {
  if (!ym) return "";
  const [y, m] = ym.split("-");
  const mi = parseInt(m, 10) - 1;
  if (isNaN(mi) || mi < 0 || mi > 11) return ym;
  return `${monthName(mi)} ${y}`;
}

function daysSince(d?: string | null): number {
  if (!d) return 0;
  const dt = new Date(d);
  if (isNaN(dt.getTime())) return 0;
  return Math.floor((Date.now() - dt.getTime()) / (1000 * 60 * 60 * 24));
}

/** Classify an audit type string into a high-level KPI category. */
function classifyAuditType(at: string): "Initial" | "Surveillance" | "ReAssessment" | "Other" {
  const v = (at || "").toLowerCase();
  if (v.includes("initial")) return "Initial";
  if (v.includes("surveil")) return "Surveillance";
  if (v.includes("re-assess") || v.includes("reassess") || v.includes("re assessment")) return "ReAssessment";
  return "Other";
}

// ═══════════════════════════════════════════════════════════════════════
// Page
// ═══════════════════════════════════════════════════════════════════════

export default function NcReportPage() {
  const router = useRouter();
  const reportRef = useRef<HTMLDivElement>(null);

  const [allNcs, setAllNcs] = useState<PreviousNcRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);

  // ─── Filters ─────────────────────────────────────────────────────────
  const [filterSource, setFilterSource] = useState<string>("");
  const [filterStatus, setFilterStatus] = useState<string>("");
  const [filterNcType, setFilterNcType] = useState<string>("");
  const [filterAuditType, setFilterAuditType] = useState<string>("");
  const [filterAuditor, setFilterAuditor] = useState<string>(""); // 🔹 NEW
  const [filterYear, setFilterYear] = useState<string>("");
  const [filterMonth, setFilterMonth] = useState<string>("");

  // ─── Fetch ALL NCs (paginated) ──────────────────────────────────────
  const fetchAllNcs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const PAGE_SIZE = 100;
      const first = await getPreviousNcsPaged({ page: 1, limit: PAGE_SIZE });
      let all: PreviousNcRow[] = first.rows ?? [];
      const totalPages = Math.min(first.totalPages ?? 1, 200);

      if (totalPages > 1) {
        const rest = await Promise.all(
          Array.from({ length: totalPages - 1 }, (_, i) =>
            getPreviousNcsPaged({ page: i + 2, limit: PAGE_SIZE }).then(
              (r) => r.rows ?? [],
            ),
          ),
        );
        rest.forEach((batch) => (all = all.concat(batch)));
      }
      setAllNcs(all);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load NC analytics");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAllNcs();
  }, [fetchAllNcs]);

  // ─── Filter dropdown options (built from the FULL dataset) ──────────
  // ─── Filter dropdown options — CASCADING ──────────────────────────────
  // Each dropdown is built from the dataset filtered by all OTHER active
  // filters (not itself). So Source=QRS narrows the Auditor list to QRS
  // auditors, and every option shows its exact count under the current
  // selection. Audit type / year / month all cascade the same way.
  const filterOptions = useMemo(() => {
    const matches = (
      nc: PreviousNcRow,
      skip: "source" | "status" | "ncType" | "auditType" | "auditor" | "year" | "month",
    ) => {
      if (skip !== "source" && filterSource && getNcSource(nc) !== filterSource) return false;
      if (skip !== "status" && filterStatus && getNcStatus(nc) !== filterStatus) return false;
      if (skip !== "ncType" && filterNcType && getNcType(nc) !== filterNcType) return false;
      if (skip !== "auditType" && filterAuditType && getNcAuditType(nc) !== filterAuditType) return false;
      if (skip !== "auditor" && filterAuditor && getNcAuditor(nc) !== filterAuditor) return false;
      if (skip !== "year" && filterYear && getCreatedYear(nc) !== filterYear) return false;
      if (skip !== "month" && filterMonth && getCreatedYearMonth(nc) !== filterMonth) return false;
      return true;
    };

    const sources = new Map<string, number>();
    const statuses = new Map<string, number>();
    const ncTypes = new Map<string, number>();
    const auditTypes = new Map<string, number>();
    const auditors = new Map<string, number>();
    const years = new Map<string, number>();
    const months = new Map<string, number>();

    allNcs.forEach((nc) => {
      const src = getNcSource(nc);
      if (src && matches(nc, "source")) sources.set(src, (sources.get(src) ?? 0) + 1);

      const st = getNcStatus(nc);
      if (st && matches(nc, "status")) statuses.set(st, (statuses.get(st) ?? 0) + 1);

      const nt = getNcType(nc);
      if (nt && matches(nc, "ncType")) ncTypes.set(nt, (ncTypes.get(nt) ?? 0) + 1);

      const at = getNcAuditType(nc);
      if (at && matches(nc, "auditType")) auditTypes.set(at, (auditTypes.get(at) ?? 0) + 1);

      const au = getNcAuditor(nc);
      if (au && matches(nc, "auditor")) auditors.set(au, (auditors.get(au) ?? 0) + 1);

      const yr = getCreatedYear(nc);
      if (yr && matches(nc, "year")) years.set(yr, (years.get(yr) ?? 0) + 1);

      const ym = getCreatedYearMonth(nc);
      if (ym && matches(nc, "month")) months.set(ym, (months.get(ym) ?? 0) + 1);
    });

    const byNameAsc = (a: [string, number], b: [string, number]) =>
      a[0].localeCompare(b[0]);
    const byCountDesc = (a: [string, number], b: [string, number]) => b[1] - a[1];

    return {
      sources: Array.from(sources.entries()).sort(byNameAsc).map(([v, n]) => ({ value: v, count: n })),
      statuses: Array.from(statuses.entries()).sort(byNameAsc).map(([v, n]) => ({ value: v, count: n })),
      ncTypes: Array.from(ncTypes.entries()).sort(byCountDesc).map(([v, n]) => ({ value: v, count: n })),
      auditTypes: Array.from(auditTypes.entries()).sort(byCountDesc).map(([v, n]) => ({ value: v, count: n })),
      auditors: Array.from(auditors.entries()).sort(byCountDesc).map(([v, n]) => ({ value: v, count: n })),
      years: Array.from(years.entries())
        .sort((a, b) => b[0].localeCompare(a[0]))
        .map(([v, n]) => ({ value: v, count: n })),
      months: Array.from(months.entries())
        .sort((a, b) => b[0].localeCompare(a[0]))
        .map(([v, n]) => ({ value: v, count: n })),
    };
  }, [
    allNcs,
    filterSource,
    filterStatus,
    filterNcType,
    filterAuditType,
    filterAuditor,
    filterYear,
    filterMonth,
  ]);

  // ─── Apply filters ───────────────────────────────────────────────────
  const filteredNcs = useMemo(() => {
    if (
      !filterSource &&
      !filterStatus &&
      !filterNcType &&
      !filterAuditType &&
      !filterAuditor &&
      !filterYear &&
      !filterMonth
    ) {
      return allNcs;
    }
    return allNcs.filter((nc) => {
      if (filterSource && getNcSource(nc) !== filterSource) return false;
      if (filterStatus && getNcStatus(nc) !== filterStatus) return false;
      if (filterNcType && getNcType(nc) !== filterNcType) return false;
      if (filterAuditType && getNcAuditType(nc) !== filterAuditType) return false;
      if (filterAuditor && getNcAuditor(nc) !== filterAuditor) return false; // 🔹 NEW
      if (filterYear && getCreatedYear(nc) !== filterYear) return false;
      if (filterMonth && getCreatedYearMonth(nc) !== filterMonth) return false;
      return true;
    });
  }, [
    allNcs,
    filterSource,
    filterStatus,
    filterNcType,
    filterAuditType,
    filterAuditor,
    filterYear,
    filterMonth,
  ]);

  const hasActiveFilter =
    !!(filterSource || filterStatus || filterNcType || filterAuditType || filterAuditor || filterYear || filterMonth);

  const clearFilters = () => {
    setFilterSource("");
    setFilterStatus("");
    setFilterNcType("");
    setFilterAuditType("");
    setFilterAuditor(""); // 🔹 NEW
    setFilterYear("");
    setFilterMonth("");
  };

  const stats = useMemo(() => computeStats(filteredNcs), [filteredNcs]);

  // PDF
  // PDF
 const handleDownloadPdf = async () => {
    if (!reportRef.current) return;
    setDownloading(true);
    try {
      const [{ default: jsPDF }, { default: html2canvas }] = await Promise.all([
        import("jspdf"),
        import("html2canvas"),
      ]);

      const canvas = await html2canvas(reportRef.current, {
        scale: 2,
        useCORS: true,
        backgroundColor: "#ffffff",
        imageTimeout: 0,
        logging: false,
        // 🔧 FIX: html2canvas paints every gradient via
        // createPattern(offscreenCanvas, "repeat"). If a gradient-backed
        // element is 0px in either dimension (e.g. a `width: 0%` progress-bar
        // fill when a count is 0), that canvas is 0×0 and createPattern throws
        // "...width or height of 0". Such boxes are invisible anyway, so we
        // drop their gradient in the clone. Also clears the decorative
        // radial-gradient texture, which html2canvas tiles poorly.
        onclone: (clonedDoc: Document) => {
          const win = clonedDoc.defaultView;
          clonedDoc.querySelectorAll<HTMLElement>("*").forEach((el) => {
            const cs = win?.getComputedStyle(el);
            const bg = cs?.backgroundImage || "";
            if (!bg.includes("gradient")) return;

            const w = el.offsetWidth;
            const h = el.offsetHeight;
            // Zero-size gradient box → would crash createPattern.
            if (w === 0 || h === 0) {
              el.style.backgroundImage = "none";
            }
            // Decorative repeating radial texture → safe to drop.
            if (bg.includes("radial-gradient")) {
              el.style.backgroundImage = "none";
            }
          });
        },
      });

      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF("p", "mm", "a4");
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const imgWidth = pdfWidth;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 0;

      pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
      heightLeft -= pdfHeight;

      while (heightLeft > 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
        heightLeft -= pdfHeight;
      }

      // first file: nc-report-...  /  second file: certificate-report-...
      pdf.save(`nc-report-${new Date().toISOString().split("T")[0]}.pdf`);
      toast.success("Report downloaded");
    } catch (err: any) {
      toast.error(err?.message ?? "PDF export failed");
    } finally {
      setDownloading(false);
    }
  };

  if (loading) return <LoadingState />;
  if (error) return <ErrorState message={error} onRetry={fetchAllNcs} />;

  return (
    <div
      style={{
        background: TOKENS.bg,
        minHeight: "100vh",
        padding: "28px 24px 60px",
        fontFamily:
          "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
        color: TOKENS.ink,
      }}
    >
      {/* ── Action Bar (no print) ── */}
      <div
        className="no-print"
        style={{
          maxWidth: 1240,
          margin: "0 auto 16px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 12,
          flexWrap: "wrap",
        }}
      >
        <button
          onClick={() => router.back()}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "9px 16px",
            background: TOKENS.surface,
            border: `1px solid ${TOKENS.line}`,
            borderRadius: TOKENS.rMd,
            cursor: "pointer",
            fontSize: 13,
            fontWeight: 600,
            color: TOKENS.ink3,
            boxShadow: TOKENS.shadow,
            transition: "all 0.15s",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = TOKENS.ink5;
            e.currentTarget.style.color = TOKENS.ink;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = TOKENS.line;
            e.currentTarget.style.color = TOKENS.ink3;
          }}
        >
          <ArrowLeft size={14} strokeWidth={2.2} />
          Back to NCs
        </button>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <ActionButton onClick={fetchAllNcs} variant="secondary">
            <RotateCw size={14} strokeWidth={2.2} />
            Refresh
          </ActionButton>
          <ActionButton onClick={() => window.print()} variant="secondary">
            <Printer size={14} strokeWidth={2.2} />
            Print
          </ActionButton>
          <ActionButton
            onClick={handleDownloadPdf}
            variant="primary"
            disabled={downloading}
          >
            {downloading ? (
              <>
                <Hourglass size={14} strokeWidth={2.2} />
                Generating PDF…
              </>
            ) : (
              <>
                <Download size={14} strokeWidth={2.2} />
                Download PDF
              </>
            )}
          </ActionButton>
        </div>
      </div>

      {/* ── Filter Bar (no print) ── */}
      <div className="no-print" style={{ maxWidth: 1240, margin: "0 auto 20px" }}>
        <FilterBar
          options={filterOptions}
          filterSource={filterSource}
          filterStatus={filterStatus}
          filterNcType={filterNcType}
          filterAuditType={filterAuditType}
          filterAuditor={filterAuditor}
          filterYear={filterYear}
          filterMonth={filterMonth}
          onChangeSource={setFilterSource}
          onChangeStatus={setFilterStatus}
          onChangeNcType={setFilterNcType}
          onChangeAuditType={setFilterAuditType}
          onChangeAuditor={setFilterAuditor}
          onChangeYear={setFilterYear}
          onChangeMonth={setFilterMonth}
          onClear={clearFilters}
          totalAll={allNcs.length}
          totalFiltered={filteredNcs.length}
          hasActiveFilter={hasActiveFilter}
        />
      </div>

      {/* ── REPORT (captured for PDF) ── */}
      <div
        ref={reportRef}
        style={{
          maxWidth: 1240,
          margin: "0 auto",
          background: TOKENS.surface,
          borderRadius: TOKENS.rLg,
          boxShadow: TOKENS.shadow,
          overflow: "hidden",
        }}
      >
        {/* ── HERO HEADER ── */}
        <div
          style={{
            background:
              "linear-gradient(135deg, #0b1220 0%, #0f172a 50%, #0d544c 100%)",
            padding: "36px 40px",
            color: "#fff",
            position: "relative",
            overflow: "hidden",
          }}
        >
          <div
            style={{
              position: "absolute",
              inset: 0,
              backgroundImage:
                "radial-gradient(circle at 1px 1px, rgba(255,255,255,0.08) 1px, transparent 0)",
              backgroundSize: "24px 24px",
              opacity: 0.6,
            }}
          />
          <div style={{ position: "relative" }}>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                padding: "5px 12px",
                background: "rgba(20, 184, 166, 0.15)",
                border: "1px solid rgba(20, 184, 166, 0.4)",
                borderRadius: 999,
                fontSize: 10,
                fontWeight: 700,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                color: "#5eead4",
                marginBottom: 14,
              }}
            >
              <ChevronRight size={11} strokeWidth={2.5} />
              Confidential Report
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "flex-start",
                justifyContent: "space-between",
                flexWrap: "wrap",
                gap: 24,
              }}
            >
              <div style={{ flex: "1 1 400px" }}>
                <h1
                  style={{
                    margin: 0,
                    fontSize: 32,
                    fontWeight: 800,
                    letterSpacing: "-0.025em",
                    lineHeight: 1.15,
                  }}
                >
                  Audit & NC Module
                  <br />
                  <span style={{ color: "#5eead4" }}>Analytics Report</span>
                </h1>
                <p
                  style={{
                    margin: "12px 0 0",
                    fontSize: 14,
                    color: "rgba(255,255,255,0.72)",
                    lineHeight: 1.5,
                    maxWidth: 540,
                  }}
                >
                  Comprehensive overview of audit conduct and non-conformity
                  findings, status distribution, source-database split,
                  audit-type breakdown and monthly trend across QRS and TQS
                  systems.
                </p>

                {hasActiveFilter && (
                  <div
                    style={{
                      marginTop: 16,
                      display: "flex",
                      flexWrap: "wrap",
                      gap: 6,
                      alignItems: "center",
                    }}
                  >
                    <span
                      style={{
                        fontSize: 10,
                        color: "rgba(255,255,255,0.55)",
                        textTransform: "uppercase",
                        letterSpacing: "0.08em",
                        fontWeight: 700,
                        marginRight: 4,
                      }}
                    >
                      Active filters:
                    </span>
                    {filterSource && (
                      <HeroFilterPill label="Source" value={filterSource} />
                    )}
                    {filterStatus && (
                      <HeroFilterPill label="Status" value={filterStatus} />
                    )}
                    {filterNcType && (
                      <HeroFilterPill label="NC Type" value={filterNcType} />
                    )}
                    {filterAuditType && (
                      <HeroFilterPill
                        label="Audit Type"
                        value={filterAuditType}
                      />
                    )}
                    {filterAuditor && (
                      <HeroFilterPill label="Auditor" value={filterAuditor} />
                    )}
                    {filterYear && (
                      <HeroFilterPill label="Year" value={filterYear} />
                    )}
                    {filterMonth && (
                      <HeroFilterPill
                        label="Month"
                        value={formatMonthOption(filterMonth)}
                      />
                    )}
                  </div>
                )}
              </div>

              <div
                style={{
                  display: "grid",
                  gap: 8,
                  fontSize: 12,
                  background: "rgba(255,255,255,0.06)",
                  border: "1px solid rgba(255,255,255,0.1)",
                  borderRadius: TOKENS.rMd,
                  padding: "14px 18px",
                  minWidth: 240,
                }}
              >
                <MetaRow label="Generated" value={todayStr()} />
                <MetaRow
                  label="Reporting Period"
                  value={
                    filterMonth
                      ? formatMonthOption(filterMonth)
                      : filterYear
                      ? filterYear
                      : "All Time"
                  }
                />
                <MetaRow
                  label="Total Records"
                  value={
                    hasActiveFilter
                      ? `${fmt(stats.total)} of ${fmt(allNcs.length)}`
                      : fmt(stats.total)
                  }
                />
                <MetaRow
                  label="Document ID"
                  value={`NC-RPT-${Date.now().toString().slice(-6)}`}
                />
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: "32px 40px 40px" }}>
          {/* ═══════════════════════════════════════════════════════════ */}
          {/* 01 — EXECUTIVE SUMMARY                                       */}
          {/* ═══════════════════════════════════════════════════════════ */}
          <SectionHeader
            number="01"
            title="Executive Summary"
            description={
              hasActiveFilter
                ? "Headline metrics across the filtered subset of non-conformities"
                : "Headline metrics across the entire NC portfolio"
            }
          />

          {/* Row 1: Overall totals */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 14,
            }}
          >
            <KpiCard
              label="Total NCs"
              value={fmt(stats.total)}
              icon={<ScrollText size={14} strokeWidth={2} />}
              accent={TOKENS.brand}
              prominent
            />
            <KpiCard
              label="Open"
              value={fmt(stats.byStatus.open)}
              sub={pct(stats.byStatus.open, stats.total)}
              icon={<CircleDot size={14} strokeWidth={2} />}
              accent={TOKENS.danger}
            />
            <KpiCard
              label="Closed"
              value={fmt(stats.byStatus.closed)}
              sub={pct(stats.byStatus.closed, stats.total)}
              icon={<Check size={14} strokeWidth={2.5} />}
              accent={TOKENS.success}
            />
            <KpiCard
              label="Total Findings"
              value={fmt(stats.totalFindings)}
              sub={`avg ${stats.avgFindings.toFixed(1)} per NC`}
              icon={<Circle size={14} strokeWidth={2} fill="currentColor" />}
              accent={TOKENS.warning}
            />
          </div>

          {/* Row 2: NC type breakdown */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 14,
            }}
          >
            <KpiCard
              label="Major"
              value={fmt(stats.byNcType.Major)}
              sub={pct(stats.byNcType.Major, stats.total)}
              icon={<Diamond size={14} strokeWidth={2} fill="currentColor" />}
              accent={TOKENS.major}
            />
            <KpiCard
              label="Minor"
              value={fmt(stats.byNcType.Minor)}
              sub={pct(stats.byNcType.Minor, stats.total)}
              icon={<Hexagon size={14} strokeWidth={2} />}
              accent={TOKENS.minor}
            />
            <KpiCard
              label="Observation"
              value={fmt(stats.byNcType.Observation)}
              sub={pct(stats.byNcType.Observation, stats.total)}
              icon={<Diamond size={14} strokeWidth={2} />}
              accent={TOKENS.observation}
            />
            <KpiCard
              label="Other Types"
              value={fmt(stats.byNcType.Other)}
              sub={pct(stats.byNcType.Other, stats.total)}
              icon={<XIcon size={14} strokeWidth={2.5} />}
              accent={TOKENS.ink4}
            />
          </div>

          {/* 🔹 Row 3 (NEW): Audit type breakdown KPIs */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 36,
            }}
          >
            <KpiCard
              label="Initial Audit"
              value={fmt(stats.byAuditTypeCategory.Initial)}
              sub={pct(stats.byAuditTypeCategory.Initial, stats.total)}
              icon={<ClipboardCheck size={14} strokeWidth={2} />}
              accent={TOKENS.initial}
            />
            <KpiCard
              label="Surveillance"
              value={fmt(stats.byAuditTypeCategory.Surveillance)}
              sub={pct(stats.byAuditTypeCategory.Surveillance, stats.total)}
              icon={<Layers size={14} strokeWidth={2} />}
              accent={TOKENS.surveillance}
            />
            <KpiCard
              label="Re-Assessment"
              value={fmt(stats.byAuditTypeCategory.ReAssessment)}
              sub={pct(stats.byAuditTypeCategory.ReAssessment, stats.total)}
              icon={<Repeat size={14} strokeWidth={2} />}
              accent={TOKENS.reassessment}
            />
            <KpiCard
              label="Other Audit"
              value={fmt(stats.byAuditTypeCategory.Other)}
              sub={pct(stats.byAuditTypeCategory.Other, stats.total)}
              icon={<Sparkles size={14} strokeWidth={2} />}
              accent={TOKENS.otherAudit}
            />
          </div>

          {/* 🔹 NEW — AUDIT CONDUCT (three audit types: Initial / Surveillance / Recertification) */}
          <SectionHeader
            number="01b"
            title="Audit Conduct"
            description="Audits conducted by type — initial, surveillance and recertification"
          />
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 14,
              marginBottom: 36,
            }}
          >
            <KpiCard
              label="Initial"
              value={fmt(stats.byAuditConduct.Initial)}
              sub={pct(stats.byAuditConduct.Initial, stats.total)}
              icon={<ClipboardCheck size={14} strokeWidth={2} />}
              accent={TOKENS.initial}
            />
            <KpiCard
              label="Surveillance"
              value={fmt(stats.byAuditConduct.Surveillance)}
              sub={pct(stats.byAuditConduct.Surveillance, stats.total)}
              icon={<Layers size={14} strokeWidth={2} />}
              accent={TOKENS.surveillance}
            />
            <KpiCard
              label="Recertification"
              value={fmt(stats.byAuditConduct.Recertification)}
              sub={pct(stats.byAuditConduct.Recertification, stats.total)}
              icon={<Repeat size={14} strokeWidth={2} />}
              accent={TOKENS.reassessment}
            />
          </div>

          {/* Empty-after-filter guard */}
          {hasActiveFilter && stats.total === 0 ? (
            <EmptyState
              icon={<CircleSlash size={20} strokeWidth={2} />}
              title="No NCs match the selected filters"
              text="Adjust or clear the filters above to see report data."
            />
          ) : (
            <>
              {/* ═══════════════════════════════════════════════════════ */}
              {/* 02 — DISTRIBUTION ANALYSIS (twin donuts)                 */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="02"
                title="Distribution Analysis"
                description="NC type & status breakdown shown as proportional segments"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <DonutCard
                  title="By NC Type"
                  segments={[
                    {
                      label: "Major",
                      value: stats.byNcType.Major,
                      color: TOKENS.major,
                    },
                    {
                      label: "Minor",
                      value: stats.byNcType.Minor,
                      color: TOKENS.minor,
                    },
                    {
                      label: "Observation",
                      value: stats.byNcType.Observation,
                      color: TOKENS.observation,
                    },
                    {
                      label: "Other",
                      value: stats.byNcType.Other,
                      color: TOKENS.ink5,
                    },
                  ]}
                />
                <DonutCard
                  title="By Status"
                  segments={[
                    {
                      label: "Open",
                      value: stats.byStatus.open,
                      color: TOKENS.danger,
                    },
                    {
                      label: "Closed",
                      value: stats.byStatus.closed,
                      color: TOKENS.success,
                    },
                  ]}
                />
              </div>

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 03 — SOURCE DATABASE SPLIT                               */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="03"
                title="Source Database Split"
                description="Distribution between QRS and TQS legacy databases"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 14,
                  marginBottom: 36,
                }}
              >
                <DomainCard
                  flag={<Building size={22} strokeWidth={2} />}
                  label="QRS Database"
                  sublabel="qrs.qrsyst.com"
                  count={stats.bySource.QRS}
                  total={stats.total}
                  accent={TOKENS.qrs}
                />
                <DomainCard
                  flag={<Globe2 size={22} strokeWidth={2} />}
                  label="TQS Database"
                  sublabel="tqs.qrsyst.com"
                  count={stats.bySource.TQS}
                  total={stats.total}
                  accent={TOKENS.tqs}
                />
              </div>

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 04 — TOP COMPANIES & AUDITORS                            */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="04"
                title="Top Contributors"
                description="Companies and auditors with the highest NC counts"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <RankingCard
                  title="Top Companies"
                  icon={<Building2 size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byCompany)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
                <RankingCard
                  title="Top Auditors"
                  icon={<UsersIcon size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byAuditor)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
              </div>

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 05 — AUDIT TYPE BREAKDOWN (full ranking)                */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="05"
                title="Audit Type Breakdown"
                description="NCs raised under each audit type — initial, surveillance, re-assessment etc."
              />
              <RankingCard
                title=""
                icon={null}
                rows={Object.entries(stats.byAuditType)
                  .sort((a, b) => b[1] - a[1])
                  .slice(0, 12)}
                total={stats.total}
                full
              />

              <div style={{ height: 36 }} />

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 06 — OPEN NCs WITHOUT FINDINGS (warning tone)           */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="06"
                title="Open NCs Without Findings"
                description={`${stats.openWithoutEntries.length} NC(s) marked open but with no ncr_entries rows — data-integrity flag`}
                accent={TOKENS.warning}
              />
              {stats.openWithoutEntries.length === 0 ? (
                <EmptyState
                  icon={<Check size={20} strokeWidth={2.5} />}
                  title="All open NCs have findings logged"
                  text="Every open non-conformity has at least one entry in ncr_entries."
                  positive
                />
              ) : (
                <DataTable
                  headers={["NC ID", "Source", "Company", "Audit Type", "Type", "Created"]}
                  rows={stats.openWithoutEntries.slice(0, 25).map((nc) => [
                    <NcIdChip key={nc.id} value={`#${nc.id}`} />,
                    <SourceChip key={`${nc.id}-s`} source={getNcSource(nc)} />,
                    getNcCompany(nc) || "—",
                    getNcAuditType(nc) || "—",
                    <TypeChip key={`${nc.id}-t`} type={getNcType(nc)} />,
                    formatDate(nc.created_at),
                  ])}
                  footer={
                    stats.openWithoutEntries.length > 25
                      ? `Showing first 25 of ${stats.openWithoutEntries.length}`
                      : undefined
                  }
                  tone="warning"
                />
              )}

              <div style={{ height: 36 }} />

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 07 — AGED OPEN NCs                                       */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="07"
                title="Aged Open NCs"
                description="Open non-conformities by age — long-running NCs need attention"
                accent={TOKENS.danger}
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3, 1fr)",
                  gap: 12,
                  marginBottom: 16,
                }}
              >
                <AgeStat label="Open 30+ Days" count={stats.aged30} accent="#d97706" />
                <AgeStat label="Open 60+ Days" count={stats.aged60} accent="#ea580c" />
                <AgeStat label="Open 90+ Days" count={stats.aged90} accent={TOKENS.danger} />
              </div>

              {stats.openList.length === 0 ? (
                <EmptyState
                  icon={<Check size={20} strokeWidth={2.5} />}
                  title="No open NCs"
                  text="All NCs in this dataset have been closed."
                  positive
                />
              ) : (
                <DataTable
                  headers={["NC ID", "Source", "Company", "Type", "Created", "Days Open"]}
                  rows={stats.openList.slice(0, 25).map((nc) => {
                    const days = daysSince(nc.created_at);
                    return [
                      <NcIdChip key={nc.id} value={`#${nc.id}`} />,
                      <SourceChip key={`${nc.id}-s`} source={getNcSource(nc)} />,
                      getNcCompany(nc) || "—",
                      <TypeChip key={`${nc.id}-t`} type={getNcType(nc)} />,
                      formatDate(nc.created_at),
                      <AgeChip key={`${nc.id}-d`} days={days} />,
                    ];
                  })}
                  footer={
                    stats.openList.length > 25
                      ? `Showing first 25 of ${stats.openList.length} open NCs (sorted oldest first)`
                      : undefined
                  }
                  tone="danger"
                />
              )}

              <div style={{ height: 36 }} />

              {/* ═══════════════════════════════════════════════════════ */}
              {/* 08 — ISSUANCE TREND                                      */}
              {/* ═══════════════════════════════════════════════════════ */}
              <SectionHeader
                number="08"
                title="NC Issuance Trend"
                description="Monthly NC creation count over the last 12 months"
              />
              <TrendChart data={stats.last12MonthsIssued} />
            </>
          )}

          {/* ── FOOTER ── */}
          <div
            style={{
              marginTop: 40,
              paddingTop: 20,
              borderTop: `1px solid ${TOKENS.line}`,
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              flexWrap: "wrap",
              gap: 12,
              fontSize: 11,
              color: TOKENS.ink5,
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: TOKENS.rSm,
                  background: `linear-gradient(135deg, ${TOKENS.brand}, ${TOKENS.brandLight})`,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "#fff",
                  fontWeight: 800,
                  fontSize: 12,
                }}
              >
                Q
              </div>
              <div>
                <div style={{ fontWeight: 700, color: TOKENS.ink2 }}>
                  QRS Certification System
                </div>
                <div>Generated automatically — {todayStr()}</div>
              </div>
            </div>
            <div style={{ textAlign: "right", fontFamily: "'IBM Plex Mono', monospace" }}>
              <div>Total analyzed: {fmt(stats.total)}</div>
              <div>Page 1 of 1</div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Print styles ── */}
      <style jsx global>{`
        @media print {
          .no-print {
            display: none !important;
          }
          body {
            background: #fff !important;
          }
          @page {
            size: A4;
            margin: 10mm;
          }
        }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Aggregation
// ═══════════════════════════════════════════════════════════════════════

interface NcStats {
  total: number;
  totalFindings: number;
  avgFindings: number;
  byNcType: { Major: number; Minor: number; Observation: number; Other: number };
  byStatus: { open: number; closed: number };
  bySource: { QRS: number; TQS: number };
  byAuditType: Record<string, number>;
  /** 🔹 NEW — KPI-friendly bucketed audit type counts */
  byAuditTypeCategory: { Initial: number; Surveillance: number; ReAssessment: number; Other: number };
  /** 🔹 NEW — Audit conduct card: three audit types */
  byAuditConduct: { Initial: number; Surveillance: number; Recertification: number };
  byCompany: Record<string, number>;
  byAuditor: Record<string, number>;
  openList: PreviousNcRow[];
  openWithoutEntries: PreviousNcRow[];
  aged30: number;
  aged60: number;
  aged90: number;
  last12MonthsIssued: { label: string; count: number; year: number; month: number }[];
}

function computeStats(ncs: PreviousNcRow[]): NcStats {
  const byNcType = { Major: 0, Minor: 0, Observation: 0, Other: 0 };
  const byStatus = { open: 0, closed: 0 };
  const bySource = { QRS: 0, TQS: 0 };
  const byAuditType: Record<string, number> = {};
  const byAuditTypeCategory = { Initial: 0, Surveillance: 0, ReAssessment: 0, Other: 0 }; // 🔹 NEW
  const byAuditConduct = { Initial: 0, Surveillance: 0, Recertification: 0 }; // 🔹 NEW
  const byCompany: Record<string, number> = {};
  const byAuditor: Record<string, number> = {};
  const openList: PreviousNcRow[] = [];
  const openWithoutEntries: PreviousNcRow[] = [];

  let totalFindings = 0;
  let aged30 = 0;
  let aged60 = 0;
  let aged90 = 0;

  const now = new Date();
  const last12: { label: string; count: number; year: number; month: number }[] = [];
  for (let i = 11; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    last12.push({
      label: `${monthName(d.getMonth())} ${String(d.getFullYear()).slice(2)}`,
      count: 0,
      year: d.getFullYear(),
      month: d.getMonth(),
    });
  }

  ncs.forEach((nc) => {
    const t = getNcType(nc).toLowerCase();
    if (t.includes("major")) byNcType.Major++;
    else if (t.includes("minor")) byNcType.Minor++;
    else if (t.includes("observ")) byNcType.Observation++;
    else byNcType.Other++;

    const st = getNcStatus(nc);
    if (st === "open") byStatus.open++;
    else if (st === "closed") byStatus.closed++;

    const src = getNcSource(nc);
    if (src === "QRS") bySource.QRS++;
    else if (src === "TQS") bySource.TQS++;

    const at = getNcAuditType(nc) || "Unknown";
    byAuditType[at] = (byAuditType[at] ?? 0) + 1;

    // 🔹 NEW — bucket the audit type into a KPI category
    const cat = classifyAuditType(at);
    byAuditTypeCategory[cat]++;

    // 🔹 NEW — audit conduct (Initial / Surveillance / Recertification)
    const av = at.toLowerCase();
    if (av.includes("initial")) byAuditConduct.Initial++;
    else if (av.includes("surveil")) byAuditConduct.Surveillance++;
    else if (
      av.includes("re-cert") || av.includes("recert") || av.includes("re certification") ||
      av.includes("re-assess") || av.includes("reassess")
    ) byAuditConduct.Recertification++;

    const co = getNcCompany(nc);
    if (co) byCompany[co] = (byCompany[co] ?? 0) + 1;

    const au = getNcAuditor(nc);
    if (au) byAuditor[au] = (byAuditor[au] ?? 0) + 1;

    const ec = getNcEntriesCount(nc);
    totalFindings += ec;

    if (st === "open") {
      openList.push(nc);
      if (ec === 0) openWithoutEntries.push(nc);

      const days = daysSince(nc.created_at);
      if (days >= 90) {
        aged30++;
        aged60++;
        aged90++;
      } else if (days >= 60) {
        aged30++;
        aged60++;
      } else if (days >= 30) {
        aged30++;
      }
    }

    if (nc.created_at) {
      const iss = new Date(nc.created_at);
      if (!isNaN(iss.getTime())) {
        const bucket = last12.find(
          (b) => b.year === iss.getFullYear() && b.month === iss.getMonth(),
        );
        if (bucket) bucket.count++;
      }
    }
  });

  openList.sort((a, b) => {
    const aTs = a.created_at ? new Date(a.created_at).getTime() : 0;
    const bTs = b.created_at ? new Date(b.created_at).getTime() : 0;
    return aTs - bTs;
  });

  return {
    total: ncs.length,
    totalFindings,
    avgFindings: ncs.length > 0 ? totalFindings / ncs.length : 0,
    byNcType,
    byStatus,
    bySource,
    byAuditType,
    byAuditTypeCategory, // 🔹 NEW
    byAuditConduct, // 🔹 NEW
    byCompany,
    byAuditor,
    openList,
    openWithoutEntries,
    aged30,
    aged60,
    aged90,
    last12MonthsIssued: last12,
  };
}

// ═══════════════════════════════════════════════════════════════════════
// Components
// ═══════════════════════════════════════════════════════════════════════

function LoadingState() {
  return (
    <div
      style={{
        minHeight: "60vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: TOKENS.bg,
      }}
    >
      <div style={{ textAlign: "center" }}>
        <div
          style={{
            width: 44,
            height: 44,
            border: `3px solid ${TOKENS.line}`,
            borderTopColor: TOKENS.brand,
            borderRadius: "50%",
            animation: "ncr-spin 0.7s linear infinite",
            margin: "0 auto 14px",
          }}
        />
        <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.ink3 }}>
          Loading NC analytics
        </div>
        <div style={{ fontSize: 11, color: TOKENS.ink5, marginTop: 4 }}>
          Aggregating data across QRS &amp; TQS databases…
        </div>
        <style>{`@keyframes ncr-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    </div>
  );
}

function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
  return (
    <div
      style={{
        minHeight: "60vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 40,
      }}
    >
      <div
        style={{
          maxWidth: 400,
          textAlign: "center",
          background: TOKENS.surface,
          padding: 32,
          borderRadius: TOKENS.rLg,
          boxShadow: TOKENS.shadow,
        }}
      >
        <AlertTriangle
          size={36}
          strokeWidth={2}
          color={TOKENS.danger}
          style={{ marginBottom: 8 }}
        />
        <h3 style={{ margin: "0 0 6px", color: TOKENS.ink, fontSize: 16 }}>
          Failed to load report
        </h3>
        <p style={{ color: TOKENS.ink4, fontSize: 13, margin: "0 0 16px" }}>
          {message}
        </p>
        <ActionButton onClick={onRetry} variant="primary">
          Try again
        </ActionButton>
      </div>
    </div>
  );
}

function ActionButton({
  children,
  onClick,
  variant,
  disabled,
}: {
  children: React.ReactNode;
  onClick: () => void;
  variant: "primary" | "secondary";
  disabled?: boolean;
}) {
  const isPrimary = variant === "primary";
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "9px 18px",
        background: isPrimary
          ? `linear-gradient(135deg, ${TOKENS.brand} 0%, ${TOKENS.brandLight} 100%)`
          : TOKENS.surface,
        color: isPrimary ? "#fff" : TOKENS.ink2,
        border: isPrimary ? "none" : `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        fontSize: 13,
        fontWeight: 700,
        cursor: disabled ? "wait" : "pointer",
        boxShadow: isPrimary
          ? "0 4px 12px rgba(15,118,110,0.25)"
          : TOKENS.shadow,
        opacity: disabled ? 0.6 : 1,
        transition: "all 0.15s",
        whiteSpace: "nowrap",
      }}
      onMouseEnter={(e) => {
        if (disabled) return;
        e.currentTarget.style.transform = "translateY(-1px)";
        e.currentTarget.style.boxShadow = isPrimary
          ? "0 8px 20px rgba(15,118,110,0.35)"
          : TOKENS.shadowLg;
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = "translateY(0)";
        e.currentTarget.style.boxShadow = isPrimary
          ? "0 4px 12px rgba(15,118,110,0.25)"
          : TOKENS.shadow;
      }}
    >
      {children}
    </button>
  );
}

// ─── Filter Bar ──────────────────────────────────────────────────────

type FilterOption = { value: string; count: number };

function FilterBar({
  options,
  filterSource,
  filterStatus,
  filterNcType,
  filterAuditType,
  filterAuditor,
  filterYear,
  filterMonth,
  onChangeSource,
  onChangeStatus,
  onChangeNcType,
  onChangeAuditType,
  onChangeAuditor,
  onChangeYear,
  onChangeMonth,
  onClear,
  totalAll,
  totalFiltered,
  hasActiveFilter,
}: {
  options: {
    sources: FilterOption[];
    statuses: FilterOption[];
    ncTypes: FilterOption[];
    auditTypes: FilterOption[];
    auditors: FilterOption[];
    years: FilterOption[];
    months: FilterOption[];
  };
  filterSource: string;
  filterStatus: string;
  filterNcType: string;
  filterAuditType: string;
  filterAuditor: string;
  filterYear: string;
  filterMonth: string;
  onChangeSource: (v: string) => void;
  onChangeStatus: (v: string) => void;
  onChangeNcType: (v: string) => void;
  onChangeAuditType: (v: string) => void;
  onChangeAuditor: (v: string) => void;
  onChangeYear: (v: string) => void;
  onChangeMonth: (v: string) => void;
  onClear: () => void;
  totalAll: number;
  totalFiltered: number;
  hasActiveFilter: boolean;
}) {
  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rLg,
        padding: "14px 18px",
        boxShadow: TOKENS.shadow,
        display: "flex",
        alignItems: "flex-end",
        gap: 12,
        flexWrap: "wrap",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 8,
          paddingBottom: 8,
          marginRight: 4,
        }}
      >
        <span
          style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: 26,
            height: 26,
            borderRadius: TOKENS.rSm,
            background: `${TOKENS.brand}12`,
            color: TOKENS.brand,
          }}
        >
          <FilterIcon size={13} strokeWidth={2} />
        </span>
        <span
          style={{
            fontSize: 11,
            fontWeight: 800,
            textTransform: "uppercase",
            letterSpacing: "0.08em",
            color: TOKENS.ink3,
          }}
        >
          Filters
        </span>
      </div>

      <FilterSelect
        label="Source"
        value={filterSource}
        onChange={onChangeSource}
        placeholder="All Sources"
        options={options.sources.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={130}
      />
      <FilterSelect
        label="Status"
        value={filterStatus}
        onChange={onChangeStatus}
        placeholder="All Statuses"
        options={options.statuses.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={130}
      />
      <FilterSelect
        label="NC Type"
        value={filterNcType}
        onChange={onChangeNcType}
        placeholder="All NC Types"
        options={options.ncTypes.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={150}
      />
      <FilterSelect
        label="Audit Type"
        value={filterAuditType}
        onChange={onChangeAuditType}
        placeholder="All Audit Types"
        options={options.auditTypes.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={200}
      />

      {/* 🔹 NEW — Auditor filter */}
      <FilterSelect
        label="Auditor"
        value={filterAuditor}
        onChange={onChangeAuditor}
        placeholder={`All Auditors${options.auditors.length > 0 ? ` (${options.auditors.length})` : ""}`}
        options={options.auditors.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={200}
        leadingIcon={<UserCheck size={11} strokeWidth={2.4} />}
      />

      <FilterSelect
        label="Year"
        value={filterYear}
        onChange={onChangeYear}
        placeholder="All Years"
        options={options.years.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={120}
      />
      <FilterSelect
        label="Month"
        value={filterMonth}
        onChange={onChangeMonth}
        placeholder="All Months"
        options={options.months.map((o) => ({
          value: o.value,
          label: `${formatMonthOption(o.value)} (${fmt(o.count)})`,
        }))}
        minWidth={170}
      />

      {hasActiveFilter && (
        <button
          onClick={onClear}
          style={{
            padding: "8px 14px",
            background: "transparent",
            border: `1px solid ${TOKENS.line}`,
            borderRadius: TOKENS.rSm,
            cursor: "pointer",
            fontSize: 12,
            fontWeight: 700,
            color: TOKENS.ink3,
            marginBottom: 0,
            height: 36,
            transition: "all 0.15s",
            display: "inline-flex",
            alignItems: "center",
            gap: 5,
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = TOKENS.danger;
            e.currentTarget.style.color = TOKENS.danger;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = TOKENS.line;
            e.currentTarget.style.color = TOKENS.ink3;
          }}
        >
          <XIcon size={11} strokeWidth={2.5} />
          Clear filters
        </button>
      )}

      <div
        style={{
          marginLeft: "auto",
          display: "flex",
          alignItems: "center",
          gap: 6,
          paddingBottom: 8,
        }}
      >
        <span
          style={{
            fontSize: 10,
            fontWeight: 700,
            color: TOKENS.ink5,
            textTransform: "uppercase",
            letterSpacing: 0.5,
          }}
        >
          Showing
        </span>
        <span
          style={{
            fontSize: 13,
            fontFamily: "'IBM Plex Mono', monospace",
            fontWeight: 800,
            color: hasActiveFilter ? TOKENS.brand : TOKENS.ink2,
          }}
        >
          {fmt(totalFiltered)}
        </span>
        <span style={{ fontSize: 11, color: TOKENS.ink5 }}>of {fmt(totalAll)}</span>
      </div>
    </div>
  );
}

function FilterSelect({
  label,
  value,
  onChange,
  options,
  placeholder,
  minWidth = 140,
  leadingIcon,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
  placeholder: string;
  minWidth?: number;
  leadingIcon?: React.ReactNode;
}) {
  const isActive = !!value;
  return (
    <label style={{ display: "inline-flex", flexDirection: "column", gap: 4 }}>
      <span
        style={{
          fontSize: 9,
          fontWeight: 800,
          color: TOKENS.ink5,
          textTransform: "uppercase",
          letterSpacing: "0.08em",
          display: "inline-flex",
          alignItems: "center",
          gap: 4,
        }}
      >
        {leadingIcon && (
          <span style={{ color: isActive ? TOKENS.brand : TOKENS.ink5, display: "inline-flex" }}>
            {leadingIcon}
          </span>
        )}
        {label}
      </span>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          appearance: "none",
          WebkitAppearance: "none",
          MozAppearance: "none",
          background: isActive ? `${TOKENS.brand}10` : TOKENS.surface,
          border: `1px solid ${isActive ? TOKENS.brand : TOKENS.line}`,
          borderRadius: TOKENS.rSm,
          padding: "8px 30px 8px 11px",
          fontSize: 12,
          fontWeight: 600,
          color: isActive ? TOKENS.brand : TOKENS.ink2,
          cursor: "pointer",
          minWidth,
          maxWidth: 240,
          height: 36,
          outline: "none",
          backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='${encodeURIComponent(
            isActive ? TOKENS.brand : TOKENS.ink4,
          )}' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'/></svg>")`,
          backgroundRepeat: "no-repeat",
          backgroundPosition: "right 9px center",
          textOverflow: "ellipsis",
          transition: "all 0.15s",
        }}
      >
        <option value="">{placeholder}</option>
        {options.length === 0 && (
          <option disabled value="">— no options —</option>
        )}
        {options.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {opt.label}
          </option>
        ))}
      </select>
    </label>
  );
}

function HeroFilterPill({ label, value }: { label: string; value: string }) {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 6,
        padding: "4px 10px",
        background: "rgba(94,234,212,0.12)",
        border: "1px solid rgba(94,234,212,0.35)",
        borderRadius: 999,
        fontSize: 11,
        fontWeight: 600,
        color: "#5eead4",
      }}
    >
      <span
        style={{
          fontSize: 9,
          fontWeight: 800,
          textTransform: "uppercase",
          letterSpacing: "0.08em",
          color: "rgba(94,234,212,0.7)",
        }}
      >
        {label}
      </span>
      <span style={{ color: "#fff" }}>{value}</span>
    </span>
  );
}

function MetaRow({ label, value }: { label: string; value: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 16 }}>
      <span style={{ color: "rgba(255,255,255,0.5)", fontWeight: 500 }}>
        {label}
      </span>
      <span
        style={{
          color: "#fff",
          fontWeight: 600,
          fontFamily: "'IBM Plex Mono', monospace",
          fontSize: 11,
        }}
      >
        {value}
      </span>
    </div>
  );
}

function SectionHeader({
  number,
  title,
  description,
  accent,
}: {
  number: string;
  title: string;
  description: string;
  accent?: string;
}) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4 }}>
        <span
          style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: 28,
            height: 28,
            background: accent ?? TOKENS.brand,
            color: "#fff",
            borderRadius: TOKENS.rSm,
            fontSize: 11,
            fontWeight: 800,
            fontFamily: "'IBM Plex Mono', monospace",
            letterSpacing: 0.5,
          }}
        >
          {number}
        </span>
        <h2
          style={{
            margin: 0,
            fontSize: 17,
            fontWeight: 800,
            color: TOKENS.ink,
            letterSpacing: "-0.01em",
          }}
        >
          {title}
        </h2>
      </div>
      <p
        style={{
          margin: "0 0 0 40px",
          fontSize: 12,
          color: TOKENS.ink4,
          lineHeight: 1.4,
        }}
      >
        {description}
      </p>
    </div>
  );
}

function KpiCard({
  label,
  value,
  sub,
  icon,
  accent,
  prominent,
}: {
  label: string;
  value: string;
  sub?: string;
  icon: React.ReactNode;
  accent: string;
  prominent?: boolean;
}) {
  return (
    <div
      style={{
        background: prominent
          ? `linear-gradient(135deg, ${TOKENS.ink} 0%, ${TOKENS.ink2} 100%)`
          : TOKENS.surface,
        border: prominent ? "none" : `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: "16px 18px",
        position: "relative",
        overflow: "hidden",
        color: prominent ? "#fff" : TOKENS.ink,
        minHeight: 100,
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
      }}
    >
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          height: 3,
          background: accent,
        }}
      />
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <span
          style={{
            fontSize: 11,
            fontWeight: 700,
            color: prominent ? "rgba(255,255,255,0.7)" : TOKENS.ink4,
            textTransform: "uppercase",
            letterSpacing: "0.06em",
          }}
        >
          {label}
        </span>
        <span
          style={{
            color: accent,
            opacity: 0.9,
            display: "inline-flex",
            alignItems: "center",
          }}
        >
          {icon}
        </span>
      </div>
      <div>
        <div
          style={{
            fontSize: prominent ? 32 : 26,
            fontWeight: 800,
            fontFamily: "'IBM Plex Mono', monospace",
            lineHeight: 1.05,
            letterSpacing: "-0.02em",
          }}
        >
          {value}
        </div>
        {sub && (
          <div
            style={{
              fontSize: 11,
              color: prominent ? "rgba(255,255,255,0.55)" : TOKENS.ink5,
              marginTop: 4,
              fontWeight: 600,
            }}
          >
            {sub} of total
          </div>
        )}
      </div>
    </div>
  );
}

function DonutCard({
  title,
  segments,
}: {
  title: string;
  segments: { label: string; value: number; color: string }[];
}) {
  const filtered = segments.filter((s) => s.value > 0);
  const sum = filtered.reduce((a, b) => a + b.value, 0);

  const size = 160;
  const stroke = 22;
  const r = (size - stroke) / 2;
  const cx = size / 2;
  const cy = size / 2;
  const circumference = 2 * Math.PI * r;

  let cumulativePct = 0;
  const arcs = filtered.map((s) => {
    const pctOf = (s.value / sum) * 100;
    const len = (pctOf / 100) * circumference;
    const offset = circumference * (cumulativePct / 100);
    cumulativePct += pctOf;
    return { ...s, len, offset, pctOf };
  });

  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: 20,
      }}
    >
      <div
        style={{
          fontSize: 13,
          fontWeight: 700,
          color: TOKENS.ink2,
          marginBottom: 16,
        }}
      >
        {title}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
        <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
          <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
            <circle
              cx={cx}
              cy={cy}
              r={r}
              fill="none"
              stroke={TOKENS.line2}
              strokeWidth={stroke}
            />
            {sum > 0 &&
              arcs.map((a, i) => (
                <circle
                  key={i}
                  cx={cx}
                  cy={cy}
                  r={r}
                  fill="none"
                  stroke={a.color}
                  strokeWidth={stroke}
                  strokeDasharray={`${a.len} ${circumference}`}
                  strokeDashoffset={-a.offset}
                  strokeLinecap="butt"
                />
              ))}
          </svg>
          <div
            style={{
              position: "absolute",
              inset: 0,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              textAlign: "center",
            }}
          >
            <div
              style={{
                fontSize: 22,
                fontWeight: 800,
                fontFamily: "'IBM Plex Mono', monospace",
                color: TOKENS.ink,
                lineHeight: 1,
              }}
            >
              {fmt(sum)}
            </div>
            <div
              style={{
                fontSize: 10,
                color: TOKENS.ink5,
                fontWeight: 600,
                marginTop: 2,
                textTransform: "uppercase",
                letterSpacing: 0.5,
              }}
            >
              Total
            </div>
          </div>
        </div>

        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map((s, i) => (
            <div
              key={i}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                fontSize: 12,
              }}
            >
              <span
                style={{
                  width: 10,
                  height: 10,
                  borderRadius: 3,
                  background: s.color,
                  flexShrink: 0,
                }}
              />
              <span style={{ flex: 1, color: TOKENS.ink2, fontWeight: 600 }}>
                {s.label}
              </span>
              <span
                style={{
                  fontFamily: "'IBM Plex Mono', monospace",
                  fontWeight: 700,
                  color: TOKENS.ink,
                }}
              >
                {fmt(s.value)}
              </span>
              <span
                style={{
                  fontFamily: "'IBM Plex Mono', monospace",
                  fontSize: 10,
                  color: TOKENS.ink5,
                  minWidth: 42,
                  textAlign: "right",
                }}
              >
                {pct(s.value, sum)}
              </span>
            </div>
          ))}
          {filtered.length === 0 && (
            <div style={{ fontSize: 12, color: TOKENS.ink5 }}>No data</div>
          )}
        </div>
      </div>
    </div>
  );
}

function DomainCard({
  flag,
  label,
  sublabel,
  count,
  total,
  accent,
}: {
  flag: React.ReactNode;
  label: string;
  sublabel: string;
  count: number;
  total: number;
  accent: string;
}) {
  const percent = pctNum(count, total);
  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: 20,
        position: "relative",
        overflow: "hidden",
      }}
    >
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: 4,
          height: "100%",
          background: accent,
        }}
      />
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 12 }}>
        <div
          style={{
            width: 44,
            height: 44,
            background: `${accent}12`,
            color: accent,
            borderRadius: TOKENS.rMd,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {flag}
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700, color: TOKENS.ink2 }}>
            {label}
          </div>
          <div
            style={{
              fontSize: 10,
              color: TOKENS.ink5,
              fontFamily: "'IBM Plex Mono', monospace",
              marginTop: 2,
            }}
          >
            {sublabel}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 8 }}>
        <span
          style={{
            fontSize: 28,
            fontWeight: 800,
            color: accent,
            fontFamily: "'IBM Plex Mono', monospace",
            lineHeight: 1,
          }}
        >
          {fmt(count)}
        </span>
        <span style={{ fontSize: 13, color: TOKENS.ink4, fontWeight: 600 }}>
          ({percent.toFixed(1)}%)
        </span>
      </div>
      <div
        style={{
          height: 6,
          background: TOKENS.line2,
          borderRadius: 3,
          overflow: "hidden",
        }}
      >
        <div
          style={{
            width: `${percent}%`,
            height: "100%",
            background: accent,
            transition: "width 0.5s",
          }}
        />
      </div>
    </div>
  );
}

function RankingCard({
  title,
  icon,
  rows,
  total,
  full,
}: {
  title: string;
  icon: React.ReactNode | null;
  rows: [string, number][];
  total: number;
  full?: boolean;
}) {
  const max = rows.length > 0 ? Math.max(...rows.map((r) => r[1])) : 1;
  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        overflow: "hidden",
      }}
    >
      {title && (
        <div
          style={{
            padding: "12px 16px",
            borderBottom: `1px solid ${TOKENS.line2}`,
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          {icon && (
            <span
              style={{
                display: "inline-flex",
                alignItems: "center",
                color: TOKENS.brand,
              }}
            >
              {icon}
            </span>
          )}
          <span style={{ fontSize: 13, fontWeight: 700, color: TOKENS.ink2 }}>
            {title}
          </span>
          <span style={{ marginLeft: "auto", fontSize: 11, color: TOKENS.ink5 }}>
            {rows.length} {rows.length === 1 ? "entry" : "entries"}
          </span>
        </div>
      )}
      <div>
        {rows.length === 0 ? (
          <div
            style={{
              padding: "32px 16px",
              textAlign: "center",
              fontSize: 12,
              color: TOKENS.ink5,
            }}
          >
            No data available
          </div>
        ) : (
          rows.map(([name, count], i) => {
            const widthPct = (count / max) * 100;
            return (
              <div
                key={i}
                style={{
                  padding: "10px 16px",
                  borderBottom:
                    i === rows.length - 1 ? "none" : `1px solid ${TOKENS.line2}`,
                  display: "grid",
                  gridTemplateColumns: full ? "32px 1fr 200px 60px 60px" : "28px 1fr 80px 50px",
                  alignItems: "center",
                  gap: 12,
                  fontSize: 12,
                }}
              >
                <span
                  style={{
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 10,
                    color: TOKENS.ink5,
                    fontWeight: 700,
                  }}
                >
                  #{i + 1}
                </span>
                <span
                  style={{
                    color: TOKENS.ink2,
                    fontWeight: 600,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                  title={name || "Unknown"}
                >
                  {name || "Unknown"}
                </span>
                {full && (
                  <div
                    style={{
                      height: 6,
                      background: TOKENS.line2,
                      borderRadius: 3,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        width: `${widthPct}%`,
                        height: "100%",
                        background: `linear-gradient(90deg, ${TOKENS.brand}, ${TOKENS.brandLight})`,
                      }}
                    />
                  </div>
                )}
                <span
                  style={{
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontWeight: 700,
                    color: TOKENS.ink,
                    textAlign: "right",
                  }}
                >
                  {fmt(count)}
                </span>
                <span
                  style={{
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 10,
                    color: TOKENS.ink5,
                    textAlign: "right",
                  }}
                >
                  {pct(count, total)}
                </span>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}

function AgeStat({
  label,
  count,
  accent,
}: {
  label: string;
  count: number;
  accent: string;
}) {
  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: "16px 18px",
        position: "relative",
        overflow: "hidden",
      }}
    >
      <div
        style={{
          position: "absolute",
          inset: 0,
          background: `linear-gradient(90deg, ${accent}08 0%, transparent 100%)`,
        }}
      />
      <div style={{ position: "relative" }}>
        <div
          style={{
            fontSize: 10,
            fontWeight: 700,
            color: TOKENS.ink4,
            textTransform: "uppercase",
            letterSpacing: "0.08em",
            marginBottom: 6,
          }}
        >
          {label}
        </div>
        <div
          style={{
            fontSize: 28,
            fontWeight: 800,
            color: accent,
            fontFamily: "'IBM Plex Mono', monospace",
            lineHeight: 1,
          }}
        >
          {fmt(count)}
        </div>
      </div>
    </div>
  );
}

function DataTable({
  headers,
  rows,
  footer,
  tone,
}: {
  headers: string[];
  rows: React.ReactNode[][];
  footer?: string;
  tone?: "warning" | "danger";
}) {
  const headerBg =
    tone === "warning" ? "#fffbeb" : tone === "danger" ? "#fef2f2" : TOKENS.line2;
  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        overflow: "hidden",
      }}
    >
      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr style={{ background: headerBg }}>
            {headers.map((h, i) => (
              <th
                key={i}
                style={{
                  padding: "10px 14px",
                  textAlign: "left",
                  fontSize: 10,
                  fontWeight: 800,
                  color: TOKENS.ink3,
                  textTransform: "uppercase",
                  letterSpacing: "0.06em",
                  borderBottom: `1px solid ${TOKENS.line}`,
                }}
              >
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr
              key={i}
              style={{
                borderBottom:
                  i === rows.length - 1 ? "none" : `1px solid ${TOKENS.line2}`,
              }}
            >
              {row.map((cell, j) => (
                <td
                  key={j}
                  style={{
                    padding: "11px 14px",
                    fontSize: 12,
                    color: TOKENS.ink2,
                  }}
                >
                  {cell}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      {footer && (
        <div
          style={{
            padding: "8px 14px",
            fontSize: 10,
            color: TOKENS.ink5,
            background: TOKENS.line2,
            fontWeight: 600,
          }}
        >
          {footer}
        </div>
      )}
    </div>
  );
}

function NcIdChip({ value }: { value: string }) {
  return (
    <span
      style={{
        display: "inline-block",
        fontFamily: "'IBM Plex Mono', monospace",
        fontSize: 11,
        fontWeight: 700,
        color: TOKENS.brand,
        background: `${TOKENS.brand}10`,
        padding: "3px 8px",
        borderRadius: TOKENS.rSm,
      }}
    >
      {value}
    </span>
  );
}

function SourceChip({ source }: { source: string }) {
  const upper = (source || "").toUpperCase();
  const color = upper === "TQS" ? TOKENS.tqs : TOKENS.qrs;
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 800,
        color,
        background: `${color}15`,
        padding: "2px 8px",
        borderRadius: TOKENS.rSm,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {upper || "—"}
    </span>
  );
}

function TypeChip({ type }: { type?: string }) {
  const t = (type ?? "").toLowerCase();
  const map: { bg: string; color: string; label: string } = t.includes("major")
    ? { bg: `${TOKENS.major}15`, color: TOKENS.major, label: "Major" }
    : t.includes("minor")
    ? { bg: `${TOKENS.minor}15`, color: TOKENS.minor, label: "Minor" }
    : t.includes("observ")
    ? { bg: `${TOKENS.observation}15`, color: TOKENS.observation, label: "Observation" }
    : { bg: TOKENS.line2, color: TOKENS.ink4, label: type ?? "—" };
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 700,
        color: map.color,
        background: map.bg,
        padding: "2px 8px",
        borderRadius: TOKENS.rSm,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {map.label}
    </span>
  );
}

function AgeChip({ days }: { days: number }) {
  const color =
    days >= 90 ? TOKENS.danger : days >= 60 ? "#ea580c" : days >= 30 ? "#d97706" : TOKENS.success;
  const bg =
    days >= 90 ? "#fee2e2" : days >= 60 ? "#ffedd5" : days >= 30 ? "#fef3c7" : "#dcfce7";
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        fontSize: 11,
        fontWeight: 700,
        color,
        background: bg,
        padding: "3px 9px",
        borderRadius: TOKENS.rSm,
        fontFamily: "'IBM Plex Mono', monospace",
      }}
    >
      <Clock size={10} strokeWidth={2.5} />
      {days}d
    </span>
  );
}

function EmptyState({
  icon,
  title,
  text,
  positive,
}: {
  icon: React.ReactNode;
  title: string;
  text: string;
  positive?: boolean;
}) {
  return (
    <div
      style={{
        background: positive ? "#f0fdf4" : TOKENS.surface,
        border: `1px dashed ${positive ? "#86efac" : TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: "28px 20px",
        textAlign: "center",
      }}
    >
      <div
        style={{
          width: 44,
          height: 44,
          borderRadius: "50%",
          background: positive ? TOKENS.success : TOKENS.ink5,
          color: "#fff",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          marginBottom: 10,
        }}
      >
        {icon}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, color: TOKENS.ink2 }}>
        {title}
      </div>
      <div style={{ fontSize: 12, color: TOKENS.ink4, marginTop: 4 }}>{text}</div>
    </div>
  );
}

function TrendChart({ data }: { data: { label: string; count: number }[] }) {
  const max = Math.max(...data.map((d) => d.count), 1);
  const chartHeight = 180;
  const yTicks = 4;

  return (
    <div
      style={{
        background: TOKENS.surface,
        border: `1px solid ${TOKENS.line}`,
        borderRadius: TOKENS.rMd,
        padding: 24,
      }}
    >
      <div style={{ display: "flex", gap: 12, alignItems: "stretch" }}>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            paddingBottom: 32,
            paddingTop: 4,
            fontSize: 10,
            fontFamily: "'IBM Plex Mono', monospace",
            color: TOKENS.ink5,
            textAlign: "right",
            minWidth: 28,
          }}
        >
          {Array.from({ length: yTicks + 1 }).map((_, i) => (
            <span key={i}>{Math.round((max * (yTicks - i)) / yTicks)}</span>
          ))}
        </div>

        <div style={{ flex: 1, position: "relative" }}>
          <div
            style={{
              position: "absolute",
              inset: `0 0 32px 0`,
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-between",
              pointerEvents: "none",
            }}
          >
            {Array.from({ length: yTicks + 1 }).map((_, i) => (
              <div
                key={i}
                style={{
                  height: 1,
                  background: i === yTicks ? TOKENS.ink5 : TOKENS.line2,
                }}
              />
            ))}
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: `repeat(${data.length}, 1fr)`,
              gap: 8,
              alignItems: "end",
              height: chartHeight,
              position: "relative",
            }}
          >
            {data.map((d, i) => {
              const h = (d.count / max) * (chartHeight - 16);
              return (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    gap: 4,
                    height: "100%",
                    justifyContent: "flex-end",
                  }}
                  title={`${d.label}: ${d.count} NCs`}
                >
                  {d.count > 0 && (
                    <span
                      style={{
                        fontSize: 10,
                        fontWeight: 700,
                        color: TOKENS.ink2,
                        fontFamily: "'IBM Plex Mono', monospace",
                      }}
                    >
                      {d.count}
                    </span>
                  )}
                  <div
                    style={{
                      width: "100%",
                      maxWidth: 36,
                      height: Math.max(h, d.count > 0 ? 6 : 2),
                      background:
                        d.count > 0
                          ? `linear-gradient(180deg, ${TOKENS.brandLight} 0%, ${TOKENS.brand} 100%)`
                          : TOKENS.line2,
                      borderRadius: "4px 4px 0 0",
                      transition: "height 0.4s",
                    }}
                  />
                </div>
              );
            })}
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: `repeat(${data.length}, 1fr)`,
              gap: 8,
              marginTop: 8,
              paddingTop: 6,
            }}
          >
            {data.map((d, i) => (
              <div
                key={i}
                style={{
                  fontSize: 10,
                  fontWeight: 600,
                  color: TOKENS.ink4,
                  textAlign: "center",
                  fontFamily: "'IBM Plex Mono', monospace",
                }}
              >
                {d.label}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}