"use client";
import React, { useEffect, useState, useMemo, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { getCertificatesPaginated } from "@/lib/api/certificate.api";
import type {
  CertificateRow,
  CertStatus,
  CertType,
} from "@/lib/api/types/certificate.types";

// ✅ NEW — Real icons (replacing all emojis)
import {
  ArrowLeft,
  RotateCw,
  Printer,
  Download,
  X as XIcon,
  AlertTriangle,
  ScrollText,
  Circle,
  CircleDot,
  CircleSlash,
  Diamond,
  Gem,
  Hexagon,
  Globe2,
  Building,
  Building2,
  ChevronRight,
  Filter as FilterIcon,
  Check,
  Hourglass,
} 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",

  // Type colors
  initial: "#6366f1",
  surveillance: "#06b6d4",
  recert: "#a855f7",

  // 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 todayShort = () =>
  new Date().toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    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) ──────────────────────
//
// The API returns `country`, `city`, and `company.certification_body` directly,
// but the mapper layer may rename / nest these. Each helper tries every
// reasonable path and accepts either a string or an object with `name`.

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();
};

/** Country, e.g. "United Arab Emirates" / "Pakistan" / "Vietnam". */
function getCertCountry(c: CertificateRow): string {
  const x: any = c;
  return (
    pickStr(x.country) ||
    pickStr(x.country_name) ||
    pickStr(x.companyCountry) ||
    pickStr(x.company?.country) ||
    pickStr(x.company?.country_name) ||
    ""
  );
}

/** City, e.g. "DUBAI" / "ABU DHABI" / "ISLAMABAD". */
function getCertCity(c: CertificateRow): string {
  const x: any = c;
  return (
    pickStr(x.city) ||
    pickStr(x.city_name) ||
    pickStr(x.companyCity) ||
    pickStr(x.company?.city) ||
    pickStr(x.company?.city_name) ||
    ""
  );
}

/** Certifying body — "QRS" / "TQS" / etc. — from company.certification_body. */
function getCertificationBody(c: CertificateRow): string {
  const x: any = c;
  const raw =
    pickStr(x.company?.certification_body) ||
    pickStr(x.certification_body) ||
    pickStr(x.certificationBody) ||
    pickStr(x.company?.certificationBody) ||
    "";
  return raw.toUpperCase();
}

/** Standard name e.g. "ISO 9001:2015". */
function getCertStandard(c: CertificateRow): string {
  const x: any = c;
  return (
    pickStr(x.standard?.name) ||
    pickStr(x.standard_name) ||
    pickStr(x.standard) ||
    ""
  );
}

/** "YYYY-MM" key from issue_date, or "" if missing/invalid. */
function getIssueYearMonth(c: CertificateRow): string {
  if (!c.issue_date) return "";
  const d = new Date(c.issue_date);
  if (isNaN(d.getTime())) return "";
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}

/** "YYYY" string from issue_date, or "" if missing/invalid. */
function getIssueYear(c: CertificateRow): string {
  if (!c.issue_date) return "";
  const d = new Date(c.issue_date);
  if (isNaN(d.getTime())) return "";
  return String(d.getFullYear());
}

