'use client';

import React, { useState, useMemo } from 'react';
import {
  X,
  Printer,
  Download,
  FileSpreadsheet,
  FileText,
  CheckCircle2,
  Scale,
  ShieldCheck,
  ChevronDown,
  Building,
  MapPin,
  Vote,
  Layers,
  Fingerprint,
  RefreshCw,
  ExternalLink
} from 'lucide-react';
import {
  NIGERIAN_STATES,
  LGAS_BY_STATE,
  WARDS_BY_LGA,
  POLLING_UNITS_BY_WARD,
  INITIAL_PU_RESULTS
} from '@/lib/electoralData';
import { sha256 } from '@/lib/sha256';

type FormType = 'EC8A' | 'EC8B' | 'EC8C' | 'EC8D' | 'EC8E';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  defaultForm?: FormType;
  userRole?: string;
  scopeType?: string;
}

// Convert numbers to words for formal Nigerian election sheets
function numberToWords(num: number): string {
  if (num === 0) return 'ZERO';
  const ones = ['', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE',
    'TEN', 'ELEVEN', 'TWELVE', 'THIRTEEN', 'FOURTEEN', 'FIFTEEN', 'SIXTEEN', 'SEVENTEEN', 'EIGHTEEN', 'NINETEEN'];
  const tens = ['', '', 'TWENTY', 'THIRTY', 'FORTY', 'FIFTY', 'SIXTY', 'SEVENTY', 'EIGHTY', 'NINETY'];

  if (num < 20) return ones[num];
  if (num < 100) return tens[Math.floor(num / 10)] + (num % 10 !== 0 ? ' ' + ones[num % 10] : '');
  if (num < 1000) {
    return ones[Math.floor(num / 100)] + ' HUNDRED' + (num % 100 !== 0 ? ' AND ' + numberToWords(num % 100) : '');
  }
  if (num < 1000000) {
    return numberToWords(Math.floor(num / 1000)) + ' THOUSAND' + (num % 1000 !== 0 ? ' ' + numberToWords(num % 1000) : '');
  }
  if (num < 1000000000) {
    return numberToWords(Math.floor(num / 1000000)) + ' MILLION' + (num % 1000000 !== 0 ? ' ' + numberToWords(num % 1000000) : '');
  }
  return num.toLocaleString();
}

