"use client";
import React, { useEffect, useState, useMemo, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { getAllJobs } from "@/lib/api/job.api";
import { mapJobsApiResponse } from "@/lib/api/mappers/job.mappers";
import type { JobRow } from "@/lib/api/types/job.types";

import {
  ArrowLeft,
  RotateCw,
  Printer,
  Download,
  X as XIcon,
  AlertTriangle,
  Briefcase,
  Layers,
  ShieldAlert,
  ShieldCheck,
  Shield,
  Circle,
  CircleDot,
  CircleSlash,
  Users,
  UserCheck,
  Building2 as Building2Icon,
  ChevronRight,
  Filter as FilterIcon,
  Hourglass,
  Search as SearchIcon,
  ScrollText,
  Award,
  ClipboardList,
  FileText,
  Calendar,
} from "lucide-react";

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

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",
  initial: "#6366f1",
  surveillance: "#06b6d4",
  recert: "#a855f7",
  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)",
};

// ═══════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════

const ALL_MONTHS: { value: string; label: string; short: string }[] = [
  { value: "01", label: "January", short: "Jan" },
  { value: "02", label: "February", short: "Feb" },
  { value: "03", label: "March", short: "Mar" },
  { value: "04", label: "April", short: "Apr" },
  { value: "05", label: "May", short: "May" },
  { value: "06", label: "June", short: "Jun" },
  { value: "07", label: "July", short: "Jul" },
  { value: "08", label: "August", short: "Aug" },
  { value: "09", label: "September", short: "Sep" },
  { value: "10", label: "October", short: "Oct" },
  { value: "11", label: "November", short: "Nov" },
  { value: "12", label: "December", short: "Dec" },
];

const STAGE_OPTIONS = ["Stage 1", "Stage 2"];
const RISK_OPTIONS = ["Low", "Medium", "High"];

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

const monthNameShort = (m: number) => ALL_MONTHS[m]?.short ?? "";
const monthLabel = (n: string) => {
  const i = parseInt(n, 10) - 1;
  if (i < 0 || i > 11 || isNaN(i)) return n;
  return ALL_MONTHS[i].label;
};

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

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

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

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",
  });
}

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

// ─── Date helpers (use j.raw?.createdAt) ─────────────────────────────

function getJobCreatedDate(j: JobRow): Date | null {
  const raw = (j as any)?.raw?.createdAt ?? (j as any)?.raw?.created_at ?? (j as any)?.createdAt;
  if (!raw) return null;
  const d = new Date(raw);
  return isNaN(d.getTime()) ? null : d;
}

function getJobYear(j: JobRow): string {
  const d = getJobCreatedDate(j);
  return d ? String(d.getFullYear()) : "";
}

