'use client';

import React, { useState, useMemo } from 'react';
import {
  Scale,
  ShieldCheck,
  ShieldAlert,
  AlertTriangle,
  FileCheck2,
  CheckCircle2,
  Search,
  Filter,
  Download,
  Printer,
  ExternalLink,
  Eye,
  Camera,
  Layers,
  BarChart3,
  TrendingUp,
  RefreshCw,
  Clock,
  ArrowRight,
  ZoomIn,
  ZoomOut,
  X,
  FileSpreadsheet,
  Cpu,
  Fingerprint,
  FileCheck,
  Scan
} from 'lucide-react';
import { POLITICAL_PARTIES, NIGERIAN_STATES } from '@/lib/electoralData';
import { ForensicOcrReport, runOcrForensicComparison } from '@/lib/ocrAnalysis';

interface AuditRecord {
  puCode: string;
  puName: string;
  state: string;
  lga: string;
  ward: string;
  registeredVoters: number;
  bvasAccredited: number;
  agentVotes: { ADC: number; APC: number; PDP: number; LP: number; NNPP: number; SDP: number };
  irevVotes: { ADC: number; APC: number; PDP: number; LP: number; NNPP: number; SDP: number };
  agentPhotoUrl: string;
  irevPhotoUrl: string;
  agentSigned: boolean;
  agentName: string;
  signedAt: string;
  irevUploadedAt: string;
  status: 'MATCH' | 'VARIANCE' | 'OVER_VOTING' | 'PENDING_IREV';
  notes: string;
}