/** "2024-03" → "Mar 2024" */
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 CertificateReportPage() {
  const router = useRouter();
  const reportRef = useRef<HTMLDivElement>(null);

  const [allCerts, setAllCerts] = useState<CertificateRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);

  // ─── Filters ─────────────────────────────────────────────────────────
  const [filterCompany, setFilterCompany] = useState<string>(""); // certification_body e.g. "QRS"
  const [filterCountry, setFilterCountry] = useState<string>("");
  const [filterCity, setFilterCity] = useState<string>("");
  const [filterYear, setFilterYear] = useState<string>(""); // "YYYY"
  const [filterMonth, setFilterMonth] = useState<string>(""); // "YYYY-MM"

  // Fetch all
  //
  // IMPORTANT: We deliberately do NOT pass the response through
  // `mapCertificatesApiResponse` here. The raw API row already carries
  // every field this report needs (`country`, `city`, `company.certification_body`,
  // `standard.name`, `cert_type`, `status`, `issue_date`, `expire_date`, etc.),
  // and the mapper was stripping/renaming `country`, `city`, and
  // `certification_body`, which made the filter dropdowns empty.
  const fetchAllCertificates = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const first = await getCertificatesPaginated({ page: 1 });
      let all: CertificateRow[] = (first.data ?? []) as unknown as CertificateRow[];
      const lastPage = Math.min(first.lastPage ?? 1, 200);
      if (lastPage > 1) {
        const rest = await Promise.all(
          Array.from({ length: lastPage - 1 }, (_, i) =>
            getCertificatesPaginated({ page: i + 2 }).then(
              (r) => (r.data ?? []) as unknown as CertificateRow[],
            ),
          ),
        );
        rest.forEach((batch) => (all = all.concat(batch)));
      }
      setAllCerts(all);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load certificates");
    } finally {
      setLoading(false);
    }
  }, []);

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

  // ─── Filter dropdown options (built from the FULL dataset) ───────────
  const filterOptions = useMemo(() => {
    const countries = new Map<string, number>();
    const cities = new Map<string, number>();
    const companies = new Map<string, number>();
    const years = new Map<string, number>();
    const months = new Map<string, number>();

    allCerts.forEach((c) => {
      const country = getCertCountry(c);
      if (country) countries.set(country, (countries.get(country) ?? 0) + 1);

      const city = getCertCity(c);
      if (city) cities.set(city, (cities.get(city) ?? 0) + 1);

      const body = getCertificationBody(c);
      if (body) companies.set(body, (companies.get(body) ?? 0) + 1);

      const yr = getIssueYear(c);
      if (yr) years.set(yr, (years.get(yr) ?? 0) + 1);

      const ym = getIssueYearMonth(c);
      if (ym) 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 {
      countries: Array.from(countries.entries()).sort(byNameAsc).map(([v, n]) => ({ value: v, count: n })),
      cities: Array.from(cities.entries()).sort(byNameAsc).map(([v, n]) => ({ value: v, count: n })),
      companies: Array.from(companies.entries()).sort(byCountDesc).map(([v, n]) => ({ value: v, count: n })),
      years: Array.from(years.entries())
        .sort((a, b) => b[0].localeCompare(a[0])) // newest year first
        .map(([v, n]) => ({ value: v, count: n })),
      months: Array.from(months.entries())
        .sort((a, b) => b[0].localeCompare(a[0])) // newest first
        .map(([v, n]) => ({ value: v, count: n })),
    };
  }, [allCerts]);

  // ─── Apply filters ───────────────────────────────────────────────────
  const filteredCerts = useMemo(() => {
    if (
      !filterCompany &&
      !filterCountry &&
      !filterCity &&
      !filterYear &&
      !filterMonth
    ) {
      return allCerts;
    }
    return allCerts.filter((c) => {
      if (filterCompany && getCertificationBody(c) !== filterCompany) return false;
      if (filterCountry && getCertCountry(c) !== filterCountry) return false;
      if (filterCity && getCertCity(c) !== filterCity) return false;
      if (filterYear && getIssueYear(c) !== filterYear) return false;
      if (filterMonth && getIssueYearMonth(c) !== filterMonth) return false;
      return true;
    });
  }, [allCerts, filterCompany, filterCountry, filterCity, filterYear, filterMonth]);

  const hasActiveFilter =
    !!(filterCompany || filterCountry || filterCity || filterYear || filterMonth);

  const clearFilters = () => {
    setFilterCompany("");
    setFilterCountry("");
    setFilterCity("");
    setFilterYear("");
    setFilterMonth("");
  };

  // Stats now computed on FILTERED data so every section reflects filters
  const stats = useMemo(() => computeStats(filteredCerts), [filteredCerts]);

  // 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 renders EVERY CSS gradient by drawing it onto an
        // offscreen canvas and calling createPattern(thatCanvas, "repeat").
        // When that tile computes to 0×0 (a known bug with repeating
        // radial-gradient textures and certain gradient stops), it throws
        // "createPattern ... width or height of 0" and the whole capture aborts.
        //
        // We can't rely on getComputedStyle here — clonedDoc.defaultView is
        // null at onclone time in this html2canvas build, so the previous
        // approach silently did nothing. Instead we read each cloned node's
        // INLINE style string (all styles in this report are inline) and swap
        // every gradient for its first solid color. No gradient survives into
        // the capture → createPattern is never called → no crash. The live UI
        // is untouched; only the throwaway clone is modified.
        onclone: (clonedDoc: Document) => {
          const firstColor = (str: string): string | null => {
            const m = str.match(/#[0-9a-fA-F]{3,8}|rgba?\([^)]*\)/);
            return m ? m[0] : null;
          };
          clonedDoc.querySelectorAll<HTMLElement>("[style]").forEach((el) => {
            const s = el.getAttribute("style") || "";
            if (!s.includes("gradient")) return;

            // Decorative repeating radial texture → purely cosmetic, drop it.
            if (s.includes("radial-gradient")) {
              el.style.backgroundImage = "none";
              return;
            }

            // Any linear gradient → replace with its first solid color so the
            // card/bar/hero keeps a sensible fill but no pattern is generated.
            const c = firstColor(s.slice(s.indexOf("gradient")));
            el.style.backgroundImage = "none";
            if (c) el.style.backgroundColor = c;
          });
        },
      });

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

      // ✅ corrected filename (was nc-report-...)
      pdf.save(`certificate-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={fetchAllCertificates} />;

  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 Certificates
        </button>

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <ActionButton onClick={fetchAllCertificates} 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}
          filterCompany={filterCompany}
          filterCountry={filterCountry}
          filterCity={filterCity}
          filterYear={filterYear}
          filterMonth={filterMonth}
          onChangeCompany={setFilterCompany}
          onChangeCountry={setFilterCountry}
          onChangeCity={setFilterCity}
          onChangeYear={setFilterYear}
          onChangeMonth={setFilterMonth}
          onClear={clearFilters}
          totalAll={allCerts.length}
          totalFiltered={filteredCerts.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",
          }}
        >
          {/* Decorative grid */}
          <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,
                  }}
                >
                  Certificate 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 certificate issuance, status
                  distribution, geographic spread, and pending operations across
                  all standards and verification domains.
                </p>

                {/* Active filters chip strip — visible in PDF/print */}
                {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>
                    {filterCompany && (
                      <HeroFilterPill label="Cert Body" value={filterCompany} />
                    )}
                    {filterCountry && (
                      <HeroFilterPill label="Country" value={filterCountry} />
                    )}
                    {filterCity && (
                      <HeroFilterPill label="City" value={filterCity} />
                    )}
                    {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(allCerts.length)}`
                      : fmt(stats.total)
                  }
                />
                <MetaRow label="Document ID" value={`QRS-RPT-${Date.now().toString().slice(-6)}`} />
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: "32px 40px 40px" }}>
          {/* ── 1. EXECUTIVE SUMMARY ── */}
          <SectionHeader
            number="01"
            title="Executive Summary"
            description={
              hasActiveFilter
                ? "Headline metrics across the filtered subset of the certificate portfolio"
                : "Headline metrics across the entire certificate portfolio"
            }
          />

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 20,
            }}
          >
            <KpiCard
              label="Total Certificates"
              value={fmt(stats.total)}
              icon={<ScrollText size={14} strokeWidth={2} />}
              accent={TOKENS.brand}
              prominent
            />
            <KpiCard
              label="Active"
              value={fmt(stats.byStatus.active)}
              sub={pct(stats.byStatus.active, stats.total)}
              icon={<Circle size={14} strokeWidth={2} fill="currentColor" />}
              accent={TOKENS.success}
            />
            <KpiCard
              label="Pending Scan"
              value={fmt(stats.byStatus.pending_scan)}
              sub={pct(stats.byStatus.pending_scan, stats.total)}
              icon={<CircleDot size={14} strokeWidth={2} />}
              accent={TOKENS.warning}
            />
            <KpiCard
              label="Expired"
              value={fmt(stats.byStatus.expired)}
              sub={pct(stats.byStatus.expired, stats.total)}
              icon={<Circle size={14} strokeWidth={2} />}
              accent={TOKENS.danger}
            />
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 36,
            }}
          >
            <KpiCard
              label="Initial Issuance"
              value={fmt(stats.byType.INITIAL)}
              sub={pct(stats.byType.INITIAL, stats.total)}
              icon={<Diamond size={14} strokeWidth={2} />}
              accent={TOKENS.initial}
            />
            <KpiCard
              label="Surveillance"
              value={fmt(stats.byType.SURVEILLANCE)}
              sub={pct(stats.byType.SURVEILLANCE, stats.total)}
              icon={<Hexagon size={14} strokeWidth={2} />}
              accent={TOKENS.surveillance}
            />
            <KpiCard
              label="Recertification"
              value={fmt(stats.byType.RECERTIFICATION)}
              sub={pct(stats.byType.RECERTIFICATION, stats.total)}
              icon={<Diamond size={14} strokeWidth={2} fill="currentColor" />}
              accent={TOKENS.recert}
            />
            <KpiCard
              label="Revoked"
              value={fmt(stats.byStatus.revoked)}
              sub={pct(stats.byStatus.revoked, stats.total)}
              icon={<XIcon size={14} strokeWidth={2.5} />}
              accent={TOKENS.ink4}
            />
          </div>

          {/* Empty-after-filter guard */}
          {hasActiveFilter && stats.total === 0 ? (
            <EmptyState
              icon={<CircleSlash size={20} strokeWidth={2} />}
              title="No certificates match the selected filters"
              text="Adjust or clear the filters above to see report data."
            />
          ) : (
            <>
              {/* ── 2. DUAL DONUT CHARTS ── */}
              <SectionHeader
                number="02"
                title="Distribution Analysis"
                description="Type & status breakdown shown as proportional segments"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <DonutCard
                  title="By Certificate Type"
                  segments={[
                    {
                      label: "Initial",
                      value: stats.byType.INITIAL,
                      color: TOKENS.initial,
                    },
                    {
                      label: "Surveillance",
                      value: stats.byType.SURVEILLANCE,
                      color: TOKENS.surveillance,
                    },
                    {
                      label: "Recertification",
                      value: stats.byType.RECERTIFICATION,
                      color: TOKENS.recert,
                    },
                  ]}
                  total={stats.total}
                />
                <DonutCard
                  title="By Status"
                  segments={[
                    {
                      label: "Active",
                      value: stats.byStatus.active,
                      color: TOKENS.success,
                    },
                    {
                      label: "Pending Scan",
                      value: stats.byStatus.pending_scan,
                      color: TOKENS.warning,
                    },
                    {
                      label: "Superseded",
                      value: stats.byStatus.superseded,
                      color: TOKENS.ink5,
                    },
                    {
                      label: "Expired",
                      value: stats.byStatus.expired,
                      color: TOKENS.danger,
                    },
                    {
                      label: "Revoked",
                      value: stats.byStatus.revoked,
                      color: TOKENS.ink3,
                    },
                  ]}
                  total={stats.total}
                />
              </div>

              {/* ── 3. VERIFICATION DOMAIN ── */}
              <SectionHeader
                number="03"
                title="Verification Domain"
                description="Split between local and international verification endpoints"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 14,
                  marginBottom: 36,
                }}
              >
                <DomainCard
                  flag={<Building size={22} strokeWidth={2} />}
                  label="Local Verification"
                  sublabel="qrsyst.com"
                  count={stats.byDomain.local}
                  total={stats.total}
                  accent={TOKENS.brand}
                />
                <DomainCard
                  flag={<Globe2 size={22} strokeWidth={2} />}
                  label="International Verification"
                  sublabel="qrs-intl.com"
                  count={stats.byDomain.international}
                  total={stats.total}
                  accent={TOKENS.info}
                />
              </div>

              {/* ── 4. GEOGRAPHIC ── */}
              <SectionHeader
                number="04"
                title="Geographic Distribution"
                description="Top countries and cities by certificate count"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <RankingCard
                  title="Top Countries"
                  icon={<Globe2 size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byCountry)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
                <RankingCard
                  title="Top Cities"
                  icon={<Building2 size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byCity)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
              </div>

              {/* ── 5. STANDARDS ── */}
              <SectionHeader
                number="05"
                title="ISO Standards Breakdown"
                description="Certificate count across each ISO standard"
              />
              <RankingCard
                title=""
                icon={null}
                rows={Object.entries(stats.byStandard)
                  .sort((a, b) => b[1] - a[1])
                  .slice(0, 12)}
                total={stats.total}
                full
              />

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

              {/* ── 6. PENDING SCANS ── */}
              <SectionHeader
                number="06"
                title="Pending Digital Certificate Scans"
                description={`${stats.pendingScans.length} certificate(s) awaiting scan upload — these are not publicly verifiable until scans are attached`}
                accent={TOKENS.warning}
              />
              {stats.pendingScans.length === 0 ? (
                <EmptyState
                  icon={<Check size={20} strokeWidth={2.5} />}
                  title="All scans uploaded"
                  text="Every issued certificate has its scan attached and is ready for verification."
                  positive
                />
              ) : (
                <DataTable
                  headers={["Cert No", "Company", "Standard", "Type", "Issued"]}
                  rows={stats.pendingScans.slice(0, 25).map((c) => [
                    <CertChip key={c.certificate_no} value={c.certificate_no} />,
                    c.company?.name ?? "—",
                    c.standard?.name ?? "—",
                    <TypeChip key={c.id} type={c.cert_type} />,
                    formatDate(c.issue_date),
                  ])}
                  footer={
                    stats.pendingScans.length > 25
                      ? `Showing first 25 of ${stats.pendingScans.length} pending`
                      : undefined
                  }
                  tone="warning"
                />
              )}

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

              {/* ── 7. EXPIRY ── */}
              <SectionHeader
                number="07"
                title="Expiring Soon"
                description="Forward-looking expiry windows for renewal planning"
                accent={TOKENS.danger}
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3, 1fr)",
                  gap: 12,
                  marginBottom: 16,
                }}
              >
                <ExpiryStat label="Next 30 Days" count={stats.expiring30} accent={TOKENS.danger} />
                <ExpiryStat label="Next 60 Days" count={stats.expiring60} accent="#ea580c" />
                <ExpiryStat label="Next 90 Days" count={stats.expiring90} accent="#d97706" />
              </div>

              {stats.expiringList.length === 0 ? (
                <EmptyState
                  icon={<Check size={20} strokeWidth={2.5} />}
                  title="No upcoming expirations"
                  text="No certificates expire within the next 90 days."
                  positive
                />
              ) : (
                <DataTable
                  headers={["Cert No", "Company", "Standard", "Expires", "Days Left"]}
                  rows={stats.expiringList.slice(0, 25).map((c) => {
                    const daysLeft = c.expire_date
                      ? Math.ceil(
                        (new Date(c.expire_date).getTime() - Date.now()) /
                        (1000 * 60 * 60 * 24),
                      )
                      : 0;
                    return [
                      <CertChip key={c.certificate_no} value={c.certificate_no} />,
                      c.company?.name ?? "—",
                      c.standard?.name ?? "—",
                      formatDate(c.expire_date),
                      <DaysChip key={c.id} days={daysLeft} />,
                    ];
                  })}
                  footer={
                    stats.expiringList.length > 25
                      ? `Showing first 25 of ${stats.expiringList.length} expiring soon`
                      : undefined
                  }
                  tone="danger"
                />
              )}

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

              {/* ── 8. ISSUANCE TREND ── */}
              <SectionHeader
                number="08"
                title="Issuance Trend"
                description="Monthly certificate issuance 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
