'use client';

import React, { useState, useRef } from 'react';
import {
  Play,
  CheckCircle2,
  FileCheck2,
  Scale,
  AlertTriangle,
  BookOpen,
  X,
  MessageSquare,
  ShieldCheck,
  Camera,
  RotateCw,
  Sparkles,
  Upload,
  Scan,
  Maximize2,
  ArrowRight
} from 'lucide-react';
import { ALL_18_POLITICAL_PARTIES } from '@/lib/electoralData';

interface Props {
  puCode: string;
  onNext: (data: any) => void;
}

interface ValidationScenario {
  id: string;
  title: string;
  category: 'CONFUSION_RESOLVED' | 'INVALID_BALLOT';
  ruling: 'VALID_VOTE' | 'REJECTED_INVALID';
  partyScored: string;
  thumbprintDesc: string;
  citedRule: string;
  poSpeech: string;
  recommendation: string;
  sampleImage: string;
}

const BALLOT_VALIDATION_RULES: ValidationScenario[] = [
  {
    id: 'scen-1',
    title: '1. Thumbprint Touches Border Line of ADC Box',
    category: 'CONFUSION_RESOLVED',
    ruling: 'VALID_VOTE',
    partyScored: 'ADC (African Democratic Congress - H.E. Atiku Abubakar 🤝)',
    thumbprintDesc: 'Thumbprint impression falls inside or touches the border line of ADC box, but clear voter intent favors ADC.',
    citedRule: 'INEC Regulations & Guidelines 2023 Reg 41(2) & Electoral Act Sec 52(2)',
    poSpeech: '“Presiding Officer, Regulation 41(2) stipulates that where a voter’s mark falls on or touches the border line of a party box, but the discernible intent points to ADC, the vote MUST be declared VALID for ADC!”',
    recommendation: 'Insist that PO counts this ballot as a VALID vote for ADC (H.E. Atiku Abubakar). Do NOT allow rivals to reject it.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23cbd5e1" stroke-width="2"/><text x="40" y="50" font-family="sans-serif" font-size="12" font-weight="bold" fill="%230f172a">INEC OFFICIAL BALLOT PAPER</text><rect x="40" y="70" width="320" height="50" rx="4" fill="%23ecfdf5" stroke="%23059669" stroke-width="2"/><text x="50" y="100" font-family="sans-serif" font-size="14" font-weight="bold" fill="%23047857">ADC [🤝 ATIKU]</text><circle cx="310" cy="95" r="14" fill="%23059669" opacity="0.8"/><text x="40" y="150" font-family="sans-serif" font-size="11" fill="%2364748b">VOTER THUMBPRINT TOUCHES ADC BORDER</text><text x="40" y="175" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23059669">LEGAL RULING: VALID FOR ADC (Reg 41.2)</text></svg>',
  },
  {
    id: 'scen-2',
    title: '2. Thumbprint Inside ADC Party Logo / Emblem Area',
    category: 'CONFUSION_RESOLVED',
    ruling: 'VALID_VOTE',
    partyScored: 'ADC (African Democratic Congress - H.E. Atiku Abubakar 🤝)',
    thumbprintDesc: 'Voter marked or thumbprinted directly over the ADC Zebra emblem or acronym text rather than the small square box.',
    citedRule: 'INEC Manual for Election Officials Reg 41(1)',
    poSpeech: '“Presiding Officer, Regulation 41(1) states clearly that a mark anywhere inside the designated party space—including the logo or name—is a VALID vote for that party!”',
    recommendation: 'Declare VALID for ADC. The logo area is legally recognized as party voting space.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23cbd5e1" stroke-width="2"/><text x="40" y="50" font-family="sans-serif" font-size="12" font-weight="bold" fill="%230f172a">INEC OFFICIAL BALLOT PAPER</text><rect x="40" y="70" width="320" height="50" rx="4" fill="%23ecfdf5" stroke="%23059669" stroke-width="2"/><circle cx="100" cy="95" r="14" fill="%23059669" opacity="0.85"/><text x="130" y="100" font-family="sans-serif" font-size="14" font-weight="bold" fill="%23047857">ADC [🤝 EMBLEM]</text><text x="40" y="150" font-family="sans-serif" font-size="11" fill="%2364748b">THUMBPRINT ON ADC PARTY EMBLEM</text><text x="40" y="175" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23059669">LEGAL RULING: VALID FOR ADC (Reg 41.1)</text></svg>',
  },
  {
    id: 'scen-3',
    title: '3. Faint Smudge / Oil Mark Alongside Clear ADC Thumbprint',
    category: 'CONFUSION_RESOLVED',
    ruling: 'VALID_VOTE',
    partyScored: 'ADC (African Democratic Congress - H.E. Atiku Abubakar 🤝)',
    thumbprintDesc: 'Ballot has a clear thumbprint for ADC, plus a faint accidental ink smear or oil smudge elsewhere.',
    citedRule: 'INEC Manual Reg 41(3) & Court of Appeal Electoral Jurisprudence',
    poSpeech: '“Presiding Officer, accidental smears or secondary smudges do NOT invalidate a clear primary thumbprint. This is a VALID vote for ADC under Regulation 41(3)!”',
    recommendation: 'Count as VALID for ADC. Secondary smudges are not grounds for ballot rejection.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23cbd5e1" stroke-width="2"/><rect x="40" y="70" width="320" height="50" rx="4" fill="%23ecfdf5" stroke="%23059669"/><text x="50" y="100" font-family="sans-serif" font-size="14" font-weight="bold" fill="%23047857">ADC [PRIMARY VOTE]</text><circle cx="310" cy="95" r="15" fill="%23047857"/><circle cx="80" cy="180" r="4" fill="%2394a3b8" opacity="0.3"/><text x="40" y="150" font-family="sans-serif" font-size="11" fill="%2364748b">PRIMARY INTENT CLEAR FOR ADC</text><text x="40" y="175" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23059669">LEGAL RULING: VALID (Reg 41.3 Smudge Rule)</text></svg>',
  },
  {
    id: 'scen-4',
    title: '4. Thumbprint Equally Straddling Two Party Boxes (Ambiguous)',
    category: 'INVALID_BALLOT',
    ruling: 'REJECTED_INVALID',
    partyScored: 'NONE (INVALID / REJECTED BALLOT)',
    thumbprintDesc: 'Thumbprint is positioned 50/50 across two party boxes with zero clear preference for either party.',
    citedRule: 'Electoral Act 2022 Section 63(1)(b) - Ambiguous Voter Intent',
    poSpeech: '“Presiding Officer, under Section 63(1)(b) of the Electoral Act 2022, because it is impossible to determine which party the voter intended, this ballot paper MUST be marked REJECTED.”',
    recommendation: 'Classify as REJECTED / INVALID BALLOT. Ensure it is placed in the official Rejected Ballots envelope.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23cbd5e1" stroke-width="2"/><rect x="40" y="70" width="320" height="40" fill="%23f1f5f9" stroke="%2394a3b8"/><rect x="40" y="115" width="320" height="40" fill="%23f1f5f9" stroke="%2394a3b8"/><circle cx="200" cy="115" r="15" fill="%23e11d48"/><text x="40" y="180" font-family="sans-serif" font-size="11" fill="%23e11d48">THUMBPRINT SPLIT 50/50 ACROSS TWO PARTIES</text><text x="40" y="205" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23e11d48">LEGAL RULING: REJECTED (Sec 63.1.b)</text></svg>',
  },
  {
    id: 'scen-5',
    title: '5. Missing INEC Stamp or PO Signature on Back of Ballot Paper',
    category: 'INVALID_BALLOT',
    ruling: 'REJECTED_INVALID',
    partyScored: 'NONE (INVALID / REJECTED BALLOT)',
    thumbprintDesc: 'Ballot paper lacks the official INEC official stamp or Presiding Officer signature on the reverse side.',
    citedRule: 'Electoral Act 2022 Section 63(1)(a) & Sec 51',
    poSpeech: '“Presiding Officer, Section 63(1)(a) requires all valid ballots to bear the official INEC stamp. Unless you confirm this was your administrative omission from the official booklet and endorse it now, it cannot be counted!”',
    recommendation: 'Challenge the ballot immediately. If PO admits omission, PO must sign back before counting; otherwise REJECT.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23e11d48" stroke-dasharray="6" stroke-width="2"/><text x="40" y="80" font-family="sans-serif" font-size="14" font-weight="bold" fill="%23e11d48">MISSING OFFICIAL INEC STAMP</text><text x="40" y="110" font-family="sans-serif" font-size="11" fill="%2364748b">NO PO SIGNATURE ON REVERSE SIDE</text><text x="40" y="160" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23e11d48">LEGAL RULING: UNENDORSED / REJECTED (Sec 63.1.a)</text></svg>',
  },
  {
    id: 'scen-6',
    title: '6. Ballot Marked with Name, Signature or Written Identifier',
    category: 'INVALID_BALLOT',
    ruling: 'REJECTED_INVALID',
    partyScored: 'NONE (INVALID / REJECTED BALLOT)',
    thumbprintDesc: 'Voter wrote their name, initials, phone number, or signature on the ballot paper.',
    citedRule: 'Electoral Act 2022 Section 62 - Breach of Secret Ballot',
    poSpeech: '“Presiding Officer, writing any name or mark by which the voter can be identified violates secret balloting under Section 62. This ballot MUST be REJECTED.”',
    recommendation: 'Mandatory REJECTED ballot. Secrecy of the vote is strictly protected by law.',
    sampleImage: 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><rect width="400" height="300" fill="%23f8fafc"/><rect x="20" y="20" width="360" height="260" rx="8" fill="white" stroke="%23cbd5e1" stroke-width="2"/><text x="40" y="70" font-family="sans-serif" font-size="13" font-weight="bold" fill="%23e11d48">WRITTEN IDENTITY MARK DETECTED</text><text x="40" y="100" font-family="cursive" font-size="16" fill="%230f172a">"Aliyu John 08031234567"</text><text x="40" y="150" font-family="sans-serif" font-size="11" fill="%2364748b">VIOLATION OF SECRECY OF THE BALLOT</text><text x="40" y="180" font-family="sans-serif" font-size="12" font-weight="bold" fill="%23e11d48">LEGAL RULING: REJECTED (Sec 62)</text></svg>',
  }
];

