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

import {
  ArrowLeft,
  RotateCw,
  Printer,
  Download,
  X as XIcon,
  AlertTriangle,
  ChevronRight,
  ChevronDown,
  Filter as FilterIcon,
  Hourglass,
  ClipboardCheck,
  FileCheck2,
  FileX2,
  UserCheck,
  Users as UsersIcon,
  Building,
  Globe2,
  Calendar,
  CircleSlash,
  Layers,
  Repeat,
} from "lucide-react";

// ═══════════════════════════════════════════════════════════════════════
// Design Tokens (identical to NcReportPage)
// ═══════════════════════════════════════════════════════════════════════
const TOKENS = {
  brand: "#0f766e",
  brandLight: "#14b8a6",
  brandDark: "#0d544c",
  ink: "#0b1220",
  ink2: "#1f2937",
  ink3: "#475569",
  ink4: "#64748b",
  ink5: "#94a3b8",
  line: "#e2e8f0",
  line2: "#f1f5f9",
  bg: "#f6f8fa",
  surface: "#ffffff",
  success: "#16a34a",
  warning: "#f59e0b",
  danger: "#dc2626",
  info: "#2563eb",
  qrs: "#6366f1",
  tqs: "#06b6d4",
  initial: "#8b5cf6",
  surveillance: "#0891b2",
  reassessment: "#db2777",
  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)",
};

const monthName = (m: number) =>
  ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][m];