// ═══════════════════════════════════════════════════════════════════════

function computeStats(certs: CertificateRow[]) {
  const byType: Record<CertType, number> = {
    INITIAL: 0,
    SURVEILLANCE: 0,
    RECERTIFICATION: 0,
  };
  const byStatus: Record<CertStatus | "other", number> = {
    pending_scan: 0,
    active: 0,
    superseded: 0,
    expired: 0,
    revoked: 0,
    fake: 0,
    other: 0,
  };
  const byDomain = { local: 0, international: 0 };
  const byCountry: Record<string, number> = {};
  const byStandard: Record<string, number> = {};
  const byCity: Record<string, number> = {};
  const pendingScans: CertificateRow[] = [];
  const expiringList: CertificateRow[] = [];

  let expiring30 = 0;
  let expiring60 = 0;
  let expiring90 = 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(),
    });
  }

  const dayMs = 1000 * 60 * 60 * 24;
  const nowTs = now.getTime();

  certs.forEach((c) => {
    const t = (c.cert_type || "").toUpperCase() as CertType;
    if (t in byType) byType[t]++;

    const s = (c.status || "").toLowerCase();
    if (s in byStatus) (byStatus as any)[s]++;
    else byStatus.other++;

    const d = c.verification_domain;
    if (d === "local") byDomain.local++;
    else if (d === "international") byDomain.international++;

    // Use the SAME defensive helpers as the filters so the report and
    // dropdowns are always in sync.
    const country = getCertCountry(c);
    if (country) byCountry[country] = (byCountry[country] ?? 0) + 1;

    const stdName = getCertStandard(c);
    if (stdName) byStandard[stdName] = (byStandard[stdName] ?? 0) + 1;

    const city = getCertCity(c);
    if (city) byCity[city] = (byCity[city] ?? 0) + 1;

    if (!(c as any).scan_pdf_url && (s === "pending_scan" || !s)) {
      pendingScans.push(c);
    }

    if (c.expire_date) {
      const expTs = new Date(c.expire_date).getTime();
      const daysLeft = Math.ceil((expTs - nowTs) / dayMs);
      if (daysLeft >= 0 && daysLeft <= 90) {
        if (daysLeft <= 30) expiring30++;
        if (daysLeft <= 60) expiring60++;
        expiring90++;
        expiringList.push(c);
      }
    }

    if (c.issue_date) {
      const iss = new Date(c.issue_date);
      const bucket = last12.find(
        (b) => b.year === iss.getFullYear() && b.month === iss.getMonth(),
      );
      if (bucket) bucket.count++;
    }
  });

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

  return {
    total: certs.length,
    byType,
    byStatus,
    byDomain,
    byCountry,
    byStandard,
    byCity,
    pendingScans,
    expiringList,
    expiring30,
    expiring60,
    expiring90,
    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: "spin 0.7s linear infinite",
            margin: "0 auto 14px",
          }}
        />
        <div style={{ fontSize: 13, fontWeight: 600, color: TOKENS.ink3 }}>
          Loading certificate data
        </div>
        <div style={{ fontSize: 11, color: TOKENS.ink5, marginTop: 4 }}>
          Aggregating analytics across all certificates…
        </div>
        <style>{`@keyframes 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,
  filterCompany,
  filterCountry,
  filterCity,
  filterYear,
  filterMonth,
  onChangeCompany,
  onChangeCountry,
  onChangeCity,
  onChangeYear,
  onChangeMonth,
  onClear,
  totalAll,
  totalFiltered,
  hasActiveFilter,
}: {
  options: {
    companies: FilterOption[];
    countries: FilterOption[];
    cities: FilterOption[];
    years: FilterOption[];
    months: FilterOption[];
  };
  filterCompany: string;
  filterCountry: string;
  filterCity: string;
  filterYear: string;
  filterMonth: string;
  onChangeCompany: (v: string) => void;
  onChangeCountry: (v: string) => void;
  onChangeCity: (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="Cert. Body"
        value={filterCompany}
        onChange={onChangeCompany}
        placeholder="All Bodies"
        options={options.companies.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={140}
      />
      <FilterSelect
        label="Country"
        value={filterCountry}
        onChange={onChangeCountry}
        placeholder="All Countries"
        options={options.countries.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={170}
      />
      <FilterSelect
        label="City"
        value={filterCity}
        onChange={onChangeCity}
        placeholder="All Cities"
        options={options.cities.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={170}
      />
      <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,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
  placeholder: string;
  minWidth?: number;
}) {
  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",
        }}
      >
        {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,
          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",
          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,
  total,
}: {
  title: string;
  segments: { label: string; value: number; color: string }[];
  total: number;
}) {
  const filtered = segments.filter((s) => s.value > 0);
  const sum = filtered.reduce((a, b) => a + b.value, 0);

  // Build SVG arc segments
  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 ExpiryStat({
  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 CertChip({ 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 TypeChip({ type }: { type?: string }) {
  const t = (type ?? "").toUpperCase();
  const map: Record<string, { bg: string; color: string; label: string }> = {
    INITIAL: { bg: `${TOKENS.initial}15`, color: TOKENS.initial, label: "Initial" },
    SURVEILLANCE: {
      bg: `${TOKENS.surveillance}15`,
      color: TOKENS.surveillance,
      label: "Surveillance",
    },
    RECERTIFICATION: {
      bg: `${TOKENS.recert}15`,
      color: TOKENS.recert,
      label: "Recert",
    },
  };
  const s = map[t] ?? { bg: TOKENS.line2, color: TOKENS.ink4, label: type ?? "—" };
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 700,
        color: s.color,
        background: s.bg,
        padding: "2px 8px",
        borderRadius: TOKENS.rSm,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {s.label}
    </span>
  );
}

function DaysChip({ days }: { days: number }) {
  const color = days <= 30 ? TOKENS.danger : days <= 60 ? "#ea580c" : "#d97706";
  const bg = days <= 30 ? "#fee2e2" : days <= 60 ? "#ffedd5" : "#fef3c7";
  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",
      }}
    >
      {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",
        }}
      >
        {/* Y axis */}
        <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>

        {/* Chart area */}
        <div style={{ flex: 1, position: "relative" }}>
          {/* Grid lines */}
          <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>

          {/* Bars */}
          <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} certificates`}
                >
                  {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>

          {/* X labels */}
          <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>
  );
}