function getJobMonth(j: JobRow): string {
  const d = getJobCreatedDate(j);
  return d ? String(d.getMonth() + 1).padStart(2, "0") : "";
}

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

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

  const [allJobs, setAllJobs] = useState<JobRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState(false);

  // ─── Filters ─────────────────────────────────────────────────────────
  const [filterSearch, setFilterSearch] = useState<string>("");
  const [filterStage, setFilterStage] = useState<string>("");
  const [filterRisk, setFilterRisk] = useState<string>("");
  const [filterAuditor, setFilterAuditor] = useState<string>("");
  const [filterStandard, setFilterStandard] = useState<string>("");
  const [filterYear, setFilterYear] = useState<string>("");
  const [filterMonth, setFilterMonth] = useState<string>("");

  const fetchAllJobs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getAllJobs();
      setAllJobs(mapJobsApiResponse(data));
    } catch (err: any) {
      setError(err?.message ?? "Failed to load jobs");
    } finally {
      setLoading(false);
    }
  }, []);

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

  // ─── Filter dropdown options ─────────────────────────────────────────
  const filterOptions = useMemo(() => {
    const auditors = new Map<string, number>();
    const standards = new Map<string, number>();
    const stages = new Map<string, number>();
    const risks = new Map<string, number>();
    const yearSet = new Set<string>();
    const monthCounts: Record<string, number> = {};

    allJobs.forEach((j) => {
      const auditor = pickStr(j.leadAuditor);
      if (auditor) auditors.set(auditor, (auditors.get(auditor) ?? 0) + 1);

      if (Array.isArray(j.standards)) {
        j.standards.forEach((s: any) => {
          const sn = pickStr(typeof s === "object" ? s.name : s);
          if (sn) standards.set(sn, (standards.get(sn) ?? 0) + 1);
        });
      }

      const stage = pickStr(j.stage);
      if (stage) stages.set(stage, (stages.get(stage) ?? 0) + 1);

      const risk = pickStr(j.mdRisk);
      if (risk) risks.set(risk, (risks.get(risk) ?? 0) + 1);

      const yr = getJobYear(j);
      if (yr) yearSet.add(yr);

      const mo = getJobMonth(j);
      if (mo) monthCounts[mo] = (monthCounts[mo] ?? 0) + 1;
    });

    const currentYear = new Date().getFullYear();
    yearSet.add(String(currentYear));
    const years = Array.from(yearSet).sort((a, b) => b.localeCompare(a));

    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 {
      auditors: Array.from(auditors.entries())
        .sort(byCountDesc)
        .map(([v, n]) => ({ value: v, count: n })),
      standards: Array.from(standards.entries())
        .sort(byCountDesc)
        .map(([v, n]) => ({ value: v, count: n })),
      stages: Array.from(stages.entries())
        .sort(byNameAsc)
        .map(([v, n]) => ({ value: v, count: n })),
      risks: Array.from(risks.entries())
        .sort(byNameAsc)
        .map(([v, n]) => ({ value: v, count: n })),
      years,
      monthCounts,
    };
  }, [allJobs]);

  // ─── Apply filters ───────────────────────────────────────────────────
  const filteredJobs = useMemo(() => {
    if (
      !filterSearch &&
      !filterStage &&
      !filterRisk &&
      !filterAuditor &&
      !filterStandard &&
      !filterYear &&
      !filterMonth
    ) {
      return allJobs;
    }
    const q = filterSearch.trim().toLowerCase();
    return allJobs.filter((j) => {
      if (q) {
        const hay = [
          pickStr(j.companyName),
          pickStr(j.leadAuditor),
          pickStr(j.templateName),
          ...(Array.isArray(j.jobCodes) ? j.jobCodes : []),
        ]
          .join(" ")
          .toLowerCase();
        if (!hay.includes(q)) return false;
      }
      if (filterStage && pickStr(j.stage) !== filterStage) return false;
      if (filterRisk && pickStr(j.mdRisk) !== filterRisk) return false;
      if (filterAuditor && pickStr(j.leadAuditor) !== filterAuditor) return false;
      if (filterStandard) {
        const has = Array.isArray(j.standards)
          ? j.standards.some((s: any) =>
              pickStr(typeof s === "object" ? s.name : s) === filterStandard,
            )
          : false;
        if (!has) return false;
      }
      if (filterYear && getJobYear(j) !== filterYear) return false;
      if (filterMonth && getJobMonth(j) !== filterMonth) return false;
      return true;
    });
  }, [
    allJobs,
    filterSearch,
    filterStage,
    filterRisk,
    filterAuditor,
    filterStandard,
    filterYear,
    filterMonth,
  ]);

  const hasActiveFilter = !!(
    filterSearch ||
    filterStage ||
    filterRisk ||
    filterAuditor ||
    filterStandard ||
    filterYear ||
    filterMonth
  );

  const clearFilters = () => {
    setFilterSearch("");
    setFilterStage("");
    setFilterRisk("");
    setFilterAuditor("");
    setFilterStandard("");
    setFilterYear("");
    setFilterMonth("");
  };

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

  // 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",
      });
      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(`job-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);
    }
  };

  const reportingPeriod = (() => {
    if (filterYear && filterMonth) return `${monthLabel(filterMonth)} ${filterYear}`;
    if (filterYear) return filterYear;
    if (filterMonth) return `${monthLabel(filterMonth)} (all years)`;
    return "All Time";
  })();

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

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

        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <ActionButton onClick={fetchAllJobs} 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" }}>
        <FilterBar
          options={filterOptions}
          filterSearch={filterSearch}
          filterStage={filterStage}
          filterRisk={filterRisk}
          filterAuditor={filterAuditor}
          filterStandard={filterStandard}
          filterYear={filterYear}
          filterMonth={filterMonth}
          onChangeSearch={setFilterSearch}
          onChangeStage={setFilterStage}
          onChangeRisk={setFilterRisk}
          onChangeAuditor={setFilterAuditor}
          onChangeStandard={setFilterStandard}
          onChangeYear={setFilterYear}
          onChangeMonth={setFilterMonth}
          onClear={clearFilters}
          totalAll={allJobs.length}
          totalFiltered={filteredJobs.length}
          hasActiveFilter={hasActiveFilter}
        />
      </div>

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

            <div
              style={{
                display: "flex",
                alignItems: "flex-start",
                justifyContent: "space-between",
                flexWrap: "wrap",
                gap: 24,
              }}
            >
              <div style={{ flex: "1 1 400px" }}>
                <h1
                  style={{
                    margin: 0,
                    fontSize: 32,
                    fontWeight: 800,
                    letterSpacing: "-0.025em",
                    lineHeight: 1.15,
                  }}
                >
                  Job Registrar
                  <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 all registered audit jobs across
                  stages, risk levels, lead auditors, ISO standards coverage,
                  and registration trends over time.
                </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>
                    {filterSearch && (
                      <HeroFilterPill label="Search" value={`"${filterSearch}"`} />
                    )}
                    {filterStage && (
                      <HeroFilterPill label="Stage" value={filterStage} />
                    )}
                    {filterRisk && (
                      <HeroFilterPill label="Risk" value={filterRisk} />
                    )}
                    {filterAuditor && (
                      <HeroFilterPill label="Auditor" value={filterAuditor} />
                    )}
                    {filterStandard && (
                      <HeroFilterPill label="Standard" value={filterStandard} />
                    )}
                    {filterYear && (
                      <HeroFilterPill label="Year" value={filterYear} />
                    )}
                    {filterMonth && (
                      <HeroFilterPill
                        label="Month"
                        value={monthLabel(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={reportingPeriod} />
                <MetaRow
                  label="Total Records"
                  value={
                    hasActiveFilter
                      ? `${fmt(stats.total)} of ${fmt(allJobs.length)}`
                      : fmt(stats.total)
                  }
                />
                <MetaRow
                  label="Document ID"
                  value={`QRS-JOB-${Date.now().toString().slice(-6)}`}
                />
              </div>
            </div>
          </div>
        </div>

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

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 20,
            }}
          >
            <KpiCard
              label="Total Jobs"
              value={fmt(stats.total)}
              icon={<Briefcase size={14} strokeWidth={2} />}
              accent={TOKENS.brand}
              prominent
            />
            <KpiCard
              label="Stage 1"
              value={fmt(stats.byStage["Stage 1"] ?? 0)}
              sub={pct(stats.byStage["Stage 1"] ?? 0, stats.total)}
              icon={<Layers size={14} strokeWidth={2} />}
              accent={TOKENS.info}
            />
            <KpiCard
              label="Stage 2"
              value={fmt(stats.byStage["Stage 2"] ?? 0)}
              sub={pct(stats.byStage["Stage 2"] ?? 0, stats.total)}
              icon={<Layers size={14} strokeWidth={2} fill="currentColor" />}
              accent={TOKENS.recert}
            />
            <KpiCard
              label="Unique Companies"
              value={fmt(stats.uniqueCompanies)}
              icon={<Building2Icon size={14} strokeWidth={2} />}
              accent={TOKENS.surveillance}
            />
          </div>

          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 14,
              marginBottom: 36,
            }}
          >
            <KpiCard
              label="Low Risk"
              value={fmt(stats.byRisk["Low"] ?? 0)}
              sub={pct(stats.byRisk["Low"] ?? 0, stats.total)}
              icon={<ShieldCheck size={14} strokeWidth={2} />}
              accent={TOKENS.success}
            />
            <KpiCard
              label="Medium Risk"
              value={fmt(stats.byRisk["Medium"] ?? 0)}
              sub={pct(stats.byRisk["Medium"] ?? 0, stats.total)}
              icon={<Shield size={14} strokeWidth={2} />}
              accent={TOKENS.warning}
            />
            <KpiCard
              label="High Risk"
              value={fmt(stats.byRisk["High"] ?? 0)}
              sub={pct(stats.byRisk["High"] ?? 0, stats.total)}
              icon={<ShieldAlert size={14} strokeWidth={2} />}
              accent={TOKENS.danger}
            />
            <KpiCard
              label="Active Auditors"
              value={fmt(stats.uniqueAuditors)}
              icon={<Users size={14} strokeWidth={2} />}
              accent={TOKENS.initial}
            />
          </div>

          {hasActiveFilter && stats.total === 0 ? (
            <EmptyState
              icon={<CircleSlash size={20} strokeWidth={2} />}
              title="No jobs match the selected filters"
              text="Adjust or clear the filters above to see report data."
            />
          ) : (
            <>
              {/* 02 — DISTRIBUTION */}
              <SectionHeader
                number="02"
                title="Distribution Analysis"
                description="Stage & risk level breakdown shown as proportional segments"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <DonutCard
                  title="By Audit Stage"
                  segments={[
                    {
                      label: "Stage 1",
                      value: stats.byStage["Stage 1"] ?? 0,
                      color: TOKENS.info,
                    },
                    {
                      label: "Stage 2",
                      value: stats.byStage["Stage 2"] ?? 0,
                      color: TOKENS.recert,
                    },
                  ]}
                  total={stats.total}
                />
                <DonutCard
                  title="By Risk Level"
                  segments={[
                    {
                      label: "Low",
                      value: stats.byRisk["Low"] ?? 0,
                      color: TOKENS.success,
                    },
                    {
                      label: "Medium",
                      value: stats.byRisk["Medium"] ?? 0,
                      color: TOKENS.warning,
                    },
                    {
                      label: "High",
                      value: stats.byRisk["High"] ?? 0,
                      color: TOKENS.danger,
                    },
                  ]}
                  total={stats.total}
                />
              </div>

              {/* 03 — TEAM */}
              <SectionHeader
                number="03"
                title="Audit Team Activity"
                description="Top lead auditors and audit templates by job count"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <RankingCard
                  title="Top Lead Auditors"
                  icon={<UserCheck size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byAuditor)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
                <RankingCard
                  title="Top Audit Templates"
                  icon={<FileText size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byTemplate)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
              </div>

              {/* 04 — COMPANIES & STANDARDS */}
              <SectionHeader
                number="04"
                title="Companies & Standards Coverage"
                description="Top audited companies and ISO standards across the portfolio"
              />
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 16,
                  marginBottom: 36,
                }}
              >
                <RankingCard
                  title="Top Audited Companies"
                  icon={<Building2Icon size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byCompany)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
                <RankingCard
                  title="Top ISO Standards"
                  icon={<Award size={14} strokeWidth={2} />}
                  rows={Object.entries(stats.byStandard)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 8)}
                  total={stats.total}
                />
              </div>

              {/* 05 — RECENT JOBS */}
              <SectionHeader
                number="05"
                title="Recent Audit Jobs"
                description="Most recently registered audit jobs"
              />
              {stats.recentJobs.length === 0 ? (
                <EmptyState
                  icon={<CircleSlash size={20} strokeWidth={2} />}
                  title="No jobs to display"
                  text="No audit jobs found for the current filter selection."
                />
              ) : (
                <DataTable
                  headers={["Job", "Company", "Stage", "Lead Auditor", "Risk", "Date"]}
                  rows={stats.recentJobs.slice(0, 25).map((j: JobRow, idx: number) => [
                    <JobChip
                      key={`j-${idx}`}
                      id={String(j.id)}
                      codes={Array.isArray(j.jobCodes) ? j.jobCodes : []}
                    />,
                    <CompanyText key={`c-${idx}`} value={j.companyName || "—"} />,
                    <StageChip key={`s-${idx}`} value={pickStr(j.stage)} />,
                    pickStr(j.leadAuditor) || "—",
                    <RiskChip key={`r-${idx}`} value={pickStr(j.mdRisk)} />,
                    j.date || formatDate(getJobCreatedDate(j)),
                  ])}
                  footer={
                    stats.recentJobs.length > 25
                      ? `Showing first 25 of ${stats.recentJobs.length} jobs`
                      : undefined
                  }
                />
              )}

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

              {/* 06 — REGISTRATION TREND */}
              <SectionHeader
                number="06"
                title="Job Registration Trend"
                description="Monthly audit job registrations over the last 12 months"
              />
              <TrendChart data={stats.last12MonthsRegistered} />
            </>
          )}

          {/* 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>

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

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

function computeStats(jobs: JobRow[]) {
  const byStage: Record<string, number> = {};
  const byRisk: Record<string, number> = {};
  const byAuditor: Record<string, number> = {};
  const byTemplate: Record<string, number> = {};
  const byCompany: Record<string, number> = {};
  const byStandard: Record<string, number> = {};

  const auditorSet = new Set<string>();
  const companySet = new Set<string>();

  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: `${monthNameShort(d.getMonth())} ${String(d.getFullYear()).slice(2)}`,
      count: 0,
      year: d.getFullYear(),
      month: d.getMonth(),
    });
  }

  jobs.forEach((j) => {
    const stage = pickStr(j.stage);
    if (stage) byStage[stage] = (byStage[stage] ?? 0) + 1;

    const risk = pickStr(j.mdRisk);
    if (risk) byRisk[risk] = (byRisk[risk] ?? 0) + 1;

    const auditor = pickStr(j.leadAuditor);
    if (auditor) {
      byAuditor[auditor] = (byAuditor[auditor] ?? 0) + 1;
      auditorSet.add(auditor);
    }

    const template = pickStr(j.templateName);
    if (template) byTemplate[template] = (byTemplate[template] ?? 0) + 1;

    const company = pickStr(j.companyName);
    if (company) {
      byCompany[company] = (byCompany[company] ?? 0) + 1;
      companySet.add(company);
    }

    if (Array.isArray(j.standards)) {
      j.standards.forEach((s: any) => {
        const sn = pickStr(typeof s === "object" ? s.name : s);
        if (sn) byStandard[sn] = (byStandard[sn] ?? 0) + 1;
      });
    }

    const d = getJobCreatedDate(j);
    if (d) {
      const bucket = last12.find(
        (b) => b.year === d.getFullYear() && b.month === d.getMonth(),
      );
      if (bucket) bucket.count++;
    }
  });

  const recentJobs = [...jobs].sort((a, b) => {
    const ta = getJobCreatedDate(a)?.getTime() ?? 0;
    const tb = getJobCreatedDate(b)?.getTime() ?? 0;
    return tb - ta;
  });

  return {
    total: jobs.length,
    byStage,
    byRisk,
    byAuditor,
    byTemplate,
    byCompany,
    byStandard,
    uniqueAuditors: auditorSet.size,
    uniqueCompanies: companySet.size,
    recentJobs,
    last12MonthsRegistered: 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 job data
        </div>
        <div style={{ fontSize: 11, color: TOKENS.ink5, marginTop: 4 }}>
          Aggregating analytics across all audit jobs…
        </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,
  filterSearch,
  filterStage,
  filterRisk,
  filterAuditor,
  filterStandard,
  filterYear,
  filterMonth,
  onChangeSearch,
  onChangeStage,
  onChangeRisk,
  onChangeAuditor,
  onChangeStandard,
  onChangeYear,
  onChangeMonth,
  onClear,
  totalAll,
  totalFiltered,
  hasActiveFilter,
}: {
  options: {
    auditors: FilterOption[];
    standards: FilterOption[];
    stages: FilterOption[];
    risks: FilterOption[];
    years: string[];
    monthCounts: Record<string, number>;
  };
  filterSearch: string;
  filterStage: string;
  filterRisk: string;
  filterAuditor: string;
  filterStandard: string;
  filterYear: string;
  filterMonth: string;
  onChangeSearch: (v: string) => void;
  onChangeStage: (v: string) => void;
  onChangeRisk: (v: string) => void;
  onChangeAuditor: (v: string) => void;
  onChangeStandard: (v: string) => void;
  onChangeYear: (v: string) => void;
  onChangeMonth: (v: string) => void;
  onClear: () => void;
  totalAll: number;
  totalFiltered: number;
  hasActiveFilter: boolean;
}) {
  const yearOpts = options.years.map((y) => ({ value: y, label: y }));
  const monthOpts = ALL_MONTHS.map((m) => {
    const count = options.monthCounts[m.value] ?? 0;
    return {
      value: m.value,
      label: count > 0 ? `${m.label} (${fmt(count)})` : m.label,
    };
  });

  // Merge known stages with any extras from data
  const stageValues = Array.from(
    new Set([...STAGE_OPTIONS, ...options.stages.map((o) => o.value)]),
  );
  const stageOpts = stageValues.map((v) => {
    const c = options.stages.find((o) => o.value === v)?.count ?? 0;
    return { value: v, label: c > 0 ? `${v} (${fmt(c)})` : v };
  });

  const riskValues = Array.from(
    new Set([...RISK_OPTIONS, ...options.risks.map((o) => o.value)]),
  );
  const riskOpts = riskValues.map((v) => {
    const c = options.risks.find((o) => o.value === v)?.count ?? 0;
    return { value: v, label: c > 0 ? `${v} (${fmt(c)})` : v };
  });

  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>

      <SearchInput
        label="Search"
        value={filterSearch}
        onChange={onChangeSearch}
        placeholder="Company, auditor, code…"
      />

      <FilterSelect
        label="Stage"
        value={filterStage}
        onChange={onChangeStage}
        placeholder="All Stages"
        options={stageOpts}
        minWidth={130}
      />
      <FilterSelect
        label="Risk"
        value={filterRisk}
        onChange={onChangeRisk}
        placeholder="All Risks"
        options={riskOpts}
        minWidth={120}
      />
      <FilterSelect
        label="Lead Auditor"
        value={filterAuditor}
        onChange={onChangeAuditor}
        placeholder="All Auditors"
        options={options.auditors.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={170}
      />
      <FilterSelect
        label="Standard"
        value={filterStandard}
        onChange={onChangeStandard}
        placeholder="All Standards"
        options={options.standards.map((o) => ({
          value: o.value,
          label: `${o.value} (${fmt(o.count)})`,
        }))}
        minWidth={170}
      />
      <FilterSelect
        label="Year"
        value={filterYear}
        onChange={onChangeYear}
        placeholder="All Years"
        options={yearOpts}
        minWidth={110}
      />
      <FilterSelect
        label="Month"
        value={filterMonth}
        onChange={onChangeMonth}
        placeholder="All Months"
        options={monthOpts}
        minWidth={150}
      />

      {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 SearchInput({
  label,
  value,
  onChange,
  placeholder,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
}) {
  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>
      <div style={{ position: "relative" }}>
        <SearchIcon
          size={12}
          strokeWidth={2.2}
          color={isActive ? TOKENS.brand : TOKENS.ink5}
          style={{
            position: "absolute",
            left: 10,
            top: "50%",
            transform: "translateY(-50%)",
            pointerEvents: "none",
          }}
        />
        <input
          type="text"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            background: isActive ? `${TOKENS.brand}10` : TOKENS.surface,
            border: `1px solid ${isActive ? TOKENS.brand : TOKENS.line}`,
            borderRadius: TOKENS.rSm,
            padding: "8px 28px 8px 28px",
            fontSize: 12,
            fontWeight: 600,
            color: isActive ? TOKENS.brand : TOKENS.ink2,
            outline: "none",
            minWidth: 200,
            height: 36,
            transition: "all 0.15s",
          }}
        />
        {isActive && (
          <button
            onClick={() => onChange("")}
            style={{
              position: "absolute",
              right: 6,
              top: "50%",
              transform: "translateY(-50%)",
              background: "transparent",
              border: "none",
              cursor: "pointer",
              padding: 4,
              display: "inline-flex",
              alignItems: "center",
              color: TOKENS.ink4,
            }}
            type="button"
            aria-label="Clear search"
          >
            <XIcon size={12} strokeWidth={2.5} />
          </button>
        )}
      </div>
    </label>
  );
}

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

  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 RankingCard({
  title,
  icon,
  rows,
  total,
}: {
  title: string;
  icon: React.ReactNode | null;
  rows: [string, number][];
  total: number;
}) {
  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) => {
            return (
              <div
                key={i}
                style={{
                  padding: "10px 16px",
                  borderBottom:
                    i === rows.length - 1 ? "none" : `1px solid ${TOKENS.line2}`,
                  display: "grid",
                  gridTemplateColumns: "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>
                <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 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 JobChip({ id, codes }: { id: string; codes: string[] }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <span
        style={{
          fontFamily: "'IBM Plex Mono', monospace",
          fontSize: 11,
          fontWeight: 700,
          color: TOKENS.brand,
          background: `${TOKENS.brand}10`,
          padding: "2px 8px",
          borderRadius: TOKENS.rSm,
          width: "fit-content",
        }}
      >
        #{id}
      </span>
      {codes.slice(0, 2).map((code, i) => (
        <span
          key={i}
          style={{
            fontFamily: "'IBM Plex Mono', monospace",
            fontSize: 10,
            background: TOKENS.line2,
            border: `1px solid ${TOKENS.line}`,
            padding: "1px 6px",
            borderRadius: 4,
            color: TOKENS.ink3,
            whiteSpace: "nowrap",
            width: "fit-content",
          }}
        >
          {code}
        </span>
      ))}
      {codes.length > 2 && (
        <span style={{ fontSize: 10, color: TOKENS.ink5 }}>
          +{codes.length - 2} more
        </span>
      )}
    </div>
  );
}

function CompanyText({ value }: { value: string }) {
  return (
    <span
      style={{
        display: "inline-block",
        fontWeight: 600,
        color: TOKENS.ink2,
        maxWidth: 220,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}
      title={value}
    >
      {value}
    </span>
  );
}

function StageChip({ value }: { value: string }) {
  if (!value) return <span style={{ color: TOKENS.ink5 }}>—</span>;
  const map: Record<string, { bg: string; color: string }> = {
    "Stage 1": { bg: `${TOKENS.info}15`, color: TOKENS.info },
    "Stage 2": { bg: `${TOKENS.recert}15`, color: TOKENS.recert },
  };
  const s = map[value] ?? { bg: TOKENS.line2, color: TOKENS.ink3 };
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 800,
        color: s.color,
        background: s.bg,
        padding: "2px 8px",
        borderRadius: TOKENS.rSm,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {value}
    </span>
  );
}

function RiskChip({ value }: { value: string }) {
  if (!value) return <span style={{ color: TOKENS.ink5 }}>—</span>;
  const map: Record<string, { bg: string; color: string }> = {
    Low: { bg: `${TOKENS.success}15`, color: TOKENS.success },
    Medium: { bg: `${TOKENS.warning}15`, color: "#a16207" },
    High: { bg: `${TOKENS.danger}15`, color: TOKENS.danger },
  };
  const s = map[value] ?? { bg: TOKENS.line2, color: TOKENS.ink3 };
  return (
    <span
      style={{
        display: "inline-block",
        fontSize: 10,
        fontWeight: 800,
        color: s.color,
        background: s.bg,
        padding: "2px 8px",
        borderRadius: TOKENS.rSm,
        textTransform: "uppercase",
        letterSpacing: 0.4,
      }}
    >
      {value}
    </span>
  );
}

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

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

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

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

          <div
            style={{
              display: "grid",
              gridTemplateColumns: `repeat(${data.length}, 1fr)`,
              gap: 8,
              alignItems: "end",
              height: chartHeight,
              position: "relative",
            }}
          >
            {data.map((d, i) => {
              const h = (d.count / max) * (chartHeight - 16);
              return (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    gap: 4,
                    height: "100%",
                    justifyContent: "flex-end",
                  }}
                  title={`${d.label}: ${d.count} jobs`}
                >
                  {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>
  );
}