export const Step5SortingProcess: React.FC<Props> = ({ puCode, onNext }) => {
  // Camera Validation Window States
  const [showCameraModal, setShowCameraModal] = useState<boolean>(false);
  const [isScanningPhoto, setIsScanningPhoto] = useState<boolean>(false);
  const [snappedBallotImage, setSnappedBallotImage] = useState<string | null>(null);
  const [scanResult, setScanResult] = useState<{
    ruling: 'VALID_VOTE' | 'REJECTED_INVALID';
    partyScored: string;
    confidence: number;
    scenario: ValidationScenario;
    boundingCoordinates: { x: number; y: number; width: number; height: number };
  } | null>(null);

  // Selected Scenario State
  const [selectedScenario, setSelectedScenario] = useState<ValidationScenario | null>(null);
  const [showGuideModal, setShowGuideModal] = useState<boolean>(false);
  const [copiedSpeech, setCopiedSpeech] = useState<boolean>(false);
  const [isSubmitted, setIsSubmitted] = useState<boolean>(false);

  const fileInputRef = useRef<HTMLInputElement>(null);

  // Handle Photo Upload & AI Scan Simulation
  const handlePhotoCapture = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          processBallotPhoto(event.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const processBallotPhoto = (imageSrc: string) => {
    setSnappedBallotImage(imageSrc);
    setIsScanningPhoto(true);
    setShowCameraModal(true);

    // Simulate real-time visual scanning HUD calculation
    setTimeout(() => {
      setIsScanningPhoto(false);
      // Randomly pick a realistic scenario or default to ADC Border Line Rule
      const mockScenario = BALLOT_VALIDATION_RULES[0];
      setScanResult({
        ruling: 'VALID_VOTE',
        partyScored: 'ADC (African Democratic Congress - H.E. Atiku Abubakar 🤝)',
        confidence: 98.4,
        scenario: mockScenario,
        boundingCoordinates: { x: 38, y: 42, width: 24, height: 18 },
      });
      setSelectedScenario(mockScenario);
    }, 1800);
  };

  const handleCopySpeech = (speechText: string) => {
    navigator.clipboard.writeText(speechText);
    setCopiedSpeech(true);
    setTimeout(() => setCopiedSpeech(false), 2500);
  };

  const handleSubmitStep5 = (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitted(true);
    onNext({
      sortingCompleted: true,
      lastValidatedScenario: scanResult?.scenario?.id || selectedScenario?.id || 'NO_DISPUTE',
      timestamp: new Date().toISOString(),
    });
  };

  return (
    <div className="bg-white text-slate-900 border border-emerald-900/20 rounded-2xl p-5 shadow-xl font-sans">
      <input
        type="file"
        ref={fileInputRef}
        accept="image/*"
        capture="environment"
        onChange={handlePhotoCapture}
        className="hidden"
      />

      {/* Stage Header */}
      <div className="border-b border-emerald-100 pb-3 mb-4 flex items-center justify-between">
        <div>
          <span className="text-[10px] font-bold text-emerald-800 bg-emerald-100 px-2.5 py-0.5 rounded-full uppercase tracking-wider">
            5. Statutory Ballot Validation (2:30 PM - 4:00 PM)
          </span>
          <h2 className="text-lg font-black text-emerald-950 mt-1">
            INEC Statutory Ballot Validation Window
          </h2>
          <p className="text-xs text-slate-500">
            Snap disputed ballot papers for legal ruling &amp; PO defense speech (No tally counting per Electoral Act).
          </p>
        </div>

        <button
          type="button"
          onClick={() => setShowGuideModal(true)}
          className="p-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold flex items-center gap-1.5 border border-slate-300"
        >
          <BookOpen className="w-4 h-4 text-emerald-700" />
          <span className="hidden sm:inline">INEC Rule Handbook</span>
        </button>
      </div>

      {/* Main Action Banner: Launch Camera Validation Window */}
      <div className="bg-gradient-to-br from-slate-950 via-slate-900 to-emerald-950 text-white rounded-2xl p-5 border border-emerald-500/40 shadow-2xl relative overflow-hidden mb-6">
        <div className="absolute -right-6 -bottom-6 w-32 h-32 bg-emerald-500/10 rounded-full blur-2xl pointer-events-none" />

        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div className="space-y-1">
            <div className="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-500/20 border border-emerald-400/40 text-emerald-300 text-[10px] font-extrabold uppercase tracking-wider">
              <Sparkles className="w-3 h-3 text-emerald-300 animate-pulse" /> Live Camera Scanner Active
            </div>
            <h3 className="text-lg font-black text-white tracking-wide">
              Disputed Ballot Camera Validation
            </h3>
            <p className="text-xs text-slate-300 max-w-lg">
              Snap a photo of any confusing or disputed ballot paper to get instant INEC statutory ruling, party determination, and verbatim PO defense speech.
            </p>
          </div>

          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            className="w-full sm:w-auto px-5 py-3 rounded-xl bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-400 hover:to-emerald-500 text-slate-950 font-black text-xs uppercase tracking-wider shadow-lg hover:shadow-emerald-500/30 transition active:scale-95 flex items-center justify-center gap-2 shrink-0 cursor-pointer"
          >
            <Camera className="w-4.5 h-4.5" />
            <span>📸 Snap Ballot Photo</span>
          </button>
        </div>
      </div>

      {/* Statutory Guidance Scenarios Accordion */}
      <div className="space-y-3 mb-6">
        <h3 className="text-xs font-extrabold text-slate-700 uppercase tracking-wider flex items-center justify-between">
          <span>Official INEC Electoral Guidelines &amp; Common Dispute Scenarios</span>
          <span className="text-[10px] text-emerald-700 font-bold">Tap scenario to inspect PO speech</span>
        </h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {BALLOT_VALIDATION_RULES.map((scen) => {
            const isSelected = selectedScenario?.id === scen.id;
            const isValid = scen.ruling === 'VALID_VOTE';

            return (
              <div
                key={scen.id}
                onClick={() => setSelectedScenario(scen)}
                className={`p-3.5 rounded-xl border-2 cursor-pointer transition-all ${
                  isSelected
                    ? isValid
                      ? 'bg-purple-50/90 border-purple-600 shadow-md ring-1 ring-purple-500'
                      : 'bg-rose-50/90 border-rose-600 shadow-md ring-1 ring-rose-500'
                    : 'bg-slate-50 border-slate-200 hover:border-slate-300'
                }`}
              >
                <div className="flex items-start justify-between gap-2">
                  <span
                    className={`text-[10px] font-extrabold px-2 py-0.5 rounded-md uppercase ${
                      isValid
                        ? 'bg-purple-700 text-white'
                        : 'bg-rose-700 text-white'
                    }`}
                  >
                    {isValid ? 'VALID VOTE' : 'REJECTED / INVALID'}
                  </span>

                  <span className="text-[10px] font-mono text-slate-500">{scen.citedRule}</span>
                </div>

                <h4 className="font-extrabold text-slate-900 text-xs mt-2">{scen.title}</h4>
                <p className="text-[11px] text-slate-600 mt-1 line-clamp-2">{scen.thumbprintDesc}</p>

                <div className="mt-2 text-[10px] font-bold text-purple-900 flex items-center justify-between border-t border-slate-200 pt-1.5">
                  <span>Party: {scen.partyScored}</span>
                  <span className="text-emerald-700 font-extrabold flex items-center gap-0.5">
                    View PO Speech &rarr;
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Display Active Selected Scenario Legal Defense Box */}
      {selectedScenario && (
        <div className="bg-slate-900 text-white rounded-2xl p-4 border border-emerald-500/40 shadow-xl space-y-3 mb-6">
          <div className="flex items-center justify-between border-b border-slate-800 pb-2">
            <span className="text-xs font-extrabold text-emerald-400 flex items-center gap-1.5">
              <Scale className="w-4 h-4 text-emerald-400" /> Statutory Legal Defense &amp; PO Speech
            </span>
            <span className="text-[10px] bg-slate-800 text-slate-300 px-2 py-0.5 rounded">
              {selectedScenario.citedRule}
            </span>
          </div>

          <div className="bg-slate-950 p-3 rounded-xl border border-slate-800">
            <p className="text-xs font-bold text-amber-300 uppercase tracking-wider mb-1 flex items-center gap-1">
              <MessageSquare className="w-3.5 h-3.5 text-amber-400" /> Read Out Loud to the Presiding Officer (PO):
            </p>
            <p className="text-xs text-slate-200 italic leading-relaxed font-mono bg-slate-900/90 p-2.5 rounded-lg border border-slate-800">
              {selectedScenario.poSpeech}
            </p>
            <button
              type="button"
              onClick={() => handleCopySpeech(selectedScenario.poSpeech)}
              className="mt-2 px-3 py-1 bg-amber-500 hover:bg-amber-400 text-slate-950 text-[10px] font-black rounded-lg transition"
            >
              {copiedSpeech ? '✓ Copy Verbatim Speech' : '📋 Copy Speech Text'}
            </button>
          </div>
        </div>
      )}

      {/* Form Submit & Navigation */}
      <form onSubmit={handleSubmitStep5} className="space-y-3">
        <button
          type="submit"
          className="w-full py-3.5 px-4 rounded-xl bg-[#065F46] hover:bg-[#047857] text-white font-black text-sm shadow-md transition active:scale-98 flex items-center justify-center gap-2"
        >
          {isSubmitted && <CheckCircle2 className="w-4 h-4 text-emerald-300" />}
          <span>Proceed to Stage 6 (Official Form EC8A Result Entry)</span>
          <ArrowRight className="w-4 h-4" />
        </button>

        <p className="text-[11px] text-center text-slate-400 italic">
          Statutory validation completed in compliance with Electoral Act 2022 Section 63
        </p>
      </form>

      {/* Camera Validation Visual Forensic HUD Modal */}
      {showCameraModal && (
        <div className="fixed inset-0 z-50 bg-slate-950/90 backdrop-blur-md flex items-center justify-center p-4">
          <div className="bg-slate-900 border border-emerald-500/40 rounded-2xl w-full max-w-xl shadow-2xl overflow-hidden text-white">
            <div className="bg-emerald-950 border-b border-emerald-500/30 p-4 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Scan className="w-5 h-5 text-emerald-400 animate-pulse" />
                <h3 className="font-extrabold text-sm text-white">
                  INEC Statutory Visual Ballot Scanner
                </h3>
              </div>
              <button
                type="button"
                onClick={() => setShowCameraModal(false)}
                className="p-1 text-slate-400 hover:text-white rounded-lg"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* Photo Area with HUD */}
              <div className="relative rounded-xl overflow-hidden bg-black aspect-video border border-slate-700 flex items-center justify-center">
                {snappedBallotImage ? (
                  <img src={snappedBallotImage} alt="Ballot Paper" className="w-full h-full object-cover" />
                ) : (
                  <div className="text-center p-6 text-slate-500">
                    <Camera className="w-8 h-8 mx-auto mb-2" />
                    <p className="text-xs">No image captured</p>
                  </div>
                )}

                {/* Scanning Animation */}
                {isScanningPhoto && (
                  <div className="absolute inset-0 bg-emerald-950/60 backdrop-blur-xs flex flex-col items-center justify-center">
                    <div className="w-full h-1 bg-emerald-400 shadow-[0_0_15px_#10b981] animate-bounce" />
                    <p className="text-xs font-mono font-bold text-emerald-300 mt-4 animate-pulse">
                      ANALYZING THUMBPRINT &amp; REG 41(2) BORDER CLEARANCE...
                    </p>
                  </div>
                )}

                {/* Bounding Box HUD Overlay */}
                {!isScanningPhoto && scanResult && (
                  <div
                    className="absolute border-2 border-emerald-400 bg-emerald-500/20 rounded-md pointer-events-none flex items-center justify-center"
                    style={{
                      left: `${scanResult.boundingCoordinates.x}%`,
                      top: `${scanResult.boundingCoordinates.y}%`,
                      width: `${scanResult.boundingCoordinates.width}%`,
                      height: `${scanResult.boundingCoordinates.height}%`,
                    }}
                  >
                    <span className="text-[9px] font-mono font-bold text-emerald-300 bg-slate-950/90 px-1 py-0.5 rounded -top-5 absolute">
                      THUMBPRINT CLEARANCE
                    </span>
                  </div>
                )}
              </div>

              {/* Scan Results Card */}
              {!isScanningPhoto && scanResult && (
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-4 space-y-3">
                  <div className="flex items-center justify-between">
                    <span
                      className={`text-xs font-black px-2.5 py-1 rounded-md uppercase tracking-wider ${
                        scanResult.ruling === 'VALID_VOTE'
                          ? 'bg-purple-700 text-white'
                          : 'bg-rose-700 text-white'
                      }`}
                    >
                      {scanResult.ruling === 'VALID_VOTE' ? 'VALID VOTE' : 'REJECTED / INVALID'}
                    </span>
                    <span className="text-xs font-mono font-extrabold text-emerald-400">
                      Match Accuracy: {scanResult.confidence}%
                    </span>
                  </div>

                  {/* Party Scored Display */}
                  <div className="bg-purple-950/60 border border-purple-500/40 p-2.5 rounded-xl">
                    <span className="text-[10px] font-bold text-purple-300 uppercase tracking-wider block">
                      Political Party Scored:
                    </span>
                    <span className="text-sm font-black text-white block mt-0.5">
                      {scanResult.partyScored}
                    </span>
                  </div>

                  <div>
                    <span className="text-[10px] font-bold text-slate-400 block uppercase">Statutory Rule:</span>
                    <span className="text-xs font-bold text-slate-200">{scanResult.scenario.citedRule}</span>
                  </div>

                  <div className="bg-slate-900 p-2.5 rounded-lg border border-slate-800">
                    <span className="text-[10px] font-bold text-amber-300 block uppercase mb-0.5">PO Verbatim Defense Speech:</span>
                    <p className="text-xs font-mono italic text-slate-200 leading-relaxed">
                      {scanResult.scenario.poSpeech}
                    </p>
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between gap-3">
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="px-4 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold rounded-xl flex items-center gap-1.5"
                >
                  <RotateCw className="w-4 h-4 text-slate-400" />
                  <span>Resnap Photo</span>
                </button>

                <button
                  type="button"
                  onClick={() => setShowCameraModal(false)}
                  className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-slate-950 font-black text-xs rounded-xl shadow-lg"
                >
                  Close Validation Window
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Guide Modal */}
      {showGuideModal && (
        <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-lg p-5 text-white max-h-[85vh] overflow-y-auto">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3 mb-4">
              <h3 className="font-extrabold text-sm flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-emerald-400" /> INEC Statutory Ballot Rules Handbook
              </h3>
              <button onClick={() => setShowGuideModal(false)} className="text-slate-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-3 text-xs text-slate-300">
              <p>
                <strong>INEC Regulation 41(2):</strong> Marks touching border lines are valid where voter intent clearly points to a candidate.
              </p>
              <p>
                <strong>INEC Regulation 41(1):</strong> Marks inside emblem or party logo space are valid for that party.
              </p>
              <p>
                <strong>Electoral Act Sec 63(1)(b):</strong> Ambiguous marks straddling two parties equally are rejected.
              </p>
              <p>
                <strong>Electoral Act Sec 62:</strong> Ballot with voter name/signature breaches secrecy and must be rejected.
              </p>
            </div>

            <button
              onClick={() => setShowGuideModal(false)}
              className="mt-5 w-full py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-200 font-bold rounded-xl text-xs"
            >
              Close Handbook
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