const fmt = (n: number) => (n ?? 0).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);
const todayStr = () =>
  new Date().toLocaleDateString("en-GB", { day: "2-digit", month: "long", year: "numeric" });

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}`;
}

// ═══════════════════════════════════════════════════════════════════════
// Page
// ═══════════════════════════════════════════════════════════════════════
export default function AuditAssignReportPage() {
  const router = useRouter();
  const reportRef = useRef<HTMLDivElement>(null);

  const [data, setData] = useState<AuditAssignReportResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);

  const [filterSource, setFilterSource] = useState<string>("");
  const [filterAuditor, setFilterAuditor] = useState<string>("");
  const [filterYear, setFilterYear] = useState<string>("");   // e.g. "2026"
  const [filterMonthNum, setFilterMonthNum] = useState<string>(""); // e.g. "03"
  const [expanded, setExpanded] = useState<Set<string>>(new Set());

  // Combined "YYYY-MM" key used everywhere internally. Only set when BOTH
  // year and month are chosen (otherwise we filter by year-only, see below).
  // Human label for the chosen period: "Mar 2026", "2026", "Mar (all years)" or "All Time".
  const periodLabel =
    filterYear && filterMonthNum
      ? `${monthName(parseInt(filterMonthNum, 10) - 1)} ${filterYear}`
      : filterYear
        ? filterYear
        : filterMonthNum
          ? `${monthName(parseInt(filterMonthNum, 10) - 1)} (all years)`
          : "All Time";

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await getAuditAssignReport();
      setData(res);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load audit-assign report");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const rows = data?.rows ?? [];

  // ─── Build filter dropdown options (cascading) ───────────────────────
  // Each dropdown's options exclude the filter it is FOR, but respect the
  // others. So picking Database=QRS narrows the Auditor list to QRS auditors.
  const filterOptions = useMemo(() => {
    const sources = new Map<string, number>();
    const auditors = new Map<string, number>();
    const years = new Map<string, number>();        // "2026" -> assigned
    const monthNums = new Map<string, number>();     // "03"   -> assigned

    const sourceOk = (r: AuditAssignRow) => !filterSource || r.source === filterSource;
    const auditorOk = (r: AuditAssignRow) => !filterAuditor || r.auditor === filterAuditor;

    rows.forEach((r) => {
      // Sources list: narrowed by auditor (not by itself).
      if (auditorOk(r)) sources.set(r.source, (sources.get(r.source) ?? 0) + 1);

      // Auditors list: narrowed by selected database (not by itself).
      if (sourceOk(r)) auditors.set(r.auditor, (auditors.get(r.auditor) ?? 0) + r.total_assigned);

      // Year / Month lists: narrowed by source + auditor (not by date).
      if (sourceOk(r) && auditorOk(r)) {
        r.months.forEach((m) => {
          const [y, mm] = m.month.split("-");
          if (y) years.set(y, (years.get(y) ?? 0) + m.total_assigned);
          if (mm) monthNums.set(mm, (monthNums.get(mm) ?? 0) + m.total_assigned);
        });
      }
    });

    return {
      sources: Array.from(sources.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([v, n]) => ({ value: v, count: n })),
      auditors: Array.from(auditors.entries()).sort((a, b) => b[1] - a[1]).map(([v, n]) => ({ value: v, count: n })),
      // Years: newest first. Only real 4-digit years (skip junk like "0202").
      years: Array.from(years.entries())
        .filter(([y]) => /^\d{4}$/.test(y) && Number(y) >= 2000 && Number(y) <= 2100)
        .sort((a, b) => b[0].localeCompare(a[0]))
        .map(([v, n]) => ({ value: v, count: n })),
      // Months Jan→Dec, always all 12 in order regardless of data.
      monthNums: Array.from({ length: 12 }, (_, i) => {
        const mm = String(i + 1).padStart(2, "0");
        return { value: mm, count: monthNums.get(mm) ?? 0 };
      }),
    };
  }, [rows, filterSource, filterAuditor]);

  // If the chosen auditor isn't available under the current database filter,
  // clear it so the dropdown doesn't show a stale, empty selection.
  useEffect(() => {
    if (filterAuditor && !filterOptions.auditors.some((a) => a.value === filterAuditor)) {
      setFilterAuditor("");
    }
  }, [filterOptions.auditors, filterAuditor]);

  // ─── Apply filters (source + auditor; date re-scopes each row) ───────
  const dateActive = !!(filterYear || filterMonthNum);
  const filteredRows = useMemo(() => {
    let base = rows.filter((r) => {
      if (filterSource && r.source !== filterSource) return false;
      if (filterAuditor && r.auditor !== filterAuditor) return false;
      return true;
    });

    if (dateActive) {
      // Decide which of a row's months match the chosen year / month-of-year.
      const monthMatches = (ym: string) => {
        const [y, mm] = ym.split("-");
        if (filterYear && y !== filterYear) return false;
        if (filterMonthNum && mm !== filterMonthNum) return false;
        return true;
      };

      base = base
        .map((r) => {
          const ms = r.months.filter((x) => monthMatches(x.month));
          if (ms.length === 0) return null;

          // Sum all matching months into one re-scoped row.
          const sum = ms.reduce(
            (a, m) => ({
              total_assigned: a.total_assigned + m.total_assigned,
              stage1_uploaded: a.stage1_uploaded + m.stage1_uploaded,
              stage2_uploaded: a.stage2_uploaded + m.stage2_uploaded,
              initial: a.initial + (m.initial ?? 0),
              surveillance: a.surveillance + (m.surveillance ?? 0),
              recertification: a.recertification + (m.recertification ?? 0),
            }),
            { total_assigned: 0, stage1_uploaded: 0, stage2_uploaded: 0, initial: 0, surveillance: 0, recertification: 0 },
          );
          const s1miss = Math.max(0, sum.total_assigned - sum.stage1_uploaded);
          const s2miss = Math.max(0, sum.total_assigned - sum.stage2_uploaded);
          return {
            ...r,
            total_assigned: sum.total_assigned,
            stage1_uploaded: sum.stage1_uploaded,
            stage1_missing: s1miss,
            stage2_uploaded: sum.stage2_uploaded,
            stage2_missing: s2miss,
            initial: sum.initial,
            surveillance: sum.surveillance,
            recertification: sum.recertification,
            months: ms.slice().sort((a, b) => a.month.localeCompare(b.month)),
          } as AuditAssignRow;
        })
        .filter((x): x is AuditAssignRow => x !== null);
    }

    return base.sort((a, b) => b.total_assigned - a.total_assigned);
  }, [rows, filterSource, filterAuditor, filterYear, filterMonthNum, dateActive]);

  const hasActiveFilter = !!(filterSource || filterAuditor || filterYear || filterMonthNum);
  const clearFilters = () => {
    setFilterSource("");
    setFilterAuditor("");
    setFilterYear("");
    setFilterMonthNum("");
  };

  // ─── Aggregate stats from filtered rows ──────────────────────────────
  const stats = useMemo(() => {
    const totals = {
      total_assigned: 0,
      stage1_uploaded: 0,
      stage1_missing: 0,
      stage2_uploaded: 0,
      stage2_missing: 0,
      initial: 0,
      surveillance: 0,
      recertification: 0,
    };
    const bySource = { QRS: 0, TQS: 0 };
    const monthMap = new Map<string, number>();

    filteredRows.forEach((r) => {
      totals.total_assigned += r.total_assigned;
      totals.stage1_uploaded += r.stage1_uploaded;
      totals.stage1_missing += r.stage1_missing;
      totals.stage2_uploaded += r.stage2_uploaded;
      totals.stage2_missing += r.stage2_missing;
      totals.initial += r.initial ?? 0;
      totals.surveillance += r.surveillance ?? 0;
      totals.recertification += r.recertification ?? 0;
      if (r.source === "QRS") bySource.QRS += r.total_assigned;
      else if (r.source === "TQS") bySource.TQS += r.total_assigned;
      r.months.forEach((m) => monthMap.set(m.month, (monthMap.get(m.month) ?? 0) + m.total_assigned));
    });

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

    const topAuditors = filteredRows
      .map((r) => [r.auditor, r.total_assigned] as [string, number])
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10);

    return { totals, bySource, last12, topAuditors, auditorCount: filteredRows.length };
  }, [filteredRows]);

  const toggleRow = (key: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  };

  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" });
      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;
      }
      pdf.save(`audit-assign-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={fetchData} />;

  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 */}
      <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={fetchData} 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 */}
      <div className="no-print" style={{ maxWidth: 1240, margin: "0 auto 20px" }}>
        <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="Database"
            value={filterSource}
            onChange={setFilterSource}
            placeholder="All Databases"
            options={filterOptions.sources.map((o) => ({ value: o.value, label: o.value }))}
            minWidth={150}
          />
          <FilterSelect
            label="Auditor"
            value={filterAuditor}
            onChange={setFilterAuditor}
            placeholder={`All Auditors${filterOptions.auditors.length ? ` (${filterOptions.auditors.length})` : ""}`}
            options={filterOptions.auditors.map((o) => ({ value: o.value, label: o.value }))}
            minWidth={220}
            leadingIcon={<UserCheck size={11} strokeWidth={2.4} />}
          />
          <FilterSelect
            label="Year"
            value={filterYear}
            onChange={setFilterYear}
            placeholder="All Years"
            options={filterOptions.years.map((o) => ({ value: o.value, label: o.value }))}
            minWidth={120}
            leadingIcon={<Calendar size={11} strokeWidth={2.4} />}
          />
          <FilterSelect
            label="Month"
            value={filterMonthNum}
            onChange={setFilterMonthNum}
            placeholder="All Months"
            options={filterOptions.monthNums.map((o) => ({ value: o.value, label: monthName(parseInt(o.value, 10) - 1) }))}
            minWidth={150}
            leadingIcon={<Calendar size={11} strokeWidth={2.4} />}
          />

          {hasActiveFilter && (
            <button
              onClick={clearFilters}
              style={{ padding: "8px 14px", background: "transparent", border: `1px solid ${TOKENS.line}`, borderRadius: TOKENS.rSm, cursor: "pointer", fontSize: 12, fontWeight: 700, color: TOKENS.ink3, height: 36, display: "inline-flex", alignItems: "center", gap: 5, transition: "all 0.15s" }}
              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 }}>Auditors</span>
            <span style={{ fontSize: 13, fontFamily: "'IBM Plex Mono', monospace", fontWeight: 800, color: hasActiveFilter ? TOKENS.brand : TOKENS.ink2 }}>{fmt(filteredRows.length)}</span>
            <span style={{ fontSize: 11, color: TOKENS.ink5 }}>of {fmt(rows.length)}</span>
          </div>
        </div>
      </div>

      {/* Report body */}
      <div ref={reportRef} style={{ maxWidth: 1240, margin: "0 auto", background: TOKENS.surface, borderRadius: TOKENS.rLg, boxShadow: TOKENS.shadow, overflow: "hidden" }}>
        {/* Hero */}
        <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} />Audit Assignment 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 }}>
                  Auditor Assignment
                  <br />
                  <span style={{ color: "#5eead4" }}>& Report Status</span>
                </h1>
                <p style={{ margin: "12px 0 0", fontSize: 14, color: "rgba(255,255,255,0.72)", lineHeight: 1.5, maxWidth: 540 }}>
                  Per-auditor breakdown of audits assigned, with stage-1 and
                  stage-2 report upload status (uploaded vs missing) across the
                  QRS and TQS databases, plus a month-by-month split.
                </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="Database" value={filterSource} />}
                    {filterAuditor && <HeroFilterPill label="Auditor" value={filterAuditor} />}
                    {filterYear && <HeroFilterPill label="Year" value={filterYear} />}
                    {filterMonthNum && <HeroFilterPill label="Month" value={monthName(parseInt(filterMonthNum, 10) - 1)} />}
                  </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={periodLabel} />
                <MetaRow label="Auditors" value={hasActiveFilter ? `${fmt(filteredRows.length)} of ${fmt(rows.length)}` : fmt(rows.length)} />
                <MetaRow label="Total Assigned" value={fmt(stats.totals.total_assigned)} />
                <MetaRow label="Document ID" value={`AA-RPT-${Date.now().toString().slice(-6)}`} />
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: "32px 40px 40px" }}>
          {/* 01 — EXECUTIVE SUMMARY */}
          <SectionHeader number="01" title={filterAuditor ? `Executive Summary — ${filterAuditor}` : "Executive Summary"} description={filterAuditor ? `Headline metrics for ${filterAuditor}${filterSource ? ` (${filterSource})` : ""}${periodLabel !== "All Time" ? ` · ${periodLabel}` : ""}` : (hasActiveFilter ? "Headline metrics across the filtered subset" : "Headline metrics across all auditors")} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 14 }}>
            <KpiCard label="Total Assigned" value={fmt(stats.totals.total_assigned)} icon={<ClipboardCheck size={14} strokeWidth={2} />} accent={TOKENS.brand} prominent />
            <KpiCard label="Auditors" value={fmt(stats.auditorCount)} icon={<UsersIcon size={14} strokeWidth={2} />} accent={TOKENS.info} />
            <KpiCard label="Avg / Auditor" value={stats.auditorCount > 0 ? (stats.totals.total_assigned / stats.auditorCount).toFixed(1) : "0"} icon={<UserCheck size={14} strokeWidth={2} />} accent={TOKENS.warning} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 36 }}>
            <KpiCard label="Stage 1 Uploaded" value={fmt(stats.totals.stage1_uploaded)} sub={pct(stats.totals.stage1_uploaded, stats.totals.total_assigned)} icon={<FileCheck2 size={14} strokeWidth={2} />} accent={TOKENS.success} />
            <KpiCard label="Stage 1 Missing" value={fmt(stats.totals.stage1_missing)} sub={pct(stats.totals.stage1_missing, stats.totals.total_assigned)} icon={<FileX2 size={14} strokeWidth={2} />} accent={TOKENS.danger} />
            <KpiCard label="Stage 2 Uploaded" value={fmt(stats.totals.stage2_uploaded)} sub={pct(stats.totals.stage2_uploaded, stats.totals.total_assigned)} icon={<FileCheck2 size={14} strokeWidth={2} />} accent={TOKENS.success} />
            <KpiCard label="Stage 2 Missing" value={fmt(stats.totals.stage2_missing)} sub={pct(stats.totals.stage2_missing, stats.totals.total_assigned)} icon={<FileX2 size={14} strokeWidth={2} />} accent={TOKENS.danger} />
          </div>

          {/* 01b — AUDIT CONDUCT (Initial / Surveillance / Recertification) */}
          <SectionHeader number="01b" title="Audit Conduct" description="Initial counts audits performed (by audit date). Surveillance & Recertification count by their scheduled due date — so they may be 0 for a given month or fall in future months." />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 12 }}>
            <KpiCard label="Initial (performed)" value={fmt(stats.totals.initial)} sub={pct(stats.totals.initial, stats.totals.total_assigned)} icon={<ClipboardCheck size={14} strokeWidth={2} />} accent={TOKENS.initial} />
            <KpiCard label="Surveillance (due)" value={fmt(stats.totals.surveillance)} icon={<Layers size={14} strokeWidth={2} />} accent={TOKENS.surveillance} />
            <KpiCard label="Recertification (due)" value={fmt(stats.totals.recertification)} icon={<Repeat size={14} strokeWidth={2} />} accent={TOKENS.reassessment} />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 14px", background: `${TOKENS.info}08`, border: `1px solid ${TOKENS.info}22`, borderRadius: TOKENS.rSm, marginBottom: 36, fontSize: 11.5, color: TOKENS.ink3, lineHeight: 1.4 }}>
            <AlertTriangle size={14} strokeWidth={2.2} color={TOKENS.info} style={{ flexShrink: 0 }} />
            <span><strong style={{ color: TOKENS.ink2 }}>Initial</strong> = audits done. <strong style={{ color: TOKENS.ink2 }}>Surveillance / Recertification</strong> = counted by due date (often future), so 0 here just means none due this month.</span>
          </div>

          {filteredRows.length === 0 ? (
            <EmptyState icon={<CircleSlash size={20} strokeWidth={2} />} title="No auditors match the selected filters" text="Adjust or clear the filters above to see report data." />
          ) : (
            <>
              {/* 02 — REPORT STATUS DONUTS */}
              <SectionHeader number="02" title="Report Upload Status" description="Stage-1 and stage-2 report completion shown as proportional segments" />
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 36 }}>
                <DonutCard title="Stage 1 Reports" segments={[
                  { label: "Uploaded", value: stats.totals.stage1_uploaded, color: TOKENS.success },
                  { label: "Missing", value: stats.totals.stage1_missing, color: TOKENS.danger },
                ]} />
                <DonutCard title="Stage 2 Reports" segments={[
                  { label: "Uploaded", value: stats.totals.stage2_uploaded, color: TOKENS.success },
                  { label: "Missing", value: stats.totals.stage2_missing, color: TOKENS.danger },
                ]} />
              </div>

              {/* 03 — SOURCE SPLIT */}
              <SectionHeader number="03" title="Source Database Split" description="Assigned audits distributed 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.totals.total_assigned} accent={TOKENS.qrs} />
                <DomainCard flag={<Globe2 size={22} strokeWidth={2} />} label="TQS Database" sublabel="tqs.qrsyst.com" count={stats.bySource.TQS} total={stats.totals.total_assigned} accent={TOKENS.tqs} />
              </div>

              {/* 04 — TOP AUDITORS */}
              <SectionHeader number="04" title="Top Auditors by Assignment" description="Auditors handling the most assigned audits" />
              <RankingCard title="" icon={null} rows={stats.topAuditors} total={stats.totals.total_assigned} full />
              <div style={{ height: 36 }} />

              {/* 05 — FULL TABLE */}
              <SectionHeader number="05" title="Per-Auditor Breakdown" description="Click any row to expand the month-by-month detail" />
              <div style={{ border: `1px solid ${TOKENS.line}`, borderRadius: TOKENS.rMd, overflow: "hidden", marginBottom: 36 }}>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead>
                    <tr style={{ background: TOKENS.line2 }}>
                      <th style={th}></th>
                      <th style={th}>Auditor</th>
                      <th style={th}>DB</th>
                      <th style={{ ...th, textAlign: "right" }}>Assigned</th>
                      <th style={{ ...th, textAlign: "right" }}>S1 Up</th>
                      <th style={{ ...th, textAlign: "right" }}>S1 Miss</th>
                      <th style={{ ...th, textAlign: "right" }}>S2 Up</th>
                      <th style={{ ...th, textAlign: "right" }}>S2 Miss</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredRows.map((r) => {
                      const key = `${r.source}:${r.user_id}`;
                      const isOpen = expanded.has(key);
                      return (
                        <React.Fragment key={key}>
                          <tr onClick={() => r.months.length > 0 && toggleRow(key)} style={{ borderBottom: `1px solid ${TOKENS.line2}`, cursor: r.months.length > 0 ? "pointer" : "default", background: isOpen ? `${TOKENS.brand}06` : "transparent" }}>
                            <td style={{ ...td, width: 34, color: TOKENS.ink5 }}>
                              {r.months.length > 0 ? (isOpen ? <ChevronDown size={15} /> : <ChevronRight size={15} />) : null}
                            </td>
                            <td style={{ ...td, fontWeight: 700, color: TOKENS.ink2 }}>
                              <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
                                <UserCheck size={13} strokeWidth={2.2} color={TOKENS.brand} />
                                {r.auditor}
                                <span style={{ fontSize: 10, color: TOKENS.ink5, fontWeight: 600 }}>#{r.user_id}</span>
                              </span>
                            </td>
                            <td style={td}><SourceChip source={r.source} /></td>
                            <td style={{ ...td, textAlign: "right", fontWeight: 800, fontFamily: "'IBM Plex Mono', monospace", color: TOKENS.ink }}>{fmt(r.total_assigned)}</td>
                            <td style={numCell(TOKENS.success)}>{fmt(r.stage1_uploaded)}</td>
                            <td style={numCell(r.stage1_missing > 0 ? TOKENS.danger : TOKENS.ink5)}>{fmt(r.stage1_missing)}</td>
                            <td style={numCell(TOKENS.success)}>{fmt(r.stage2_uploaded)}</td>
                            <td style={numCell(r.stage2_missing > 0 ? TOKENS.danger : TOKENS.ink5)}>{fmt(r.stage2_missing)}</td>
                          </tr>
                          {isOpen && r.months.length > 0 && (
                            <tr>
                              <td colSpan={8} style={{ padding: 0, background: TOKENS.bg }}>
                                <div style={{ padding: "10px 16px 14px 50px" }}>
                                  <div style={{ fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.06em", color: TOKENS.ink4, marginBottom: 8, display: "inline-flex", alignItems: "center", gap: 6 }}>
                                    <Calendar size={11} strokeWidth={2.2} />Monthly breakdown
                                  </div>
                                  <table style={{ width: "100%", borderCollapse: "collapse", background: TOKENS.surface, border: `1px solid ${TOKENS.line}`, borderRadius: TOKENS.rSm, overflow: "hidden" }}>
                                    <thead>
                                      <tr style={{ background: TOKENS.line2 }}>
                                        <th style={subTh}>Month</th>
                                        <th style={{ ...subTh, textAlign: "right" }}>Assigned</th>
                                        <th style={{ ...subTh, textAlign: "right" }}>S1 Uploaded</th>
                                        <th style={{ ...subTh, textAlign: "right" }}>S2 Uploaded</th>
                                      </tr>
                                    </thead>
                                    <tbody>
                                      {r.months.map((m) => (
                                        <tr key={m.month} style={{ borderBottom: `1px solid ${TOKENS.line2}` }}>
                                          <td style={subTd}>{formatMonthOption(m.month)}</td>
                                          <td style={{ ...subTd, textAlign: "right", fontWeight: 700, fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(m.total_assigned)}</td>
                                          <td style={{ ...subTd, textAlign: "right", fontFamily: "'IBM Plex Mono', monospace", color: TOKENS.success }}>{fmt(m.stage1_uploaded)}</td>
                                          <td style={{ ...subTd, textAlign: "right", fontFamily: "'IBM Plex Mono', monospace", color: TOKENS.success }}>{fmt(m.stage2_uploaded)}</td>
                                        </tr>
                                      ))}
                                    </tbody>
                                  </table>
                                </div>
                              </td>
                            </tr>
                          )}
                        </React.Fragment>
                      );
                    })}
                  </tbody>
                  <tfoot>
                    <tr style={{ background: TOKENS.ink, color: "#fff" }}>
                      <td style={td}></td>
                      <td style={{ ...td, color: "#fff", fontWeight: 800 }}>TOTAL</td>
                      <td style={td}></td>
                      <td style={{ ...td, textAlign: "right", color: "#fff", fontWeight: 800, fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(stats.totals.total_assigned)}</td>
                      <td style={{ ...td, textAlign: "right", color: "#86efac", fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(stats.totals.stage1_uploaded)}</td>
                      <td style={{ ...td, textAlign: "right", color: "#fca5a5", fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(stats.totals.stage1_missing)}</td>
                      <td style={{ ...td, textAlign: "right", color: "#86efac", fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(stats.totals.stage2_uploaded)}</td>
                      <td style={{ ...td, textAlign: "right", color: "#fca5a5", fontFamily: "'IBM Plex Mono', monospace" }}>{fmt(stats.totals.stage2_missing)}</td>
                    </tr>
                  </tfoot>
                </table>
              </div>

              {/* 06 — TREND */}
              <SectionHeader number="06" title="Assignment Trend" description="Audits assigned per month over the last 12 months" />
              <TrendChart data={stats.last12} />
            </>
          )}

          {/* 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>Auditors: {fmt(filteredRows.length)}</div>
              <div>Total assigned: {fmt(stats.totals.total_assigned)}</div>
            </div>
          </div>
        </div>
      </div>

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

// ═══════════════════════════════════════════════════════════════════════
// Shared cell styles
// ═══════════════════════════════════════════════════════════════════════
const th: React.CSSProperties = { padding: "10px 14px", textAlign: "left", fontSize: 10, fontWeight: 800, color: TOKENS.ink3, textTransform: "uppercase", letterSpacing: "0.06em", borderBottom: `1px solid ${TOKENS.line}` };
const td: React.CSSProperties = { padding: "11px 14px", fontSize: 12, color: TOKENS.ink2 };
const numCell = (color: string): React.CSSProperties => ({ padding: "11px 14px", fontSize: 12, textAlign: "right", fontFamily: "'IBM Plex Mono', monospace", fontWeight: 700, color });
const subTh: React.CSSProperties = { padding: "7px 12px", textAlign: "left", fontSize: 9, fontWeight: 800, color: TOKENS.ink4, textTransform: "uppercase", letterSpacing: "0.05em", borderBottom: `1px solid ${TOKENS.line2}` };
const subTd: React.CSSProperties = { padding: "7px 12px", fontSize: 11, color: TOKENS.ink3 };

// ═══════════════════════════════════════════════════════════════════════
// Components (visual parity with NcReportPage)
// ═══════════════════════════════════════════════════════════════════════
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>
  );
}

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",
          backgroundColor: isActive ? `${TOKENS.brand}10` : TOKENS.surface,
          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",
          backgroundSize: "12px 12px",
          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: 280,
          height: 36,
          outline: "none",
          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 assigned</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, stroke = 22;
  const r = (size - stroke) / 2, cx = size / 2, 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 };
  });
  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 SourceChip({ source }: { source: 'QRS' | 'TQS' | 'QRS & TQS' }) {
  const color = source === "TQS" ? TOKENS.tqs : TOKENS.qrs;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, fontWeight: 800, color, background: `${color}15`, padding: "2px 8px", borderRadius: TOKENS.rSm, textTransform: "uppercase", letterSpacing: 0.4 }}>
      {source === "TQS" ? <Globe2 size={10} strokeWidth={2.4} /> : <Building size={10} strokeWidth={2.4} />}
      {source}
    </span>
  );
}

function TrendChart({ data }: { data: { label: string; count: number }[] }) {
  const max = Math.max(...data.map((d) => d.count), 1);
  const chartHeight = 180, 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} assigned`}>
                  {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>
  );
}

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: "aa-spin 0.7s linear infinite", margin: "0 auto 14px" }} />
        <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.ink3 }}>Loading audit-assign report</div>
        <div style={{ fontSize: 11, color: TOKENS.ink5, marginTop: 4 }}>Aggregating across QRS &amp; TQS databases…</div>
        <style>{`@keyframes aa-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 EmptyState({ icon, title, text }: { icon: React.ReactNode; title: string; text: string; }) {
  return (
    <div style={{ background: TOKENS.surface, border: `1px dashed ${TOKENS.line}`, borderRadius: TOKENS.rMd, padding: "28px 20px", textAlign: "center" }}>
      <div style={{ width: 44, height: 44, borderRadius: "50%", background: 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>
  );
}