export const InecFormGeneratorModal: React.FC<Props> = ({
  isOpen,
  onClose,
  defaultForm = 'EC8E',
  userRole,
  scopeType,
}) => {
  const isWardOnly = scopeType === 'WARD' || userRole === 'WARD_SUPERVISOR';
  const isLgaOnly = scopeType === 'LGA' || userRole === 'LGA_SUPERVISOR';
  const isStateOnly = scopeType === 'STATE' || userRole === 'STATE_SUPERVISOR';

  const allowedForms: FormType[] = useMemo(() => {
    if (isWardOnly) return ['EC8A', 'EC8B'];
    if (isLgaOnly) return ['EC8A', 'EC8B', 'EC8C'];
    if (isStateOnly) return ['EC8A', 'EC8B', 'EC8C', 'EC8D'];
    return ['EC8A', 'EC8B', 'EC8C', 'EC8D', 'EC8E'];
  }, [isWardOnly, isLgaOnly, isStateOnly]);

  const [activeForm, setActiveForm] = useState<FormType>(defaultForm);
  const [isTemplateMode, setIsTemplateMode] = useState<boolean>(false);

  React.useEffect(() => {
    if (isOpen) {
      if (defaultForm && allowedForms.includes(defaultForm)) {
        setActiveForm(defaultForm);
      } else if (!allowedForms.includes(activeForm)) {
        setActiveForm(allowedForms[allowedForms.length - 1] || 'EC8A');
      }
    }
  }, [defaultForm, allowedForms, isOpen]);

  // Cascading Selection Hierarchy
  const [selectedStateId, setSelectedStateId] = useState<string>('24'); // Lagos by default
  const [selectedLgaId, setSelectedLgaId] = useState<string>('24-11'); // Ikeja
  const [selectedWardId, setSelectedWardId] = useState<string>('24-11-01'); // Alausa
  const [selectedPuCode, setSelectedPuCode] = useState<string>('24-11-01-001');

  // Available Cascades
  const currentLgas = useMemo(() => LGAS_BY_STATE[selectedStateId] || [], [selectedStateId]);
  const currentWards = useMemo(() => WARDS_BY_LGA[selectedLgaId] || [], [selectedLgaId]);
  const currentPus = useMemo(() => POLLING_UNITS_BY_WARD[selectedWardId] || [], [selectedWardId]);

  // Selected Names
  const currentState = useMemo(() => NIGERIAN_STATES.find((s) => s.id === selectedStateId) || NIGERIAN_STATES[0], [selectedStateId]);
  const currentLga = useMemo(() => currentLgas.find((l) => l.id === selectedLgaId) || currentLgas[0], [currentLgas, selectedLgaId]);
  const currentWard = useMemo(() => currentWards.find((w) => w.id === selectedWardId) || currentWards[0], [currentWards, selectedWardId]);
  const currentPu = useMemo(() => currentPus.find((p) => p.pu_code === selectedPuCode) || currentPus[0], [currentPus, selectedPuCode]);

  // Handle State Change
  const handleStateChange = (id: string) => {
    setSelectedStateId(id);
    const lgas = LGAS_BY_STATE[id] || [];
    if (lgas.length > 0) {
      setSelectedLgaId(lgas[0].id);
      const wards = WARDS_BY_LGA[lgas[0].id] || [];
      if (wards.length > 0) {
        setSelectedWardId(wards[0].id);
        const pus = POLLING_UNITS_BY_WARD[wards[0].id] || [];
        if (pus.length > 0) {
          setSelectedPuCode(pus[0].pu_code);
        }
      }
    }
  };

  // Handle LGA Change
  const handleLgaChange = (id: string) => {
    setSelectedLgaId(id);
    const wards = WARDS_BY_LGA[id] || [];
    if (wards.length > 0) {
      setSelectedWardId(wards[0].id);
      const pus = POLLING_UNITS_BY_WARD[wards[0].id] || [];
      if (pus.length > 0) {
        setSelectedPuCode(pus[0].pu_code);
      }
    }
  };

  // Handle Ward Change
  const handleWardChange = (id: string) => {
    setSelectedWardId(id);
    const pus = POLLING_UNITS_BY_WARD[id] || [];
    if (pus.length > 0) {
      setSelectedPuCode(pus[0].pu_code);
    }
  };

  if (!isOpen) return null;

  // Compute National Aggregate for Form EC8E
  const nationalSummary = useMemo(() => {
    const totalReg = NIGERIAN_STATES.reduce((acc, s) => acc + s.registered_voters, 0);
    const adcVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.ADC || 0), 0);
    const apcVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.APC || 0), 0);
    const pdpVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.PDP || 0), 0);
    const lpVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.LP || 0), 0);
    const nnppVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.NNPP || 0), 0);
    const sdpVotes = NIGERIAN_STATES.reduce((acc, s) => acc + (s.votes?.SDP || 0), 0);

    const validVotes = adcVotes + apcVotes + pdpVotes + lpVotes + nnppVotes + sdpVotes;
    const totalAcc = validVotes > 0 ? validVotes + Math.round(validVotes * 0.02) : 0;
    const rejectedBallots = validVotes > 0 ? Math.round(validVotes * 0.024) : 0;
    const totalVotesCast = validVotes + rejectedBallots;

    return {
      totalRegistered: totalReg,
      totalAccredited: totalAcc,
      validVotes,
      rejectedBallots,
      totalVotesCast,
      candidateVotes: {
        ADC: adcVotes,
        APC: apcVotes,
        PDP: pdpVotes,
        LP: lpVotes,
        NNPP: nnppVotes,
        SDP: sdpVotes,
      },
      marginOfVictory: adcVotes - apcVotes,
    };
  }, []);

  // Compute Active Form Data
  const activeFormData = useMemo(() => {
    if (activeForm === 'EC8A') {
      const puResult = (!isTemplateMode && INITIAL_PU_RESULTS[selectedPuCode]) || {
        registered_voters: currentPu?.registered_voters || 750,
        accredited_voters: 0,
        party_votes: { ADC: 0, APC: 0, PDP: 0, LP: 0, NNPP: 0, SDP: 0 },
        total_valid_votes: 0,
        rejected_ballots: 0,
        total_votes_cast: 0,
      };
      return {
        formTitle: 'FORM EC 8A: POLLING UNIT RESULTS OF ELECTION',
        scopeDescription: `Polling Unit: ${currentPu?.pu_name || 'PU ' + selectedPuCode} (${selectedPuCode})`,
        registeredVoters: currentPu?.registered_voters || puResult.registered_voters || 0,
        accreditedVoters: isTemplateMode ? 0 : puResult.accredited_voters || 0,
        ballotsIssued: isTemplateMode ? 0 : puResult.accredited_voters || 0,
        unusedBallots: isTemplateMode ? 0 : Math.max(0, (currentPu?.registered_voters || 0) - (puResult.accredited_voters || 0)),
        spoiledBallots: 0,
        rejectedBallots: isTemplateMode ? 0 : puResult.rejected_ballots || 0,
        validVotes: isTemplateMode ? 0 : puResult.total_valid_votes || 0,
        totalVotesCast: isTemplateMode ? 0 : puResult.total_votes_cast || 0,
        votes: isTemplateMode ? { ADC: 0, APC: 0, PDP: 0, LP: 0, NNPP: 0, SDP: 0 } : puResult.party_votes,
        officerTitle: 'Presiding Officer (PO)',
        officerName: isTemplateMode ? '................................................' : 'Presiding Officer',
      };
    } else if (activeForm === 'EC8B') {
      const reg = currentWard?.registered_voters || 0;
      const adc = isTemplateMode ? 0 : (currentWard?.votes?.ADC || 0);
      const apc = isTemplateMode ? 0 : (currentWard?.votes?.APC || 0);
      const pdp = isTemplateMode ? 0 : (currentWard?.votes?.PDP || 0);
      const lp = isTemplateMode ? 0 : (currentWard?.votes?.LP || 0);
      const nnpp = isTemplateMode ? 0 : (currentWard?.votes?.NNPP || 0);
      const sdp = isTemplateMode ? 0 : (currentWard?.votes?.SDP || 0);
      const valid = adc + apc + pdp + lp + nnpp + sdp;
      const rejected = 0;
      const acc = valid;
      return {
        formTitle: 'FORM EC 8B: SUMMARY OF RESULTS AT REGISTRATION AREA (WARD) COLLATION',
        scopeDescription: `Ward: ${currentWard?.name || 'Ward'} (${currentWard?.id || selectedWardId}) • ${currentLga?.name || 'LGA'}, ${currentState?.name || 'State'}`,
        registeredVoters: reg,
        accreditedVoters: acc,
        ballotsIssued: acc,
        unusedBallots: Math.max(0, reg - acc),
        spoiledBallots: 0,
        rejectedBallots: rejected,
        validVotes: valid,
        totalVotesCast: valid + rejected,
        votes: { ADC: adc, APC: apc, PDP: pdp, LP: lp, NNPP: nnpp, SDP: sdp },
        officerTitle: 'Ward Collation Officer (RACO)',
        officerName: isTemplateMode ? '................................................' : 'Ward Collation Officer',
      };
    } else if (activeForm === 'EC8C') {
      const reg = currentLga?.registered_voters || 0;
      const adc = isTemplateMode ? 0 : (currentLga?.votes?.ADC || 0);
      const apc = isTemplateMode ? 0 : (currentLga?.votes?.APC || 0);
      const pdp = isTemplateMode ? 0 : (currentLga?.votes?.PDP || 0);
      const lp = isTemplateMode ? 0 : (currentLga?.votes?.LP || 0);
      const nnpp = isTemplateMode ? 0 : (currentLga?.votes?.NNPP || 0);
      const sdp = isTemplateMode ? 0 : (currentLga?.votes?.SDP || 0);
      const valid = adc + apc + pdp + lp + nnpp + sdp;
      const rejected = 0;
      const acc = valid;
      return {
        formTitle: 'FORM EC 8C: SUMMARY OF RESULTS AT LOCAL GOVERNMENT AREA COLLATION',
        scopeDescription: `Local Government Area: ${currentLga?.name || 'LGA'} (${currentLga?.id || selectedLgaId}) • ${currentState?.name || 'State'}`,
        registeredVoters: reg,
        accreditedVoters: acc,
        ballotsIssued: acc,
        unusedBallots: Math.max(0, reg - acc),
        spoiledBallots: 0,
        rejectedBallots: rejected,
        validVotes: valid,
        totalVotesCast: valid + rejected,
        votes: { ADC: adc, APC: apc, PDP: pdp, LP: lp, NNPP: nnpp, SDP: sdp },
        officerTitle: 'LGA Collation Officer (LGACO)',
        officerName: isTemplateMode ? '................................................' : 'LGA Collation Officer',
      };
    } else if (activeForm === 'EC8D') {
      const reg = currentState?.registered_voters || 0;
      const adc = isTemplateMode ? 0 : (currentState?.votes?.ADC || 0);
      const apc = isTemplateMode ? 0 : (currentState?.votes?.APC || 0);
      const pdp = isTemplateMode ? 0 : (currentState?.votes?.PDP || 0);
      const lp = isTemplateMode ? 0 : (currentState?.votes?.LP || 0);
      const nnpp = isTemplateMode ? 0 : (currentState?.votes?.NNPP || 0);
      const sdp = isTemplateMode ? 0 : (currentState?.votes?.SDP || 0);
      const valid = adc + apc + pdp + lp + nnpp + sdp;
      const rejected = 0;
      const acc = valid;
      return {
        formTitle: 'FORM EC 8D: SUMMARY OF RESULTS AT STATE COLLATION',
        scopeDescription: `State: ${currentState?.name || 'State'} (State Code: ${currentState?.id || selectedStateId}) • ${currentState?.total_lgas || 0} LGAs`,
        registeredVoters: reg,
        accreditedVoters: acc,
        ballotsIssued: acc,
        unusedBallots: Math.max(0, reg - acc),
        spoiledBallots: 0,
        rejectedBallots: rejected,
        validVotes: valid,
        totalVotesCast: valid + rejected,
        votes: { ADC: adc, APC: apc, PDP: pdp, LP: lp, NNPP: nnpp, SDP: sdp },
        officerTitle: 'State Collation Officer for the Presidential Election (SCOPE) / Resident Electoral Commissioner',
        officerName: isTemplateMode ? '................................................' : 'SCOPE Resident Electoral Commissioner',
      };
    } else {
      // EC8E National Declaration
      return {
        formTitle: 'FORM EC 8E: DECLARATION OF RESULT OF ELECTION (NATIONAL SUMMARY)',
        scopeDescription: 'Federal Republic of Nigeria • 36 States + Federal Capital Territory (FCT) Abuja',
        registeredVoters: nationalSummary.totalRegistered,
        accreditedVoters: isTemplateMode ? 0 : nationalSummary.totalAccredited,
        ballotsIssued: isTemplateMode ? 0 : nationalSummary.totalAccredited,
        unusedBallots: isTemplateMode ? 0 : Math.max(0, nationalSummary.totalRegistered - nationalSummary.totalAccredited),
        spoiledBallots: 0,
        rejectedBallots: isTemplateMode ? 0 : nationalSummary.rejectedBallots,
        validVotes: isTemplateMode ? 0 : nationalSummary.validVotes,
        totalVotesCast: isTemplateMode ? 0 : nationalSummary.totalVotesCast,
        votes: isTemplateMode
          ? { ADC: 0, APC: 0, PDP: 0, LP: 0, NNPP: 0, SDP: 0 }
          : nationalSummary.candidateVotes,
        officerTitle: 'Chief Electoral Commissioner of the Federation & Returning Officer for the Presidential Election',
        officerName: isTemplateMode ? '................................................' : 'Chairman, Independent National Electoral Commission (INEC)',
      };
    }
  }, [activeForm, isTemplateMode, selectedPuCode, currentPu, currentWard, selectedWardId, currentLga, selectedLgaId, currentState, selectedStateId, nationalSummary]);

  // Forensic Hash Stamp
  const formHash = useMemo(() => {
    const adc = activeFormData.votes?.ADC || 0;
    return sha256(`INEC-${activeForm}-${activeFormData.scopeDescription}-${activeFormData.validVotes}-${adc}-2027`);
  }, [activeForm, activeFormData]);

  // Helper: Safe Vote Getter
  const getVote = (partyKey: string): number => {
    if (!activeFormData || !activeFormData.votes) return 0;
    return Number(activeFormData.votes[partyKey as keyof typeof activeFormData.votes]) || 0;
  };

  // Handle PDF Export / Print
  const handlePrintPdf = () => {
    window.print();
  };

  // Handle CSV Export
  const handleDownloadCsv = () => {
    let csvRawText = '';

    if (activeForm === 'EC8A') {
      // Form EC8A: Polling Unit Results Breakdown
      const headers = [
        'Form_Type',
        'PU_Code',
        'PU_Name',
        'Ward_Name',
        'LGA_Name',
        'State_Name',
        'Registered_Voters',
        'BVAS_Accredited_Voters',
        'Ballots_Issued',
        'Unused_Ballots',
        'Spoiled_Ballots',
        'ADC_Votes_Atiku_Abubakar',
        'APC_Votes_Bola_Tinubu',
        'PDP_Votes',
        'LP_Votes_Peter_Obi',
        'NNPP_Votes_Rabiu_Kwankwaso',
        'SDP_Votes_Adewole_Adebayo',
        'Total_Valid_Votes',
        'Rejected_Ballots',
        'Total_Votes_Cast',
        'Over_Voting_Flag',
        'PO_Signed',
        'ADC_Agent_Signed',
        'SHA256_Stamp',
      ];

      const puRows = currentPus.map((pu) => {
        const puRes = (!isTemplateMode && INITIAL_PU_RESULTS[pu.pu_code]) || {
          registered_voters: pu.registered_voters || 750,
          accredited_voters: 0,
          party_votes: { ADC: 0, APC: 0, PDP: 0, LP: 0, NNPP: 0, SDP: 0 },
          total_valid_votes: 0,
          rejected_ballots: 0,
          total_votes_cast: 0,
        };

        const adc = isTemplateMode ? 0 : (puRes.party_votes?.ADC || 0);
        const apc = isTemplateMode ? 0 : (puRes.party_votes?.APC || 0);
        const pdp = isTemplateMode ? 0 : (puRes.party_votes?.PDP || 0);
        const lp = isTemplateMode ? 0 : (puRes.party_votes?.LP || 0);
        const nnpp = isTemplateMode ? 0 : (puRes.party_votes?.NNPP || 0);
        const sdp = isTemplateMode ? 0 : (puRes.party_votes?.SDP || 0);
        const valid = adc + apc + pdp + lp + nnpp + sdp;
        const rejected = isTemplateMode ? 0 : (puRes.rejected_ballots || 0);
        const totalCast = valid + rejected;
        const overVoting = puRes.accredited_voters > 0 && totalCast > puRes.accredited_voters ? 'YES_OVER_VOTING' : 'NO';

        return [
          'EC8A',
          pu.pu_code,
          `"${pu.pu_name}"`,
          `"${currentWard?.name || 'Ward'}"`,
          `"${currentLga?.name || 'LGA'}"`,
          `"${currentState?.name || 'State'}"`,
          puRes.registered_voters,
          isTemplateMode ? 0 : puRes.accredited_voters,
          isTemplateMode ? 0 : puRes.accredited_voters,
          isTemplateMode ? 0 : Math.max(0, puRes.registered_voters - puRes.accredited_voters),
          0,
          adc,
          apc,
          pdp,
          lp,
          nnpp,
          sdp,
          valid,
          rejected,
          totalCast,
          overVoting,
          isTemplateMode ? 'PENDING' : 'YES_PO_SIGNED',
          isTemplateMode ? 'PENDING' : 'YES_ADC_SIGNED',
          formHash.slice(0, 16),
        ].join(',');
      });

      csvRawText = [headers.join(','), ...puRows].join('\n');
    } else if (activeForm === 'EC8B') {
      // Form EC8B: Registration Area (Ward) Collation Breakdown
      const headers = [
        'Form_Type',
        'Ward_Code',
        'Ward_Name',
        'LGA_Name',
        'State_Name',
        'Registered_Voters',
        'Accredited_Voters',
        'ADC_Votes_Atiku',
        'APC_Votes_Tinubu',
        'PDP_Votes',
        'LP_Votes_Obi',
        'NNPP_Votes',
        'SDP_Votes',
        'Total_Valid_Votes',
        'Rejected_Ballots',
        'Total_Votes_Cast',
        'Ward_Winner',
        'RACO_Certified',
        'SHA256_Stamp',
      ];

      const wardRows = currentWards.map((w) => {
        const reg = w.registered_voters || 0;
        const adc = isTemplateMode ? 0 : (w.votes?.ADC || 0);
        const apc = isTemplateMode ? 0 : (w.votes?.APC || 0);
        const pdp = isTemplateMode ? 0 : (w.votes?.PDP || 0);
        const lp = isTemplateMode ? 0 : (w.votes?.LP || 0);
        const nnpp = isTemplateMode ? 0 : (w.votes?.NNPP || 0);
        const sdp = isTemplateMode ? 0 : (w.votes?.SDP || 0);
        const valid = adc + apc + pdp + lp + nnpp + sdp;
        const rejected = 0;
        const acc = valid;
        const winner = valid > 0 ? (adc > apc ? 'ADC (Atiku Abubakar)' : apc > adc ? 'APC (Tinubu)' : 'TIE') : '-';

        return [
          'EC8B',
          w.id,
          `"${w.name}"`,
          `"${currentLga?.name || 'LGA'}"`,
          `"${currentState?.name || 'State'}"`,
          reg,
          acc,
          adc,
          apc,
          pdp,
          lp,
          nnpp,
          sdp,
          valid,
          rejected,
          valid + rejected,
          `"${winner}"`,
          valid > 0 ? 'YES_RACO_CERTIFIED' : 'AWAITING_COLLATION',
          formHash.slice(0, 16),
        ].join(',');
      });

      csvRawText = [headers.join(','), ...wardRows].join('\n');
    } else if (activeForm === 'EC8C') {
      // Form EC8C: LGA Collation Summary Breakdown
      const headers = [
        'Form_Type',
        'LGA_Code',
        'LGA_Name',
        'State_Name',
        'Registered_Voters',
        'Accredited_Voters',
        'ADC_Votes_Atiku',
        'APC_Votes_Tinubu',
        'PDP_Votes',
        'LP_Votes_Obi',
        'NNPP_Votes',
        'SDP_Votes',
        'Total_Valid_Votes',
        'Rejected_Ballots',
        'Total_Votes_Cast',
        'LGA_Winner',
        'LGACO_Certified',
        'SHA256_Stamp',
      ];

      const lgaRows = currentLgas.map((lga) => {
        const reg = lga.registered_voters || 0;
        const adc = isTemplateMode ? 0 : (lga.votes?.ADC || 0);
        const apc = isTemplateMode ? 0 : (lga.votes?.APC || 0);
        const pdp = isTemplateMode ? 0 : (lga.votes?.PDP || 0);
        const lp = isTemplateMode ? 0 : (lga.votes?.LP || 0);
        const nnpp = isTemplateMode ? 0 : (lga.votes?.NNPP || 0);
        const sdp = isTemplateMode ? 0 : (lga.votes?.SDP || 0);
        const valid = adc + apc + pdp + lp + nnpp + sdp;
        const rejected = 0;
        const acc = valid;
        const winner = valid > 0 ? (adc > apc ? 'ADC (Atiku Abubakar)' : apc > adc ? 'APC (Tinubu)' : 'TIE') : '-';

        return [
          'EC8C',
          lga.id,
          `"${lga.name}"`,
          `"${currentState?.name || 'State'}"`,
          reg,
          acc,
          adc,
          apc,
          pdp,
          lp,
          nnpp,
          sdp,
          valid,
          rejected,
          valid + rejected,
          `"${winner}"`,
          valid > 0 ? 'YES_LGACO_CERTIFIED' : 'AWAITING_COLLATION',
          formHash.slice(0, 16),
        ].join(',');
      });

      csvRawText = [headers.join(','), ...lgaRows].join('\n');
    } else if (activeForm === 'EC8D') {
      // Form EC8D: State Collation Breakdown across LGAs
      const headers = [
        'Form_Type',
        'LGA_Code',
        'LGA_Name',
        'State_Name',
        'Registered_Voters',
        'Accredited_Voters',
        'ADC_Votes_Atiku',
        'APC_Votes_Tinubu',
        'PDP_Votes',
        'LP_Votes_Obi',
        'NNPP_Votes',
        'SDP_Votes',
        'Total_Valid_Votes',
        'Rejected_Ballots',
        'Total_Votes_Cast',
        'LGA_Winner',
        'SCOPE_Certified',
        'SHA256_Stamp',
      ];

      const lgaRows = currentLgas.map((lga) => {
        const reg = lga.registered_voters || 0;
        const adc = isTemplateMode ? 0 : (lga.votes?.ADC || 0);
        const apc = isTemplateMode ? 0 : (lga.votes?.APC || 0);
        const pdp = isTemplateMode ? 0 : (lga.votes?.PDP || 0);
        const lp = isTemplateMode ? 0 : (lga.votes?.LP || 0);
        const nnpp = isTemplateMode ? 0 : (lga.votes?.NNPP || 0);
        const sdp = isTemplateMode ? 0 : (lga.votes?.SDP || 0);
        const valid = adc + apc + pdp + lp + nnpp + sdp;
        const rejected = 0;
        const acc = valid;
        const winner = valid > 0 ? (adc > apc ? 'ADC (Atiku Abubakar)' : apc > adc ? 'APC (Tinubu)' : 'TIE') : '-';

        return [
          'EC8D',
          lga.id,
          `"${lga.name}"`,
          `"${currentState?.name || 'State'}"`,
          reg,
          acc,
          adc,
          apc,
          pdp,
          lp,
          nnpp,
          sdp,
          valid,
          rejected,
          valid + rejected,
          `"${winner}"`,
          valid > 0 ? 'YES_SCOPE_CERTIFIED' : 'AWAITING_COLLATION',
          formHash.slice(0, 16),
        ].join(',');
      });

      csvRawText = [headers.join(','), ...lgaRows].join('\n');
    } else {
      // Form EC8E: Full 37 States National Declaration Breakdown
      const headers = [
        'Form_Type',
        'S_No',
        'State_Code',
        'State_Name',
        'Geopolitical_Zone',
        'Registered_Voters',
        'Total_PUs',
        'PUs_Reported',
        'ADC_Votes_Atiku',
        'APC_Votes_Tinubu',
        'PDP_Votes',
        'LP_Votes_Obi',
        'NNPP_Votes_Kwankwaso',
        'SDP_Votes',
        'Total_Valid_Votes',
        'Rejected_Ballots',
        'Total_Votes_Cast',
        'State_Winner',
        'Form_EC8D_Certified',
        'SHA256_Stamp',
      ];

      const rows = NIGERIAN_STATES.map((s, idx) => {
        const adc = isTemplateMode ? 0 : (s.votes?.ADC || 0);
        const apc = isTemplateMode ? 0 : (s.votes?.APC || 0);
        const pdp = isTemplateMode ? 0 : (s.votes?.PDP || 0);
        const lp = isTemplateMode ? 0 : (s.votes?.LP || 0);
        const nnpp = isTemplateMode ? 0 : (s.votes?.NNPP || 0);
        const sdp = isTemplateMode ? 0 : (s.votes?.SDP || 0);
        const valid = adc + apc + pdp + lp + nnpp + sdp;
        const rejected = valid > 0 ? Math.round(valid * 0.024) : 0;
        const winner = valid > 0 ? (adc > apc ? 'ADC (Atiku Abubakar)' : apc > adc ? 'APC (Tinubu)' : 'TIE') : '-';

        return [
          'EC8E',
          idx + 1,
          s.id,
          `"${s.name}"`,
          s.geopolitical_zone,
          s.registered_voters,
          s.total_pus,
          s.pus_reported || 0,
          adc,
          apc,
          pdp,
          lp,
          nnpp,
          sdp,
          valid,
          rejected,
          valid + rejected,
          `"${winner}"`,
          valid > 0 ? 'YES_CERTIFIED' : 'AWAITING_COLLATION',
          formHash.slice(0, 16),
        ].join(',');
      });

      // Append National Summary Total Row
      const nationalRow = [
        'EC8E',
        'TOTAL',
        'NATIONAL',
        '"FEDERAL REPUBLIC OF NIGERIA"',
        'ALL_6_ZONES',
        nationalSummary.totalRegistered,
        176846,
        nationalSummary.validVotes > 0 ? 176846 : 0,
        nationalSummary.candidateVotes.ADC,
        nationalSummary.candidateVotes.APC,
        nationalSummary.candidateVotes.PDP,
        nationalSummary.candidateVotes.LP,
        nationalSummary.candidateVotes.NNPP,
        nationalSummary.candidateVotes.SDP,
        nationalSummary.validVotes,
        nationalSummary.rejectedBallots,
        nationalSummary.totalVotesCast,
        nationalSummary.validVotes > 0 && nationalSummary.candidateVotes.ADC > nationalSummary.candidateVotes.APC ? '"ADC (PRESIDENTIAL WINNER)"' : '"AWAITING NATIONAL DECLARATION"',
        nationalSummary.validVotes > 0 ? 'FORM_EC8E_DECLARED' : 'AWAITING_COLLATION',
        formHash.slice(0, 16),
      ].join(',');

      csvRawText = [headers.join(','), ...rows, nationalRow].join('\n');
    }

    // Add UTF-8 BOM (\uFEFF) for native Excel compatibility
    const blob = new Blob(['\uFEFF' + csvRawText], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = isTemplateMode
      ? `INEC_OFFICIAL_BLANK_TEMPLATE_${activeForm}.csv`
      : `INEC_OFFICIAL_${activeForm}_RESULT_SHEET_${Date.now()}.csv`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-4 bg-black/85 backdrop-blur-md animate-in fade-in overflow-y-auto">
      <div className="w-full max-w-5xl bg-slate-900 border border-slate-700 rounded-2xl shadow-2xl overflow-hidden my-auto max-h-[96vh] flex flex-col text-slate-100">
        {/* Header Navigation & Form Tabs (Screen Only) */}
        <div className="p-4 bg-slate-950 border-b border-slate-800 flex flex-col md:flex-row md:items-center justify-between gap-3 flex-shrink-0 print:hidden">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 rounded-xl bg-amber-500/20 border border-amber-500/40 text-amber-400 flex items-center justify-center font-black">
              <FileSpreadsheet className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="text-base font-bold text-white tracking-tight">
                  Official INEC Form EC8 Generator &amp; Collation Dossier
                </h3>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-amber-500/15 text-amber-300 border border-amber-500/40 font-mono font-bold">
                  PDF &amp; CSV Ready
                </span>
              </div>
              <p className="text-xs text-slate-400">
                {isWardOnly
                  ? 'Ward Collation Scope: Form EC8A (PU) & Form EC8B (Ward Summary)'
                  : isLgaOnly
                  ? 'LGA Collation Scope: Form EC8A (PU), Form EC8B (Ward) & Form EC8C (LGA Summary)'
                  : isStateOnly
                  ? 'State Collation Scope: Form EC8A, EC8B, EC8C & Form EC8D (State Summary)'
                  : 'Command Collation Scope: Complete Form EC8A, EC8B, EC8C, EC8D & EC8E Declaration'}
              </p>
            </div>
          </div>

          {/* Action Buttons: Template Toggle, CSV, and Print PDF */}
          <div className="flex items-center flex-wrap gap-2">
            {/* Blank Statutory Template vs Live Collation Data Toggle */}
            <div className="flex items-center bg-slate-900 border border-slate-700/80 rounded-xl p-0.5">
              <button
                type="button"
                onClick={() => setIsTemplateMode(false)}
                className={`px-2.5 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 ${
                  !isTemplateMode
                    ? 'bg-emerald-600 text-white shadow-xs'
                    : 'text-slate-400 hover:text-white'
                }`}
                title="View with Live Collation Data"
              >
                <CheckCircle2 className="w-3.5 h-3.5" />
                <span>Live Data</span>
              </button>
              <button
                type="button"
                onClick={() => setIsTemplateMode(true)}
                className={`px-2.5 py-1.5 rounded-lg text-xs font-black transition flex items-center gap-1.5 ${
                  isTemplateMode
                    ? 'bg-amber-500 text-slate-950 shadow-xs'
                    : 'text-slate-400 hover:text-white'
                }`}
                title="View and Print Blank Statutory INEC Form Template"
              >
                <FileText className="w-3.5 h-3.5" />
                <span>Blank Template</span>
              </button>
            </div>

            <button
              onClick={handleDownloadCsv}
              className="px-3 py-1.5 rounded-xl bg-emerald-700 hover:bg-emerald-600 text-white text-xs font-bold flex items-center gap-1.5 shadow transition"
              title={isTemplateMode ? 'Download Blank Statutory CSV Template' : 'Download Data as CSV Spreadsheet'}
            >
              <Download className="w-3.5 h-3.5" />
              <span>{isTemplateMode ? 'Blank CSV' : 'Export CSV'}</span>
            </button>

            <button
              onClick={handlePrintPdf}
              className="px-3.5 py-1.5 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 text-xs font-bold flex items-center gap-1.5 shadow transition"
              title="Print or Save Official Form as PDF"
            >
              <Printer className="w-3.5 h-3.5" />
              <span>Print / Save PDF</span>
            </button>

            <button
              onClick={onClose}
              className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition ml-1"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Level Tabs: EC8A, EC8B, EC8C, EC8D, EC8E (Screen Only, based on allowedForms) */}
        <div className="bg-slate-950/80 px-4 py-2 border-b border-slate-800 flex items-center gap-1.5 overflow-x-auto no-scrollbar print:hidden">
          {allowedForms.includes('EC8A') && (
            <button
              onClick={() => setActiveForm('EC8A')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 whitespace-nowrap ${
                activeForm === 'EC8A'
                  ? 'bg-amber-500 text-slate-950 shadow'
                  : 'bg-slate-900 text-slate-400 hover:text-white border border-slate-800'
              }`}
            >
              <span>Form EC8A</span>
              <span className="text-[10px] opacity-75 font-normal">(Polling Unit)</span>
            </button>
          )}

          {allowedForms.includes('EC8B') && (
            <button
              onClick={() => setActiveForm('EC8B')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 whitespace-nowrap ${
                activeForm === 'EC8B'
                  ? 'bg-amber-500 text-slate-950 shadow'
                  : 'bg-slate-900 text-slate-400 hover:text-white border border-slate-800'
              }`}
            >
              <span>Form EC8B</span>
              <span className="text-[10px] opacity-75 font-normal">(Ward Collation)</span>
            </button>
          )}

          {allowedForms.includes('EC8C') && (
            <button
              onClick={() => setActiveForm('EC8C')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 whitespace-nowrap ${
                activeForm === 'EC8C'
                  ? 'bg-amber-500 text-slate-950 shadow'
                  : 'bg-slate-900 text-slate-400 hover:text-white border border-slate-800'
              }`}
            >
              <span>Form EC8C</span>
              <span className="text-[10px] opacity-75 font-normal">(LGA Collation)</span>
            </button>
          )}

          {allowedForms.includes('EC8D') && (
            <button
              onClick={() => setActiveForm('EC8D')}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 whitespace-nowrap ${
                activeForm === 'EC8D'
                  ? 'bg-amber-500 text-slate-950 shadow'
                  : 'bg-slate-900 text-slate-400 hover:text-white border border-slate-800'
              }`}
            >
              <span>Form EC8D</span>
              <span className="text-[10px] opacity-75 font-normal">(State Collation)</span>
            </button>
          )}

          {allowedForms.includes('EC8E') && (
            <button
              onClick={() => setActiveForm('EC8E')}
              className={`px-3.5 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-1.5 whitespace-nowrap ${
                activeForm === 'EC8E'
                  ? 'bg-amber-500 text-slate-950 shadow'
                  : 'bg-slate-900 text-amber-300 hover:text-white border border-amber-500/40'
              }`}
            >
              <ShieldCheck className="w-3.5 h-3.5" />
              <span>Form EC8E</span>
              <span className="text-[10px] opacity-75 font-normal">(National Declaration)</span>
            </button>
          )}
        </div>

        {/* Cascading Delimitation Selectors (Screen Only, when not EC8E) */}
        {activeForm !== 'EC8E' && (
          <div className="bg-slate-900/90 px-4 py-2.5 border-b border-slate-800 flex flex-wrap items-center gap-2.5 text-xs print:hidden">
            {/* State Selector */}
            <div className="flex items-center gap-1.5">
              <span className="text-slate-400 font-semibold">State:</span>
              <select
                value={selectedStateId}
                onChange={(e) => handleStateChange(e.target.value)}
                className="bg-slate-950 text-white font-mono px-2.5 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-amber-500"
              >
                {NIGERIAN_STATES.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.id} - {s.name}
                  </option>
                ))}
              </select>
            </div>

            {/* LGA Selector (for EC8A, EC8B, EC8C) */}
            {(activeForm === 'EC8A' || activeForm === 'EC8B' || activeForm === 'EC8C') && (
              <div className="flex items-center gap-1.5">
                <span className="text-slate-400 font-semibold">LGA:</span>
                <select
                  value={selectedLgaId}
                  onChange={(e) => handleLgaChange(e.target.value)}
                  className="bg-slate-950 text-white font-mono px-2.5 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-amber-500"
                >
                  {currentLgas.map((lga) => (
                    <option key={lga.id} value={lga.id}>
                      {lga.name}
                    </option>
                  ))}
                </select>
              </div>
            )}

            {/* Ward Selector (for EC8A, EC8B) */}
            {(activeForm === 'EC8A' || activeForm === 'EC8B') && (
              <div className="flex items-center gap-1.5">
                <span className="text-slate-400 font-semibold">Ward:</span>
                <select
                  value={selectedWardId}
                  onChange={(e) => handleWardChange(e.target.value)}
                  className="bg-slate-950 text-white font-mono px-2.5 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-amber-500"
                >
                  {currentWards.map((w) => (
                    <option key={w.id} value={w.id}>
                      {w.name}
                    </option>
                  ))}
                </select>
              </div>
            )}

            {/* PU Selector (for EC8A only) */}
            {activeForm === 'EC8A' && (
              <div className="flex items-center gap-1.5">
                <span className="text-slate-400 font-semibold">PU:</span>
                <select
                  value={selectedPuCode}
                  onChange={(e) => setSelectedPuCode(e.target.value)}
                  className="bg-slate-950 text-white font-mono px-2.5 py-1 rounded-lg border border-slate-700 focus:outline-none focus:border-amber-500 max-w-[280px] truncate"
                >
                  {currentPus.map((p) => (
                    <option key={p.id} value={p.pu_code}>
                      {p.pu_name} [{p.pu_code}]
                    </option>
                  ))}
                </select>
              </div>
            )}
          </div>
        )}

        {/* Official Printable Form Canvas */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-8 bg-slate-950 print:bg-white print:text-black print:p-0">
          <div className="max-w-4xl mx-auto bg-slate-900 print:bg-white text-slate-100 print:text-black border-2 border-slate-700 print:border-black rounded-xl print:rounded-none p-6 sm:p-8 space-y-6 shadow-2xl">
            {/* Template Mode Watermark / Header Notice */}
            {isTemplateMode && (
              <div className="bg-amber-500/10 border-2 border-dashed border-amber-500/40 print:border-black text-amber-300 print:text-black p-3 rounded-xl text-center space-y-1">
                <div className="text-xs font-black uppercase tracking-widest font-mono">
                  ★ OFFICIAL STATUTORY BLANK RESULT SHEET TEMPLATE ★
                </div>
                <p className="text-[10px] text-slate-400 print:text-gray-700">
                  INEC Prescribed Physical Collation &amp; Polling Unit Record Form • Ready for Field Accreditation, Manual Count &amp; Physical Signatures
                </p>
              </div>
            )}

            {/* INEC Official Emblem & Form Heading */}
            <div className="text-center border-b-2 border-slate-700 print:border-black pb-4 space-y-1">
              <div className="text-[11px] font-black uppercase tracking-widest text-amber-400 print:text-black">
                FEDERAL REPUBLIC OF NIGERIA
              </div>
              <h1 className="text-lg sm:text-xl font-black uppercase tracking-wide text-white print:text-black">
                INDEPENDENT NATIONAL ELECTORAL COMMISSION (INEC)
              </h1>
              <div className="text-sm font-extrabold uppercase text-slate-300 print:text-black">
                PRESIDENTIAL ELECTION 2027
              </div>
              <div className="inline-block border-2 border-amber-500 print:border-black bg-amber-500/15 print:bg-transparent px-4 py-1 rounded font-mono font-black text-sm text-amber-300 print:text-black mt-2">
                {activeFormData.formTitle}
              </div>
              <p className="text-xs font-mono text-slate-400 print:text-gray-700 pt-1">
                {activeFormData.scopeDescription}
              </p>
            </div>

            {/* Delimitation & Ballot Accounting Grid */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs font-mono border border-slate-800 print:border-black p-3 rounded-lg bg-slate-950 print:bg-gray-50">
              <div>
                <span className="block text-[10px] text-slate-400 print:text-gray-600">1. REGISTERED VOTERS</span>
                <span className="text-sm font-bold text-white print:text-black">
                  {isTemplateMode ? '________________' : activeFormData.registeredVoters.toLocaleString()}
                </span>
              </div>
              <div>
                <span className="block text-[10px] text-slate-400 print:text-gray-600">2. BVAS ACCREDITED</span>
                <span className="text-sm font-bold text-emerald-400 print:text-black">
                  {isTemplateMode ? '________________' : activeFormData.accreditedVoters.toLocaleString()}
                </span>
              </div>
              <div>
                <span className="block text-[10px] text-slate-400 print:text-gray-600">3. TOTAL VALID VOTES</span>
                <span className="text-sm font-bold text-amber-400 print:text-black">
                  {isTemplateMode ? '________________' : activeFormData.validVotes.toLocaleString()}
                </span>
              </div>
              <div>
                <span className="block text-[10px] text-slate-400 print:text-gray-600">4. REJECTED BALLOTS</span>
                <span className="text-sm font-bold text-red-400 print:text-black">
                  {isTemplateMode ? '________________' : activeFormData.rejectedBallots.toLocaleString()}
                </span>
              </div>
              {isTemplateMode && (
                <>
                  <div>
                    <span className="block text-[10px] text-slate-400 print:text-gray-600">5. BALLOTS ISSUED</span>
                    <span className="text-sm font-bold text-slate-300 print:text-black">________________</span>
                  </div>
                  <div>
                    <span className="block text-[10px] text-slate-400 print:text-gray-600">6. UNUSED BALLOTS</span>
                    <span className="text-sm font-bold text-slate-300 print:text-black">________________</span>
                  </div>
                  <div>
                    <span className="block text-[10px] text-slate-400 print:text-gray-600">7. SPOILED BALLOTS</span>
                    <span className="text-sm font-bold text-slate-300 print:text-black">________________</span>
                  </div>
                  <div>
                    <span className="block text-[10px] text-slate-400 print:text-gray-600">8. BVAS SERIAL NO.</span>
                    <span className="text-sm font-bold text-slate-300 print:text-black">BVAS-2027-_______</span>
                  </div>
                </>
              )}
            </div>

            {/* Political Party Results Table */}
            <div className="border border-slate-700 print:border-black rounded-lg overflow-hidden">
              <div className="bg-slate-800 print:bg-gray-200 px-4 py-2 border-b border-slate-700 print:border-black flex items-center justify-between">
                <span className="text-xs font-black uppercase tracking-wider text-amber-400 print:text-black">
                  SCORES OF POLITICAL PARTIES
                </span>
                <span className="text-[10px] font-mono text-slate-400 print:text-black">
                  Section 60 &amp; 64 of Electoral Act 2022
                </span>
              </div>

              <table className="w-full text-left text-xs">
                <thead className="bg-slate-900 print:bg-gray-100 text-slate-400 print:text-black font-mono text-[10px] uppercase border-b border-slate-700 print:border-black">
                  <tr>
                    <th className="p-2.5">S/N</th>
                    <th className="p-2.5">Party</th>
                    <th className="p-2.5">Presidential Candidate</th>
                    <th className="p-2.5 text-right">Votes in Figures</th>
                    <th className="p-2.5">Votes in Words</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-800 print:divide-gray-300 font-mono">
                  {/* ADC Row */}
                  <tr className="bg-purple-950/30 print:bg-gray-100 font-bold">
                    <td className="p-2.5 text-amber-400 print:text-black">1</td>
                    <td className="p-2.5 font-black text-white print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-purple-500" />
                      <span>ADC</span>
                    </td>
                    <td className="p-2.5 text-amber-300 print:text-black font-sans font-bold">
                      H.E. ATIKU ABUBAKAR (GCON)
                    </td>
                    <td className="p-2.5 text-right font-black text-white print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('ADC').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-300 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('ADC'))}
                    </td>
                  </tr>

                  {/* APC Row */}
                  <tr className="hover:bg-slate-800/40 print:hover:bg-transparent">
                    <td className="p-2.5 text-slate-400 print:text-black">2</td>
                    <td className="p-2.5 font-bold text-slate-200 print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-blue-500" />
                      <span>APC</span>
                    </td>
                    <td className="p-2.5 text-slate-300 print:text-black font-sans">Bola Ahmed Tinubu</td>
                    <td className="p-2.5 text-right font-bold text-slate-200 print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('APC').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('APC'))}
                    </td>
                  </tr>

                  {/* LP Row */}
                  <tr className="hover:bg-slate-800/40 print:hover:bg-transparent">
                    <td className="p-2.5 text-slate-400 print:text-black">3</td>
                    <td className="p-2.5 font-bold text-slate-200 print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
                      <span>LP</span>
                    </td>
                    <td className="p-2.5 text-slate-300 print:text-black font-sans">Peter Obi</td>
                    <td className="p-2.5 text-right font-bold text-slate-200 print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('LP').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('LP'))}
                    </td>
                  </tr>

                  {/* PDP Row */}
                  <tr className="hover:bg-slate-800/40 print:hover:bg-transparent">
                    <td className="p-2.5 text-slate-400 print:text-black">4</td>
                    <td className="p-2.5 font-bold text-slate-200 print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-red-500" />
                      <span>PDP</span>
                    </td>
                    <td className="p-2.5 text-slate-300 print:text-black font-sans">Presidential Candidate</td>
                    <td className="p-2.5 text-right font-bold text-slate-200 print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('PDP').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('PDP'))}
                    </td>
                  </tr>

                  {/* NNPP Row */}
                  <tr className="hover:bg-slate-800/40 print:hover:bg-transparent">
                    <td className="p-2.5 text-slate-400 print:text-black">5</td>
                    <td className="p-2.5 font-bold text-slate-200 print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-amber-500" />
                      <span>NNPP</span>
                    </td>
                    <td className="p-2.5 text-slate-300 print:text-black font-sans">Rabiu Musa Kwankwaso</td>
                    <td className="p-2.5 text-right font-bold text-slate-200 print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('NNPP').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('NNPP'))}
                    </td>
                  </tr>

                  {/* SDP Row */}
                  <tr className="hover:bg-slate-800/40 print:hover:bg-transparent">
                    <td className="p-2.5 text-slate-400 print:text-black">6</td>
                    <td className="p-2.5 font-bold text-slate-200 print:text-black flex items-center gap-1.5">
                      <span className="w-2.5 h-2.5 rounded-full bg-yellow-500" />
                      <span>SDP</span>
                    </td>
                    <td className="p-2.5 text-slate-300 print:text-black font-sans">Adewole Adebayo</td>
                    <td className="p-2.5 text-right font-bold text-slate-200 print:text-black text-sm">
                      {isTemplateMode ? '[  ____________________  ]' : getVote('SDP').toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(getVote('SDP'))}
                    </td>
                  </tr>

                  {/* Total Valid Votes Row */}
                  <tr className="bg-slate-950 print:bg-gray-200 font-extrabold text-sm border-t-2 border-slate-700 print:border-black">
                    <td colSpan={3} className="p-3 text-right uppercase text-white print:text-black">
                      TOTAL VALID VOTES (A)
                    </td>
                    <td className="p-3 text-right text-emerald-400 print:text-black">
                      {isTemplateMode ? '[  ____________________  ]' : activeFormData.validVotes.toLocaleString()}
                    </td>
                    <td className="p-3 text-xs text-slate-300 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(activeFormData.validVotes)}
                    </td>
                  </tr>

                  {/* Rejected Ballots Row */}
                  <tr className="bg-slate-950 print:bg-gray-100 font-bold text-xs">
                    <td colSpan={3} className="p-2.5 text-right uppercase text-red-400 print:text-black">
                      REJECTED BALLOTS (B)
                    </td>
                    <td className="p-2.5 text-right text-red-400 print:text-black">
                      {isTemplateMode ? '[  ____________________  ]' : activeFormData.rejectedBallots.toLocaleString()}
                    </td>
                    <td className="p-2.5 text-[11px] text-slate-400 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(activeFormData.rejectedBallots)}
                    </td>
                  </tr>

                  {/* Total Votes Cast Row */}
                  <tr className="bg-slate-900 print:bg-gray-300 font-black text-sm border-t border-slate-700 print:border-black">
                    <td colSpan={3} className="p-3 text-right uppercase text-amber-300 print:text-black">
                      TOTAL VOTES CAST (A + B)
                    </td>
                    <td className="p-3 text-right text-amber-300 print:text-black">
                      {isTemplateMode ? '[  ____________________  ]' : activeFormData.totalVotesCast.toLocaleString()}
                    </td>
                    <td className="p-3 text-xs text-slate-200 print:text-black uppercase">
                      {isTemplateMode ? '____________________________________________________________' : numberToWords(activeFormData.totalVotesCast)}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* National 37 Jurisdictions Table (Rendered only on Form EC8E) */}
            {activeForm === 'EC8E' && (
              <div className="space-y-2 border border-slate-700 print:border-black rounded-lg p-3 bg-slate-950 print:bg-white">
                <div className="flex items-center justify-between pb-1 border-b border-slate-800 print:border-black">
                  <span className="text-xs font-bold text-white print:text-black uppercase">
                    Annexure 1: Nationwide 37 State Collation Breakdown (36 States + FCT Abuja)
                  </span>
                  <span className="text-[10px] font-mono text-emerald-400 print:text-black">
                    {isTemplateMode ? 'Master State Entry Collation Roster' : '100% PUs Collated'}
                  </span>
                </div>
                <div className="overflow-x-auto max-h-60 overflow-y-auto">
                  <table className="w-full text-left text-[11px] font-mono">
                    <thead className="bg-slate-900 print:bg-gray-100 text-slate-400 print:text-black text-[9px] uppercase sticky top-0">
                      <tr>
                        <th className="p-1.5">Code</th>
                        <th className="p-1.5">State</th>
                        <th className="p-1.5 text-right">ADC (Atiku)</th>
                        <th className="p-1.5 text-right">APC (Tinubu)</th>
                        <th className="p-1.5 text-right">PDP</th>
                        <th className="p-1.5 text-right">LP (Obi)</th>
                        <th className="p-1.5 text-right">Total Valid</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-800 print:divide-gray-300">
                      {NIGERIAN_STATES.map((s) => (
                        <tr key={s.id} className="hover:bg-slate-900/50">
                          <td className="p-1.5 text-slate-400 print:text-black">{s.id}</td>
                          <td className="p-1.5 font-bold text-white print:text-black">{s.name}</td>
                          <td className="p-1.5 text-right text-amber-300 print:text-black font-bold">
                            {isTemplateMode ? '______' : (s.votes?.ADC || 0).toLocaleString()}
                          </td>
                          <td className="p-1.5 text-right text-slate-300 print:text-black">
                            {isTemplateMode ? '______' : (s.votes?.APC || 0).toLocaleString()}
                          </td>
                          <td className="p-1.5 text-right text-slate-300 print:text-black">
                            {isTemplateMode ? '______' : (s.votes?.PDP || 0).toLocaleString()}
                          </td>
                          <td className="p-1.5 text-right text-slate-300 print:text-black">
                            {isTemplateMode ? '______' : (s.votes?.LP || 0).toLocaleString()}
                          </td>
                          <td className="p-1.5 text-right text-slate-300 print:text-black">
                            {isTemplateMode ? '______' : ((s.votes?.ADC || 0) + (s.votes?.APC || 0) + (s.votes?.PDP || 0) + (s.votes?.LP || 0)).toLocaleString()}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* Official Certification & Signatures Box */}
            <div className="border-t-2 border-slate-700 print:border-black pt-4 space-y-4 text-xs">
              <div className="italic text-slate-300 print:text-black leading-relaxed">
                &ldquo;I hereby certify that the information contained in this form is a true, accurate, and complete record of votes cast at this collation center under the Electoral Act 2022.&rdquo;
              </div>

              {/* Collation Officer & Official INEC Embossed Stamp Box */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 pt-2">
                {/* Collation Officer Box */}
                <div className="p-3.5 border border-slate-800 print:border-black rounded-xl bg-slate-950 print:bg-transparent space-y-3">
                  <div className="text-[10px] font-bold uppercase tracking-wider text-amber-400 print:text-black">
                    {activeFormData.officerTitle}
                  </div>
                  <div>
                    <span className="text-[10px] text-slate-400 print:text-gray-600 block">Name of Officer:</span>
                    <div className="pt-2 border-b border-dashed border-slate-700 print:border-black font-serif italic text-white print:text-black text-sm">
                      {isTemplateMode ? '________________________________________________' : activeFormData.officerName}
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-[10px] text-slate-400 print:text-black font-mono pt-1">
                    <div>
                      <span>Officer ID / Phone:</span>
                      <span className="block text-white print:text-black font-bold">
                        {isTemplateMode ? '____________________' : 'INEC-OFF-84920'}
                      </span>
                    </div>
                    <div>
                      <span>Date &amp; Time:</span>
                      <span className="block text-white print:text-black font-bold">
                        {isTemplateMode ? '____/____/2027  ___:___' : 'Election Night 2027'}
                      </span>
                    </div>
                  </div>
                  <div>
                    <span className="text-[10px] text-slate-400 print:text-gray-600 block">Official Signature:</span>
                    <div className="pt-5 border-b border-dashed border-slate-700 print:border-black"></div>
                  </div>
                </div>

                {/* Official INEC Prescribed Stamp & Seal Box */}
                <div className="p-4 border-2 border-dashed border-amber-500/50 print:border-black rounded-xl bg-amber-500/5 print:bg-white flex flex-col items-center justify-center text-center space-y-2 min-h-[140px]">
                  <div className="w-10 h-10 rounded-full border border-amber-500/40 print:border-black flex items-center justify-center text-amber-400 print:text-black">
                    <ShieldCheck className="w-5 h-5" />
                  </div>
                  <span className="font-bold uppercase tracking-wider text-xs text-amber-300 print:text-black">
                    OFFICIAL INEC STAMP &amp; SEAL
                  </span>
                  <span className="text-[10px] text-slate-400 print:text-gray-600">
                    (Prescribed Ink Impression &amp; Endorsement Date Required Here)
                  </span>
                </div>
              </div>

              {/* Accredited Party Agents Signing Roster */}
              <div className="mt-4 border border-slate-800 print:border-black rounded-xl p-3 bg-slate-950/70 print:bg-transparent space-y-2">
                <div className="flex items-center justify-between pb-1.5 border-b border-slate-800 print:border-black">
                  <span className="text-xs font-bold text-white print:text-black uppercase">
                    Accredited Political Party Agents Endorsement Roster (Section 60 &amp; 62)
                  </span>
                  <span className="text-[10px] font-mono text-slate-400 print:text-black">
                    Statutory Signatures
                  </span>
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs font-mono">
                    <thead className="bg-slate-900 print:bg-gray-100 text-[10px] text-slate-400 print:text-black uppercase">
                      <tr>
                        <th className="p-2">Party</th>
                        <th className="p-2">Accredited Agent Full Name</th>
                        <th className="p-2">Phone / Voter ID</th>
                        <th className="p-2">Signature</th>
                        <th className="p-2 text-center">Thumbprint</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-800 print:divide-gray-300">
                      {[
                        { party: 'ADC', agent: isTemplateMode ? '' : 'Amb. Dr. Ralph Nwosu / Ibrahim Danjuma', color: 'text-purple-400' },
                        { party: 'APC', agent: isTemplateMode ? '' : 'Festus Keyamo / Babatunde Ogala', color: 'text-blue-400' },
                        { party: 'LP', agent: isTemplateMode ? '' : 'Doyin Okupe / Kenneth Okonkwo', color: 'text-emerald-400' },
                        { party: 'PDP', agent: isTemplateMode ? '' : 'Dino Melaye / Osita Chidoka', color: 'text-rose-400' },
                        { party: 'NNPP', agent: isTemplateMode ? '' : 'Buba Galadima / Ladipo Johnson', color: 'text-amber-400' },
                        { party: 'SDP', agent: isTemplateMode ? '' : 'Adewole Adebayo Rep.', color: 'text-yellow-400' },
                      ].map((pRow, idx) => (
                        <tr key={pRow.party} className="hover:bg-slate-900/40">
                          <td className={`p-2 font-black ${pRow.color} print:text-black`}>
                            {pRow.party}
                          </td>
                          <td className="p-2 text-white print:text-black">
                            {pRow.agent || '__________________________________'}
                          </td>
                          <td className="p-2 text-slate-400 print:text-black">
                            {isTemplateMode ? '____________________' : `0803-000-${1000 + idx}`}
                          </td>
                          <td className="p-2 text-slate-400 print:text-black">
                            {isTemplateMode ? '____________________' : '✓ Signed & Verified'}
                          </td>
                          <td className="p-2 text-center">
                            <span className="inline-block w-8 h-8 border border-dashed border-slate-700 print:border-black rounded text-[9px] text-slate-500 flex items-center justify-center">
                              Ink
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Evidence Act Section 84 Forensic Stamp */}
              <div className="p-2.5 rounded-lg bg-slate-950 print:bg-gray-100 border border-slate-800 print:border-black flex flex-col sm:flex-row items-center justify-between gap-2 text-[10px] font-mono text-slate-400 print:text-black">
                <span className="flex items-center gap-1.5">
                  <Fingerprint className="w-3.5 h-3.5 text-amber-400 print:text-black" />
                  <span>Evidence Act 2011 Sec 84 SHA-256 Stamp:</span>
                  <code className="text-amber-300 print:text-black font-bold select-all">
                    {isTemplateMode ? 'STATUTORY-INEC-BLANK-FORM-TEMPLATE-SERIES-2027' : formHash}
                  </code>
                </span>
                <span className="text-emerald-400 print:text-black font-bold">
                  {isTemplateMode ? 'Statutory Electoral Document' : 'Certified Legal Exhibit'}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