// Statistically representative sample of PUs for PVT & IReV Audit Desk
const SAMPLE_AUDIT_DATA: AuditRecord[] = [
  {
    puCode: '24-11-01-001',
    puName: 'Governor Office Gate / Secretariat Alausa',
    state: 'Lagos',
    lga: 'Ikeja',
    ward: 'Alausa',
    registeredVoters: 750,
    bvasAccredited: 465,
    agentVotes: { ADC: 245, APC: 155, LP: 53, PDP: 7, NNPP: 5, SDP: 0 },
    irevVotes: { ADC: 245, APC: 155, LP: 53, PDP: 7, NNPP: 5, SDP: 0 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: '/sample_ec8a_snap.jpg',
    agentSigned: true,
    agentName: 'Ibrahim Danjuma',
    signedAt: '04:45 PM',
    irevUploadedAt: '05:12 PM',
    status: 'MATCH',
    notes: '100% mathematical match between signed physical Form EC8A and INEC IReV upload.',
  },
  {
    puCode: '24-11-01-002',
    puName: 'Central Primary School Compound, Alausa',
    state: 'Lagos',
    lga: 'Ikeja',
    ward: 'Alausa',
    registeredVoters: 820,
    bvasAccredited: 510,
    agentVotes: { ADC: 295, APC: 160, LP: 45, PDP: 5, NNPP: 3, SDP: 2 },
    irevVotes: { ADC: 215, APC: 240, LP: 45, PDP: 5, NNPP: 3, SDP: 2 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: 'https://images.unsplash.com/photo-1568602471122-7832951cc4c5?auto=format&fit=crop&q=80&w=1000',
    agentSigned: true,
    agentName: 'Babatunde Fashola Jr.',
    signedAt: '05:10 PM',
    irevUploadedAt: '06:30 PM',
    status: 'VARIANCE',
    notes: 'CRITICAL TAMPERING: INEC IReV scraped upload reduced ADC by 80 votes and inflated APC by 80 votes.',
  },
  {
    puCode: '21-06-01-001',
    puName: 'Birnin Kebbi Model Primary School PU 001',
    state: 'Kebbi',
    lga: 'Birnin Kebbi',
    ward: 'Nassarawa I',
    registeredVoters: 720,
    bvasAccredited: 420,
    agentVotes: { ADC: 260, APC: 120, PDP: 30, LP: 5, NNPP: 3, SDP: 2 },
    irevVotes: { ADC: 260, APC: 120, PDP: 30, LP: 5, NNPP: 3, SDP: 2 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: '/sample_ec8a_snap.jpg',
    agentSigned: true,
    agentName: 'Usman Bello',
    signedAt: '04:30 PM',
    irevUploadedAt: '05:00 PM',
    status: 'MATCH',
    notes: 'Verified match. Clear Form EC8A copy endorsed by all polling agents.',
  },
  {
    puCode: '37-06-01-001',
    puName: 'City Centre Open Space, Area 1 Garki',
    state: 'FCT (Abuja)',
    lga: 'Municipal Area Council (AMAC)',
    ward: 'City Centre',
    registeredVoters: 850,
    bvasAccredited: 490,
    agentVotes: { ADC: 310, APC: 95, LP: 70, PDP: 10, NNPP: 2, SDP: 3 },
    irevVotes: { ADC: 310, APC: 95, LP: 70, PDP: 10, NNPP: 2, SDP: 3 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: '/sample_ec8a_snap.jpg',
    agentSigned: true,
    agentName: 'Chidinma Okafor',
    signedAt: '04:55 PM',
    irevUploadedAt: '05:25 PM',
    status: 'MATCH',
    notes: 'Federal Capital Territory flagship unit: 100% verified transmission.',
  },
  {
    puCode: '20-12-01-003',
    puName: 'Fagge Model Nursery/Primary School PU 03',
    state: 'Kano',
    lga: 'Fagge',
    ward: 'Fagge A',
    registeredVoters: 600,
    bvasAccredited: 340,
    agentVotes: { ADC: 140, NNPP: 110, APC: 75, PDP: 10, LP: 3, SDP: 2 },
    irevVotes: { ADC: 140, NNPP: 110, APC: 195, PDP: 10, LP: 3, SDP: 2 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: 'https://images.unsplash.com/photo-1568602471122-7832951cc4c5?auto=format&fit=crop&q=80&w=1000',
    agentSigned: true,
    agentName: 'Haruna Sanusi',
    signedAt: '05:20 PM',
    irevUploadedAt: '07:15 PM',
    status: 'OVER_VOTING',
    notes: 'SECTION 51 VIOLATION: IReV uploaded tally (460 votes) exceeds BVAS accreditation (340) by +120 votes. Void under Sec 51(2).',
  },
  {
    puCode: '33-22-01-005',
    puName: 'Township Primary School Block B, Port Harcourt',
    state: 'Rivers',
    lga: 'Port Harcourt',
    ward: 'Township',
    registeredVoters: 780,
    bvasAccredited: 450,
    agentVotes: { ADC: 270, APC: 110, PDP: 50, LP: 15, NNPP: 2, SDP: 3 },
    irevVotes: { ADC: 0, APC: 0, PDP: 0, LP: 0, NNPP: 0, SDP: 0 },
    agentPhotoUrl: '/sample_ec8a_snap.jpg',
    irevPhotoUrl: '',
    agentSigned: true,
    agentName: 'Tamuno Briggs',
    signedAt: '05:40 PM',
    irevUploadedAt: 'PENDING',
    status: 'PENDING_IREV',
    notes: 'Field agent submitted signed Form EC8A. INEC IReV portal has NOT uploaded EC8A after 4+ hours.',
  },
];

interface Props {
  onOpenCourtModal?: () => void;
}

export const PvtAuditDesk: React.FC<Props> = ({ onOpenCourtModal }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<'ALL' | 'MATCH' | 'VARIANCE' | 'OVER_VOTING' | 'PENDING_IREV'>('ALL');
  const [inspectedRecord, setInspectedRecord] = useState<AuditRecord | null>(null);
  const [zoomLevel, setZoomLevel] = useState<number>(1);
  const [ocrLoading, setOcrLoading] = useState(false);
  const [ocrReport, setOcrReport] = useState<ForensicOcrReport | null>(null);

  const handleRunOcr = async (record: AuditRecord) => {
    setOcrLoading(true);
    setOcrReport(null);
    try {
      const res = await fetch('/api/analyze-ec8a', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          puCode: record.puCode,
          puName: record.puName,
          agentPhotoUrl: record.agentPhotoUrl,
          irevPhotoUrl: record.irevPhotoUrl,
          agentVotes: record.agentVotes,
          irevVotes: record.irevVotes,
          bvasAccredited: record.bvasAccredited,
        }),
      });
      const data = await res.json();
      if (data.success && data.report) {
        setOcrReport(data.report);
      } else {
        const fallback = await runOcrForensicComparison({
          puCode: record.puCode,
          puName: record.puName,
          agentPhotoUrl: record.agentPhotoUrl,
          irevPhotoUrl: record.irevPhotoUrl,
          agentVotes: record.agentVotes,
          irevVotes: record.irevVotes,
          bvasAccredited: record.bvasAccredited,
        });
        setOcrReport(fallback);
      }
    } catch {
      const fallback = await runOcrForensicComparison({
        puCode: record.puCode,
        puName: record.puName,
        agentPhotoUrl: record.agentPhotoUrl,
        irevPhotoUrl: record.irevPhotoUrl,
        agentVotes: record.agentVotes,
        irevVotes: record.irevVotes,
        bvasAccredited: record.bvasAccredited,
      });
      setOcrReport(fallback);
    } finally {
      setOcrLoading(false);
    }
  };

  const handleDownloadCertificate = (report: ForensicOcrReport) => {
    const certText = `================================================================================
PRESIDENTIAL ELECTION 2027 • FORENSIC INTEGRITY CERTIFICATE
IN COMPLIANCE WITH SECTION 84 OF EVIDENCE ACT 2011 & ELECTORAL ACT 2022
================================================================================

EXHIBIT CODE: ${report.tribunalExhibitCode}
POLLING UNIT: ${report.puCode} - ${report.puName}
ANALYSIS TIMESTAMP: ${report.analysisTimestamp}
FORENSIC SHA-256 DIGITAL HASH: ${report.forensicHash}
OPTICAL OCR CONFIDENCE: ${report.overallConfidence}%
BVAS ACCREDITED VOTERS: ${report.bvasAccredited}

VERDICT: ${report.verdict}
SUMMARY STATEMENT: ${report.summaryStatement}

--------------------------------------------------------------------------------
PARTY-BY-PARTY OCR VARIANCE BREAKDOWN:
--------------------------------------------------------------------------------
PARTY  | AGENT PHYSICAL EC8A | INEC IREV UPLOAD | VARIANCE | OCR CONFIDENCE
ADC    | ${report.partyBreakdown.find(p => p.party === 'ADC')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'ADC')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'ADC')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'ADC')?.confidenceScore ?? 0}%
APC    | ${report.partyBreakdown.find(p => p.party === 'APC')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'APC')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'APC')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'APC')?.confidenceScore ?? 0}%
PDP    | ${report.partyBreakdown.find(p => p.party === 'PDP')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'PDP')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'PDP')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'PDP')?.confidenceScore ?? 0}%
LP     | ${report.partyBreakdown.find(p => p.party === 'LP')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'LP')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'LP')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'LP')?.confidenceScore ?? 0}%
NNPP   | ${report.partyBreakdown.find(p => p.party === 'NNPP')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'NNPP')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'NNPP')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'NNPP')?.confidenceScore ?? 0}%
SDP    | ${report.partyBreakdown.find(p => p.party === 'SDP')?.agentPhotoDigit ?? 0}                  | ${report.partyBreakdown.find(p => p.party === 'SDP')?.irevPhotoDigit ?? 0}                | ${report.partyBreakdown.find(p => p.party === 'SDP')?.variance ?? 0}        | ${report.partyBreakdown.find(p => p.party === 'SDP')?.confidenceScore ?? 0}%

TOTAL VALID VOTES (AGENT): ${report.totalValidVotesAgent}
TOTAL VALID VOTES (IREV):  ${report.totalValidVotesIrev}
OVERALL VARIANCE DETECTED: ${report.overallVarianceDetected ? 'YES (' + report.varianceMagnitude + ' VOTES DISCREPANCY)' : 'NO (100% MATCH)'}

DIGITAL CERTIFICATION:
This document is generated by GetoCore Digital Forensics Subsystem for the Presidential Campaign of
His Excellency Atiku Abubakar (ADC 🤝). This forensic audit trail is admissible in the Presidential
Election Petitions Court as computer-generated evidence under Section 84 of the Evidence Act 2011.
================================================================================`;

    const blob = new Blob([certText], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `FORENSIC_OCR_CERTIFICATE_${report.tribunalExhibitCode.replace('#', '')}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Filtered records
  const filteredRecords = useMemo(() => {
    return SAMPLE_AUDIT_DATA.filter((r) => {
      const matchSearch =
        r.puCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.puName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.state.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.lga.toLowerCase().includes(searchTerm.toLowerCase());

      const matchStatus = statusFilter === 'ALL' || r.status === statusFilter;
      return matchSearch && matchStatus;
    });
  }, [searchTerm, statusFilter]);

  // Summary Metrics
  const totalAudited = SAMPLE_AUDIT_DATA.length;
  const matchCount = SAMPLE_AUDIT_DATA.filter((r) => r.status === 'MATCH').length;
  const varianceCount = SAMPLE_AUDIT_DATA.filter((r) => r.status === 'VARIANCE').length;
  const overVotingCount = SAMPLE_AUDIT_DATA.filter((r) => r.status === 'OVER_VOTING').length;
  const pendingIrevCount = SAMPLE_AUDIT_DATA.filter((r) => r.status === 'PENDING_IREV').length;

  const handleExportCsv = () => {
    const headers = [
      'PU_Code',
      'PU_Name',
      'State',
      'LGA',
      'Ward',
      'BVAS_Accredited',
      'Agent_ADC_Votes',
      'Agent_APC_Votes',
      'Agent_PDP_Votes',
      'Agent_LP_Votes',
      'IReV_ADC_Votes',
      'IReV_APC_Votes',
      'IReV_PDP_Votes',
      'IReV_LP_Votes',
      'Audit_Status',
      'Agent_Signed',
      'Agent_Name',
      'Signed_At',
      'IReV_Uploaded_At',
      'Audit_Notes',
    ];

    const rows = filteredRecords.map((r) => [
      r.puCode,
      `"${r.puName}"`,
      r.state,
      r.lga,
      r.ward,
      r.bvasAccredited,
      r.agentVotes.ADC,
      r.agentVotes.APC,
      r.agentVotes.PDP,
      r.agentVotes.LP,
      r.irevVotes.ADC,
      r.irevVotes.APC,
      r.irevVotes.PDP,
      r.irevVotes.LP,
      r.status,
      r.agentSigned ? 'YES' : 'NO',
      `"${r.agentName}"`,
      r.signedAt,
      r.irevUploadedAt,
      `"${r.notes.replace(/"/g, '""')}"`,
    ]);

    const csvContent = 'data:text/csv;charset=utf-8,' + [headers.join(','), ...rows.map((e) => e.join(','))].join('\n');
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', `PVT_EC8A_VS_IREV_AUDIT_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-6">
      {/* Top Banner: PVT & Audit Desk Overview */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-lg">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div className="flex items-start space-x-3.5">
            <div className="w-10 h-10 rounded-xl bg-slate-800 border border-amber-500/50 text-amber-400 flex items-center justify-center font-black shrink-0">
              <Scale className="w-5 h-5" />
            </div>
            <div>
              <div className="flex flex-wrap items-center gap-2">
                <h2 className="text-base sm:text-lg font-black text-white tracking-wide">
                  PVT & Form EC8A vs INEC IReV Audit Desk
                </h2>
                <span className="text-[10px] bg-amber-500/15 border border-amber-500/60 text-amber-300 px-2 py-0.5 rounded-full font-mono font-bold">
                  99% Confidence Interval
                </span>
              </div>
              <p className="text-xs text-slate-400 mt-1 max-w-3xl leading-relaxed">
                Parallel Vote Tabulation (PVT) statistical projection vs official collation, with side-by-side verification between Field Agent Signed Form EC8A sheets and scraped INEC IReV uploads.
              </p>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={handleExportCsv}
              className="px-3.5 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-amber-300 border border-amber-500/40 text-xs font-bold flex items-center gap-1.5 transition shadow-sm"
            >
              <Download className="w-3.5 h-3.5" />
              <span>Export Audit Dossier (CSV)</span>
            </button>
            {onOpenCourtModal && (
              <button
                onClick={onOpenCourtModal}
                className="px-3.5 py-2 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 text-xs font-bold flex items-center gap-1.5 transition shadow-md"
              >
                <FileCheck2 className="w-3.5 h-3.5" />
                <span>Generate Court Affidavits</span>
              </button>
            )}
          </div>
        </div>

        {/* PVT Statistical Projection Grid */}
        <div className="mt-5 pt-4 border-t border-slate-800 grid grid-cols-2 md:grid-cols-4 gap-3">
          <div className="p-3 bg-slate-950 rounded-xl border border-slate-800">
            <span className="text-[10px] text-slate-400 uppercase font-semibold block">
              Sample Polling Units
            </span>
            <span className="text-lg font-mono font-bold text-white block mt-0.5">
              5,000 PUs
            </span>
            <span className="text-[10px] text-emerald-400">Stratified across 36 States + FCT</span>
          </div>

          <div className="p-3 bg-slate-950 rounded-xl border border-slate-800">
            <span className="text-[10px] text-slate-400 uppercase font-semibold block">
              Margin of Error
            </span>
            <span className="text-lg font-mono font-bold text-amber-400 block mt-0.5">
              &plusmn; 1.2%
            </span>
            <span className="text-[10px] text-slate-400">At 99% statistical confidence</span>
          </div>

          <div className="p-3 bg-slate-950 rounded-xl border border-slate-800">
            <span className="text-[10px] text-slate-400 uppercase font-semibold block">
              PVT Projected Turnout
            </span>
            <span className="text-lg font-mono font-bold text-cyan-400 block mt-0.5">
              39.4%
            </span>
            <span className="text-[10px] text-slate-400">Reported Collation: 38.1%</span>
          </div>

          <div className="p-3 bg-slate-950 rounded-xl border border-amber-500/40">
            <span className="text-[10px] text-amber-400 uppercase font-semibold block">
              PVT Projected Winner
            </span>
            <span className="text-lg font-mono font-black text-amber-300 block mt-0.5">
              H.E. ATIKU ABUBAKAR
            </span>
            <span className="text-[10px] text-emerald-400 font-semibold">ADC Projected: 46.8% (&plusmn;1.2%)</span>
          </div>
        </div>

        {/* PVT Projected Share vs Scraped IReV Bar */}
        <div className="mt-4 p-3.5 bg-slate-950/80 rounded-xl border border-slate-800 space-y-2">
          <div className="flex items-center justify-between text-xs">
            <span className="font-bold text-white flex items-center gap-1.5">
              <TrendingUp className="w-3.5 h-3.5 text-amber-400" />
              <span>PVT Stratified Projections vs Official Collation</span>
            </span>
            <span className="text-[10px] font-mono text-slate-400">
              Confidence Range: ADC [45.6% - 48.0%] &bull; APC [32.8% - 35.2%]
            </span>
          </div>

          {/* Stacked Proportional Bar */}
          <div className="h-4 w-full rounded-full overflow-hidden flex bg-slate-800 border border-slate-700">
            <div style={{ width: '46.8%' }} className="bg-amber-500 h-full" title="ADC: 46.8%" />
            <div style={{ width: '34.0%' }} className="bg-blue-600 h-full" title="APC: 34.0%" />
            <div style={{ width: '10.2%' }} className="bg-emerald-600 h-full" title="PDP: 10.2%" />
            <div style={{ width: '6.9%' }} className="bg-red-600 h-full" title="LP: 6.9%" />
            <div style={{ width: '2.1%' }} className="bg-slate-500 h-full" title="Others: 2.1%" />
          </div>

          <div className="flex flex-wrap items-center gap-4 text-[11px] pt-1">
            <span className="flex items-center gap-1.5 font-bold text-amber-300">
              <span className="w-2.5 h-2.5 rounded-full bg-amber-500 inline-block" />
              ADC: 46.8% (14.2M proj.)
            </span>
            <span className="flex items-center gap-1.5 text-blue-300">
              <span className="w-2.5 h-2.5 rounded-full bg-blue-600 inline-block" />
              APC: 34.0% (10.3M proj.)
            </span>
            <span className="flex items-center gap-1.5 text-emerald-300">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-600 inline-block" />
              PDP: 10.2% (3.1M proj.)
            </span>
            <span className="flex items-center gap-1.5 text-red-300">
              <span className="w-2.5 h-2.5 rounded-full bg-red-600 inline-block" />
              LP: 6.9% (2.1M proj.)
            </span>
          </div>
        </div>
      </div>

      {/* Audit Matrix Controls */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        {/* Search Input */}
        <div className="relative flex-1 max-w-md">
          <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search PU code, Polling Unit name, LGA, or State..."
            className="w-full pl-9 pr-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none focus:border-amber-500 transition"
          />
        </div>

        {/* Status Filter Buttons */}
        <div className="flex items-center gap-1.5 overflow-x-auto pb-1">
          <button
            onClick={() => setStatusFilter('ALL')}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition ${
              statusFilter === 'ALL'
                ? 'bg-amber-500 text-slate-950 font-bold'
                : 'bg-slate-900 text-slate-400 border border-slate-800 hover:text-white'
            }`}
          >
            All ({totalAudited})
          </button>
          <button
            onClick={() => setStatusFilter('MATCH')}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition flex items-center gap-1 ${
              statusFilter === 'MATCH'
                ? 'bg-emerald-600 text-white font-bold'
                : 'bg-slate-900 text-emerald-400 border border-slate-800 hover:bg-slate-800'
            }`}
          >
            <CheckCircle2 className="w-3 h-3" />
            <span>Matched ({matchCount})</span>
          </button>
          <button
            onClick={() => setStatusFilter('VARIANCE')}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition flex items-center gap-1 ${
              statusFilter === 'VARIANCE'
                ? 'bg-red-700 text-white font-bold'
                : 'bg-slate-900 text-red-400 border border-slate-800 hover:bg-slate-800'
            }`}
          >
            <AlertTriangle className="w-3 h-3" />
            <span>Tampered / Variance ({varianceCount})</span>
          </button>
          <button
            onClick={() => setStatusFilter('OVER_VOTING')}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition flex items-center gap-1 ${
              statusFilter === 'OVER_VOTING'
                ? 'bg-red-800 text-white font-bold'
                : 'bg-slate-900 text-red-300 border border-slate-800 hover:bg-slate-800'
            }`}
          >
            <ShieldAlert className="w-3 h-3" />
            <span>Section 51 ({overVotingCount})</span>
          </button>
          <button
            onClick={() => setStatusFilter('PENDING_IREV')}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition flex items-center gap-1 ${
              statusFilter === 'PENDING_IREV'
                ? 'bg-amber-600 text-white font-bold'
                : 'bg-slate-900 text-amber-400 border border-slate-800 hover:bg-slate-800'
            }`}
          >
            <Clock className="w-3 h-3" />
            <span>Pending IReV ({pendingIrevCount})</span>
          </button>
        </div>
      </div>

      {/* Audit Comparison Cards */}
      <div className="space-y-4">
        {filteredRecords.map((record) => {
          const isMatch = record.status === 'MATCH';
          const isVariance = record.status === 'VARIANCE';
          const isOverVoting = record.status === 'OVER_VOTING';
          const isPending = record.status === 'PENDING_IREV';

          const adcVariance = record.agentVotes.ADC - record.irevVotes.ADC;
          const apcVariance = record.agentVotes.APC - record.irevVotes.APC;

          return (
            <div
              key={record.puCode}
              className={`p-4 sm:p-5 rounded-2xl border transition-all ${
                isMatch
                  ? 'bg-slate-900/90 border-slate-800'
                  : isOverVoting
                  ? 'bg-red-950/40 border-red-700/80 shadow-lg shadow-red-950/40'
                  : isVariance
                  ? 'bg-red-950/30 border-red-600/70 shadow-md'
                  : 'bg-slate-900/90 border-amber-600/40'
              }`}
            >
              {/* Card Header */}
              <div className="flex flex-col sm:flex-row sm:items-center justify-between pb-3 border-b border-slate-800 gap-2">
                <div>
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="font-mono text-xs font-bold text-amber-300">
                      {record.puCode}
                    </span>
                    <span className="text-xs text-slate-300 font-semibold">
                      &bull; {record.puName}
                    </span>
                    <span className="text-[10px] text-slate-400 bg-slate-800 px-2 py-0.5 rounded">
                      {record.lga}, {record.state}
                    </span>
                  </div>
                </div>

                {/* Status Badges */}
                <div className="flex items-center gap-2">
                  {isMatch && (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-300 bg-emerald-950/80 px-2.5 py-1 rounded-full border border-emerald-600">
                      <CheckCircle2 className="w-3 h-3" /> VERIFIED MATCH (100%)
                    </span>
                  )}
                  {isVariance && (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold text-red-200 bg-red-950/90 px-2.5 py-1 rounded-full border border-red-600 animate-pulse">
                      <AlertTriangle className="w-3 h-3 text-red-400" /> VARIANCE DETECTED
                    </span>
                  )}
                  {isOverVoting && (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold text-red-200 bg-red-950 px-2.5 py-1 rounded-full border border-red-500 animate-pulse">
                      <ShieldAlert className="w-3 h-3 text-red-400" /> SECTION 51 OVER-VOTING
                    </span>
                  )}
                  {isPending && (
                    <span className="inline-flex items-center gap-1 text-[10px] font-bold text-amber-300 bg-amber-950/80 px-2.5 py-1 rounded-full border border-amber-600">
                      <Clock className="w-3 h-3" /> PENDING IREV TRANSMISSION
                    </span>
                  )}

                  <button
                    onClick={() => {
                      setInspectedRecord(record);
                      handleRunOcr(record);
                    }}
                    className="px-2.5 py-1 rounded-lg bg-amber-500/15 hover:bg-amber-500/25 text-xs text-amber-300 border border-amber-500/40 hover:text-white transition flex items-center gap-1 font-semibold"
                  >
                    <Scan className="w-3 h-3 text-amber-400" />
                    <span>Forensic OCR</span>
                  </button>

                  <button
                    onClick={() => setInspectedRecord(record)}
                    className="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-xs text-slate-300 hover:text-white transition flex items-center gap-1"
                  >
                    <Eye className="w-3 h-3 text-amber-400" />
                    <span>Inspect</span>
                  </button>
                </div>
              </div>

              {/* Side-by-Side Comparison Columns */}
              <div className="mt-3.5 grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Column 1: Field Agent Form EC8A */}
                <div className="p-3.5 bg-slate-950 rounded-xl border border-slate-800 space-y-2.5">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-white flex items-center gap-1.5">
                      <Camera className="w-3.5 h-3.5 text-amber-400" />
                      <span>Field Agent Signed EC8A</span>
                    </span>
                    <span className="text-[10px] font-mono text-slate-400">
                      Signed: {record.signedAt} by {record.agentName}
                    </span>
                  </div>

                  <div className="grid grid-cols-4 gap-2 text-center text-xs">
                    <div className="p-1.5 rounded-lg bg-slate-900 border border-amber-500/40">
                      <span className="block text-[9px] font-bold text-amber-400">ADC</span>
                      <span className="font-mono font-extrabold text-white">{record.agentVotes.ADC}</span>
                    </div>
                    <div className="p-1.5 rounded-lg bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">APC</span>
                      <span className="font-mono font-bold text-slate-200">{record.agentVotes.APC}</span>
                    </div>
                    <div className="p-1.5 rounded-lg bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">PDP</span>
                      <span className="font-mono font-bold text-slate-200">{record.agentVotes.PDP}</span>
                    </div>
                    <div className="p-1.5 rounded-lg bg-slate-900 border border-slate-800">
                      <span className="block text-[9px] text-slate-400">LP</span>
                      <span className="font-mono font-bold text-slate-200">{record.agentVotes.LP}</span>
                    </div>
                  </div>

                  <div className="flex items-center justify-between text-[11px] text-slate-400 pt-1 border-t border-slate-900">
                    <span>BVAS Accredited: <strong className="text-white font-mono">{record.bvasAccredited}</strong></span>
                    <span className="text-emerald-400 font-semibold flex items-center gap-1">
                      <ShieldCheck className="w-3 h-3" /> Agent Affidavit Affirmed
                    </span>
                  </div>
                </div>

                {/* Column 2: Scraped INEC IReV Upload */}
                <div className="p-3.5 bg-slate-950 rounded-xl border border-slate-800 space-y-2.5">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-white flex items-center gap-1.5">
                      <Layers className="w-3.5 h-3.5 text-cyan-400" />
                      <span>INEC IReV Portal Scraped Data</span>
                    </span>
                    <span className="text-[10px] font-mono text-slate-400">
                      Uploaded: {record.irevUploadedAt}
                    </span>
                  </div>

                  {isPending ? (
                    <div className="py-3 text-center text-xs text-amber-400 font-mono">
                      No Form EC8A uploaded to INEC IReV yet. Awaiting server transmission...
                    </div>
                  ) : (
                    <div className="grid grid-cols-4 gap-2 text-center text-xs">
                      <div className={`p-1.5 rounded-lg border ${
                        adcVariance !== 0
                          ? 'bg-red-950/60 border-red-600 text-red-200'
                          : 'bg-slate-900 border-slate-800'
                      }`}>
                        <span className="block text-[9px] font-bold text-amber-400">ADC</span>
                        <span className="font-mono font-extrabold text-white">{record.irevVotes.ADC}</span>
                        {adcVariance !== 0 && (
                          <span className="block text-[9px] text-red-400 font-mono">
                            {adcVariance > 0 ? `-${adcVariance}` : `+${Math.abs(adcVariance)}`}
                          </span>
                        )}
                      </div>

                      <div className={`p-1.5 rounded-lg border ${
                        apcVariance !== 0
                          ? 'bg-red-950/60 border-red-600 text-red-200'
                          : 'bg-slate-900 border-slate-800'
                      }`}>
                        <span className="block text-[9px] text-slate-400">APC</span>
                        <span className="font-mono font-bold text-slate-200">{record.irevVotes.APC}</span>
                        {apcVariance !== 0 && (
                          <span className="block text-[9px] text-red-400 font-mono">
                            {apcVariance > 0 ? `-${apcVariance}` : `+${Math.abs(apcVariance)}`}
                          </span>
                        )}
                      </div>

                      <div className="p-1.5 rounded-lg bg-slate-900 border border-slate-800">
                        <span className="block text-[9px] text-slate-400">PDP</span>
                        <span className="font-mono font-bold text-slate-200">{record.irevVotes.PDP}</span>
                      </div>

                      <div className="p-1.5 rounded-lg bg-slate-900 border border-slate-800">
                        <span className="block text-[9px] text-slate-400">LP</span>
                        <span className="font-mono font-bold text-slate-200">{record.irevVotes.LP}</span>
                      </div>
                    </div>
                  )}

                  <div className="flex items-center justify-between text-[11px] text-slate-400 pt-1 border-t border-slate-900">
                    <span className="truncate max-w-[280px]">
                      {record.notes}
                    </span>
                    <a
                      href={`https://inecelectionresults.ng/elections/presidential/state/${record.state}`}
                      target="_blank"
                      rel="noreferrer"
                      className="text-amber-400 hover:text-amber-300 flex items-center gap-1 shrink-0"
                    >
                      <ExternalLink className="w-3 h-3" /> IReV Link
                    </a>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Side-by-Side Detailed Inspection Modal */}
      {inspectedRecord && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 bg-black/85 backdrop-blur-sm animate-in fade-in">
          <div className="w-full max-w-4xl bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-2xl space-y-4 max-h-[92vh] overflow-y-auto">
            {/* Modal Header */}
            <div className="flex items-center justify-between pb-3 border-b border-slate-800">
              <div>
                <h3 className="text-base font-bold text-white flex items-center gap-2">
                  <Scale className="w-5 h-5 text-amber-400" />
                  <span>Forensic Audit: PU {inspectedRecord.puCode}</span>
                </h3>
                <p className="text-xs text-slate-400">
                  {inspectedRecord.puName} &bull; {inspectedRecord.lga}, {inspectedRecord.state}
                </p>
              </div>
              <button
                onClick={() => setInspectedRecord(null)}
                className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Side-by-Side Photos */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <div className="flex items-center justify-between text-xs font-bold text-slate-300">
                  <span>Field Agent Physical Form EC8A</span>
                  <span className="text-emerald-400 font-mono text-[10px]">Signed &amp; Witnessed</span>
                </div>
                <div className="h-64 rounded-xl overflow-hidden border border-slate-800 bg-slate-950 flex items-center justify-center">
                  <img
                    src={inspectedRecord.agentPhotoUrl}
                    alt="Agent Signed EC8A"
                    className="w-full h-full object-cover transition-transform"
                    style={{ transform: `scale(${zoomLevel})` }}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between text-xs font-bold text-slate-300">
                  <span>Official INEC IReV Scraped Upload</span>
                  <span className="text-cyan-400 font-mono text-[10px]">Portal Capture</span>
                </div>
                <div className="h-64 rounded-xl overflow-hidden border border-slate-800 bg-slate-950 flex items-center justify-center">
                  {inspectedRecord.irevPhotoUrl ? (
                    <img
                      src={inspectedRecord.irevPhotoUrl}
                      alt="INEC IReV Form"
                      className="w-full h-full object-cover transition-transform"
                      style={{ transform: `scale(${zoomLevel})` }}
                    />
                  ) : (
                    <div className="text-xs text-slate-500 text-center px-4">
                      No image transmitted to INEC IReV portal yet.
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Zoom Controls */}
            <div className="flex items-center justify-center gap-2 pt-2">
              <button
                onClick={() => setZoomLevel(Math.max(0.8, zoomLevel - 0.2))}
                className="p-1.5 rounded-lg bg-slate-800 text-slate-300 hover:text-white"
                title="Zoom Out"
              >
                <ZoomOut className="w-4 h-4" />
              </button>
              <span className="text-xs font-mono text-slate-400 px-2">{Math.round(zoomLevel * 100)}%</span>
              <button
                onClick={() => setZoomLevel(Math.min(2.5, zoomLevel + 0.2))}
                className="p-1.5 rounded-lg bg-slate-800 text-slate-300 hover:text-white"
                title="Zoom In"
              >
                <ZoomIn className="w-4 h-4" />
              </button>
            </div>

            {/* Automated Forensic OCR Analysis Suite */}
            <div className="p-4 bg-slate-950 rounded-xl border border-slate-800 space-y-3">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-800 pb-2.5">
                <div className="flex items-center gap-2">
                  <div className="p-1.5 rounded-lg bg-amber-500/20 text-amber-400">
                    <Fingerprint className="w-4 h-4" />
                  </div>
                  <div>
                    <h4 className="text-xs font-bold text-white flex items-center gap-1.5">
                      <span>Automated Form EC8A OCR &amp; CV Forensic Extraction</span>
                      <span className="text-[9px] bg-amber-500/15 text-amber-300 px-1.5 py-0.2 rounded border border-amber-500/30">
                        Evidence Act Sec 84
                      </span>
                    </h4>
                    <p className="text-[10px] text-slate-400">
                      Optical character recognition comparing party rows against INEC server pixels.
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleRunOcr(inspectedRecord)}
                    disabled={ocrLoading}
                    className="px-3 py-1.5 rounded-lg bg-amber-500 hover:bg-amber-400 disabled:opacity-50 text-slate-950 text-xs font-bold flex items-center gap-1.5 transition shadow cursor-pointer"
                  >
                    {ocrLoading ? (
                      <>
                        <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                        <span>Running OCR Scan...</span>
                      </>
                    ) : (
                      <>
                        <Scan className="w-3.5 h-3.5" />
                        <span>{ocrReport ? 'Re-Run OCR Analysis' : 'Run OCR Analysis'}</span>
                      </>
                    )}
                  </button>

                  {ocrReport && (
                    <button
                      onClick={() => handleDownloadCertificate(ocrReport)}
                      className="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 text-xs font-semibold flex items-center gap-1 border border-slate-700 transition cursor-pointer"
                    >
                      <Download className="w-3.5 h-3.5" />
                      <span>Export Certificate</span>
                    </button>
                  )}
                </div>
              </div>

              {/* OCR Report View */}
              {ocrReport && (
                <div className="space-y-3 animate-in fade-in">
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-center text-xs">
                    <div className="p-2 bg-slate-900 rounded-lg border border-slate-800">
                      <span className="text-[10px] text-slate-400 block">Optical Confidence</span>
                      <span className="font-mono font-bold text-emerald-400 text-sm">{ocrReport.overallConfidence}%</span>
                    </div>
                    <div className="p-2 bg-slate-900 rounded-lg border border-slate-800">
                      <span className="text-[10px] text-slate-400 block">Audit Verdict</span>
                      <span className={`font-mono font-bold text-xs ${
                        ocrReport.verdict === 'CERTIFIED_MATCH'
                          ? 'text-emerald-400'
                          : ocrReport.verdict === 'OVER_VOTING_ALERT'
                          ? 'text-red-400'
                          : 'text-amber-400'
                      }`}>
                        {ocrReport.verdict.replace(/_/g, ' ')}
                      </span>
                    </div>
                    <div className="p-2 bg-slate-900 rounded-lg border border-slate-800">
                      <span className="text-[10px] text-slate-400 block">Net Variance</span>
                      <span className={`font-mono font-bold text-sm ${ocrReport.varianceMagnitude > 0 ? 'text-red-400' : 'text-slate-200'}`}>
                        {ocrReport.varianceMagnitude > 0 ? `${ocrReport.varianceMagnitude} Votes` : '0 Votes'}
                      </span>
                    </div>
                    <div className="p-2 bg-slate-900 rounded-lg border border-slate-800">
                      <span className="text-[10px] text-slate-400 block">Exhibit Code</span>
                      <span className="font-mono font-bold text-amber-400 text-[10px] truncate block">
                        {ocrReport.tribunalExhibitCode}
                      </span>
                    </div>
                  </div>

                  {/* Party Table Breakdown */}
                  <div className="overflow-x-auto border border-slate-800/80 rounded-lg">
                    <table className="w-full text-left text-xs">
                      <thead className="bg-slate-900 text-slate-400 font-mono text-[10px] uppercase border-b border-slate-800">
                        <tr>
                          <th className="p-2">Party</th>
                          <th className="p-2">Agent OCR Digit</th>
                          <th className="p-2">INEC IReV OCR Digit</th>
                          <th className="p-2">Variance</th>
                          <th className="p-2">Confidence</th>
                          <th className="p-2">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-800/60 font-mono">
                        {ocrReport.partyBreakdown.map((row) => (
                          <tr key={row.party} className={row.discrepancyFlag ? 'bg-red-950/20' : 'hover:bg-slate-900/40'}>
                            <td className="p-2 font-bold text-white flex items-center gap-1">
                              <span className={`w-2 h-2 rounded-full ${row.party === 'ADC' ? 'bg-amber-400' : 'bg-slate-500'}`} />
                              <span>{row.party}</span>
                            </td>
                            <td className="p-2 text-slate-200 font-bold">{row.agentPhotoDigit}</td>
                            <td className="p-2 text-slate-200 font-bold">{row.irevPhotoDigit}</td>
                            <td className={`p-2 font-bold ${row.variance !== 0 ? 'text-red-400' : 'text-slate-400'}`}>
                              {row.variance === 0 ? '0' : row.variance > 0 ? `+${row.variance}` : row.variance}
                            </td>
                            <td className="p-2 text-emerald-400">{row.confidenceScore}%</td>
                            <td className="p-2">
                              {row.discrepancyFlag ? (
                                <span className="px-1.5 py-0.5 text-[9px] font-bold rounded bg-red-950 text-red-300 border border-red-700">
                                  TAMPERED
                                </span>
                              ) : (
                                <span className="px-1.5 py-0.5 text-[9px] font-bold rounded bg-emerald-950 text-emerald-300 border border-emerald-800">
                                  MATCHED
                                </span>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* SHA-256 Digital Stamp */}
                  <div className="flex items-center justify-between p-2 bg-slate-900/90 rounded-lg border border-slate-800 text-[10px] text-slate-400">
                    <span className="flex items-center gap-1 font-mono">
                      <Fingerprint className="w-3 h-3 text-amber-400" />
                      <span>SHA-256 Digital Stamp:</span>
                      <code className="text-amber-300 select-all font-mono">{ocrReport.forensicHash}</code>
                    </span>
                    <span className="text-emerald-400 font-bold">Court Submissible Evidence</span>
                  </div>
                </div>
              )}
            </div>

            {/* Audit Notes & Exhibit Actions */}
            <div className="p-3.5 bg-slate-950 rounded-xl border border-slate-800 text-xs text-slate-300 space-y-2">
              <div className="font-bold text-white">Forensic Findings:</div>
              <p className="leading-relaxed">{inspectedRecord.notes}</p>
            </div>

            <div className="flex justify-end gap-2 pt-2 border-t border-slate-800">
              <button
                onClick={() => setInspectedRecord(null)}
                className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-xs text-slate-300 font-semibold"
              >
                Close Audit View
              </button>
              {onOpenCourtModal && (
                <button
                  onClick={() => {
                    setInspectedRecord(null);
                    onOpenCourtModal();
                  }}
                  className="px-4 py-2 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 text-xs font-bold shadow-md"
                >
                  Export Tribunal Petition Exhibit
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
