'use client';

import React, { useState } from 'react';
import {
  Radio,
  Send,
  ShieldAlert,
  MessageSquare,
  Users,
  AlertTriangle,
  CheckCircle2,
  Building2,
  Search,
  ChevronRight,
  Wifi,
  Signal,
  Share2,
  Bell,
  Clock,
  Volume2,
  Lock,
  Scale,
  Sparkles,
  MapPin,
  Flame
} from 'lucide-react';
import {
  NIGERIAN_STATES,
  GEOPOLITICAL_ZONES,
  INITIAL_COMMUNICATION_MESSAGES,
  LGAS_BY_STATE,
  WARDS_BY_LGA,
} from '@/lib/electoralData';
import {
  CommunicationMessage,
  DirectiveType,
  UserRole,
  ScopeType,
  StateItem
} from '@/types';

interface NationalCommunicationDeskProps {
  userRole?: UserRole;
  userScopeType?: ScopeType;
  userScopeId?: string;
  userName?: string;
}

export const NationalCommunicationDesk: React.FC<NationalCommunicationDeskProps> = ({
  userRole = 'NATIONAL_COORDINATOR',
  userScopeType = 'NATIONAL',
  userScopeId = 'ALL',
  userName = 'Situation Room Director'
}) => {
  const [messages, setMessages] = useState<CommunicationMessage[]>(INITIAL_COMMUNICATION_MESSAGES);
  const [broadcastText, setBroadcastText] = useState('');
  const [targetAudience, setTargetAudience] = useState('ALL_ASSIGNED');
  const [directiveType, setDirectiveType] = useState<DirectiveType>('SITUATION_ROOM_BROADCAST');
  const [selectedStateDetail, setSelectedStateDetail] = useState<StateItem | null>(null);
  const [isSending, setIsSending] = useState(false);
  const [searchFilter, setSearchFilter] = useState('');

  // Scoped states based on downward-only hierarchy
  let visibleStates = NIGERIAN_STATES;
  if (userScopeType === 'STATE') {
    visibleStates = NIGERIAN_STATES.filter((s) => s.id === userScopeId || s.name.toLowerCase() === userScopeId.toLowerCase());
  } else if (userScopeType === 'REGION') {
    visibleStates = NIGERIAN_STATES.filter((s) => s.geopolitical_zone === userScopeId);
  } else if (userScopeType === 'LGA' || userScopeType === 'WARD') {
    const sId = userScopeId.slice(0, 2);
    visibleStates = NIGERIAN_STATES.filter((s) => s.id === sId);
  }

  // Aggregates for visible scope
  const totalReportedPUs = visibleStates.reduce((acc, s) => acc + (s.pus_reported || 0), 0);
  const totalPUs = visibleStates.reduce((acc, s) => acc + s.total_pus, 0);
  const totalADC = visibleStates.reduce((acc, s) => acc + (s.votes?.ADC || 0), 0);
  const totalAPC = visibleStates.reduce((acc, s) => acc + (s.votes?.APC || 0), 0);
  const totalPDP = visibleStates.reduce((acc, s) => acc + (s.votes?.PDP || 0), 0);
  const totalLP = visibleStates.reduce((acc, s) => acc + (s.votes?.LP || 0), 0);
  const totalNNPP = visibleStates.reduce((acc, s) => acc + (s.votes?.NNPP || 0), 0);
  const totalVoters = visibleStates.reduce((acc, s) => acc + s.registered_voters, 0);

  const filteredStates = visibleStates.filter((st) => {
    if (!searchFilter) return true;
    const q = searchFilter.toLowerCase();
    return st.name.toLowerCase().includes(q) || st.geopolitical_zone.toLowerCase().includes(q);
  });

  const handleSendBroadcast = (e: React.FormEvent) => {
    e.preventDefault();
    if (!broadcastText.trim()) return;

    setIsSending(true);
    setTimeout(() => {
      let targetLabel = 'Nationwide (All 36 States + FCT)';
      if (targetAudience.startsWith('ZONE_')) {
        const zoneName = targetAudience.replace('ZONE_', '').replace(/_/g, ' ');
        targetLabel = `${zoneName} Zone`;
      } else if (targetAudience.startsWith('STATE_')) {
        const st = NIGERIAN_STATES.find((s) => s.id === targetAudience.replace('STATE_', ''));
        targetLabel = st ? `${st.name} State Command` : 'Target State';
      }

      const newMsg: CommunicationMessage = {
        id: 'msg-' + Date.now(),
        sender: `HQ COMMAND (${userName})`,
        role: userRole.replace(/_/g, ' '),
        jurisdiction: targetLabel,
        message: broadcastText,
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        type: directiveType,
        status: 'DELIVERED',
      };

      setMessages([newMsg, ...messages]);
      setBroadcastText('');
      setIsSending(false);
    }, 500);
  };

  return (
    <div className="space-y-6">
      {/* ── TOP BANNER: NATIONAL 2-WAY COMMAND DESK ── */}
      <div className="rounded-3xl border border-purple-500/40 bg-gradient-to-r from-slate-950 via-purple-950/40 to-slate-900 p-6 shadow-2xl relative overflow-hidden">
        <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center space-x-2 mb-2 flex-wrap gap-y-1">
              <span className="rounded-full bg-purple-500/20 px-3 py-1 text-xs font-bold text-purple-300 border border-purple-500/30 flex items-center space-x-1.5">
                <Radio className="h-3.5 w-3.5 animate-pulse text-amber-400" />
                <span>NIGERIA 2027 &bull; 2-WAY PRESIDENTIAL COMMAND &amp; MONITORING DESK</span>
              </span>
              <span className="rounded-full bg-emerald-500/20 px-2.5 py-1 text-xs font-bold text-emerald-400 border border-emerald-500/30">
                ADC Flagbearer Atiku Abubakar 🤝 Live
              </span>
              <span className="rounded-full bg-slate-900 px-2.5 py-1 text-xs font-bold text-amber-300 border border-amber-500/30">
                Powered by GetoCore
              </span>
            </div>
            <h1 className="text-2xl md:text-3xl font-black tracking-tight text-white">
              National Result Collation &amp; Field Dispatch Communication Hub
            </h1>
            <p className="text-xs md:text-sm text-slate-300 mt-1 max-w-3xl leading-relaxed">
              Real-time collation telemetry across 36 States + FCT (176,846 Polling Units) with encrypted two-way digital radio/SMS dispatch to PU agents, ward captains, and state collation directors.
            </p>
          </div>

          <div className="flex items-center space-x-3 bg-slate-900/90 border border-purple-900/60 p-3.5 rounded-2xl shrink-0">
            <div className="text-right">
              <div className="text-[11px] text-slate-400 font-medium">Communication Channel</div>
              <div className="text-sm font-black text-emerald-400 flex items-center justify-end space-x-1.5">
                <span className="h-2 w-2 rounded-full bg-emerald-400 animate-ping"></span>
                <span>GetoCore Mesh Radio Active</span>
              </div>
              <div className="text-[10px] text-purple-300 font-mono mt-0.5">
                176,846 PUs Network Connected
              </div>
            </div>
          </div>
        </div>

        {/* High Level Collation Summary Bar */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5 mt-6 pt-5 border-t border-purple-900/40">
          <div className="bg-slate-900/80 rounded-2xl p-4 border border-purple-900/40">
            <div className="text-slate-400 text-xs">PUs Reported (Nationwide)</div>
            <div className="text-2xl font-black text-cyan-400 mt-1">
              {totalReportedPUs.toLocaleString()}{' '}
              <span className="text-xs text-slate-500 font-normal">/ {totalPUs.toLocaleString()}</span>
            </div>
            <div className="text-[10px] text-cyan-400 mt-0.5 font-mono">
              {((totalReportedPUs / totalPUs) * 100).toFixed(1)}% Coverage Reached
            </div>
          </div>

          <div className="bg-slate-900/90 rounded-2xl p-4 border border-purple-500/60 ring-1 ring-purple-500/40 shadow-lg">
            <div className="text-purple-300 text-xs font-bold flex items-center justify-between">
              <span>ADC Presidential Votes 🤝</span>
              <span className="text-[10px] bg-purple-500/20 px-1.5 py-0.5 rounded text-amber-300 font-black">
                LEADING
              </span>
            </div>
            <div className="text-2xl font-black text-amber-300 mt-1">
              {totalADC.toLocaleString()}
            </div>
            <div className="text-[10px] text-slate-300 mt-0.5">
              H.E. Atiku Abubakar (Presidential Candidate)
            </div>
          </div>

          <div className="bg-slate-900/80 rounded-2xl p-4 border border-purple-900/40">
            <div className="text-slate-400 text-xs">Trailing Opponents</div>
            <div className="text-xs font-bold text-slate-200 mt-1.5 flex items-center justify-between">
              <span>APC: {totalAPC.toLocaleString()}</span>
              <span>PDP: {totalPDP.toLocaleString()}</span>
            </div>
            <div className="text-[10px] text-emerald-400 mt-1 font-bold">
              Lead Margin: +{(totalADC - Math.max(totalAPC, totalPDP)).toLocaleString()} votes
            </div>
          </div>

          <div className="bg-slate-900/80 rounded-2xl p-4 border border-purple-900/40">
            <div className="text-slate-400 text-xs">BVAS Accreditation Tally</div>
            <div className="text-2xl font-black text-white mt-1">
              {Math.round(totalReportedPUs * 385).toLocaleString()}
            </div>
            <div className="text-[10px] text-purple-300 mt-0.5 font-mono">
              Anti-Over-Voting Audit Passed (Sec 51)
            </div>
          </div>
        </div>
      </div>

      {/* ── MAIN WORKSPACE: STATE REPORTING GRID (LEFT) + 2-WAY DISPATCH & STREAM (RIGHT) ── */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        
        {/* LEFT COLUMN: State Collation Telemetry (7 Cols) */}
        <div className="lg:col-span-7 space-y-4">
          <div className="bg-slate-900/90 rounded-2xl p-4 border border-slate-800 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center space-x-2.5">
              <Building2 className="h-5 w-5 text-purple-400" />
              <div>
                <h3 className="text-sm font-black text-white">
                  {userScopeType === 'NATIONAL'
                    ? '36 States + FCT Collation Telemetry'
                    : `${userScopeId} Collation Coverage`}
                </h3>
                <p className="text-[11px] text-slate-400">
                  Click any state card (e.g., Kebbi, Lagos, Kano, Adamawa) to inspect PU details and Form EC8A telemetry
                </p>
              </div>
            </div>

            <div className="flex items-center space-x-2">
              <div className="relative">
                <Search className="w-3.5 h-3.5 absolute left-2.5 top-2.5 text-slate-400" />
                <input
                  type="text"
                  placeholder="Filter state or zone..."
                  value={searchFilter}
                  onChange={(e) => setSearchFilter(e.target.value)}
                  className="bg-slate-950 border border-slate-700 rounded-xl pl-8 pr-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-purple-500"
                />
              </div>
              <span className="rounded-xl bg-purple-500/20 px-2.5 py-1 text-xs font-bold text-purple-300 border border-purple-500/30 whitespace-nowrap">
                {filteredStates.length} States Live
              </span>
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-[720px] overflow-y-auto pr-1">
            {filteredStates.map((st) => {
              const repCount = st.pus_reported || 0;
              const progressPct = Math.round((repCount / Math.max(1, st.total_pus)) * 100);
              const adcVotes = st.votes?.ADC || 0;
              const totalTopVotes = Math.max(1, (st.votes?.ADC || 0) + (st.votes?.APC || 0) + (st.votes?.PDP || 0));
              const adcShare = Math.round((adcVotes / totalTopVotes) * 100);
              const isKebbi = st.name.toLowerCase() === 'kebbi';

              return (
                <div
                  key={st.id}
                  onClick={() => setSelectedStateDetail(st)}
                  className={`p-4 rounded-2xl border transition cursor-pointer space-y-3 relative ${
                    isKebbi
                      ? 'bg-purple-950/30 border-purple-500/70 hover:border-amber-400 ring-1 ring-purple-500/40'
                      : 'bg-slate-900/80 border-slate-800 hover:border-purple-500/50 hover:bg-slate-800/60'
                  }`}
                >
                  <div className="flex items-start justify-between">
                    <div>
                      <div className="flex items-center space-x-1.5">
                        <span className="text-xs font-bold text-purple-400">State {st.id}</span>
                        <span className="text-[10px] text-slate-400 font-mono">({st.geopolitical_zone.replace(/_/g, ' ')})</span>
                        {isKebbi && (
                          <span className="bg-amber-400 text-slate-950 font-black text-[9px] px-1.5 py-0.2 rounded">
                            FEATURED
                          </span>
                        )}
                      </div>
                      <div className="text-sm font-black text-white">{st.name} State</div>
                    </div>
                    <span className="px-2 py-0.5 rounded text-[10px] font-black bg-purple-500/20 text-amber-300 border border-purple-500/40">
                      ADC {adcShare}%
                    </span>
                  </div>

                  {/* Progress Bar */}
                  <div className="space-y-1">
                    <div className="flex justify-between text-[10px] text-slate-400">
                      <span>PUs Reported</span>
                      <span className="font-bold text-white font-mono">
                        {repCount.toLocaleString()} / {st.total_pus.toLocaleString()}
                      </span>
                    </div>
                    <div className="h-2 w-full bg-slate-950 rounded-full overflow-hidden">
                      <div
                        className="h-full bg-gradient-to-r from-purple-600 via-purple-500 to-amber-400 rounded-full transition-all duration-500"
                        style={{ width: `${progressPct}%` }}
                      ></div>
                    </div>
                  </div>

                  {/* Results preview */}
                  <div className="grid grid-cols-4 gap-1 pt-2 border-t border-slate-800/80 text-center">
                    <div className="bg-slate-950/70 p-1.5 rounded-lg">
                      <div className="text-[9px] text-amber-400 font-bold">ADC 🤝</div>
                      <div className="text-xs font-black text-white font-mono">
                        {st.votes?.ADC ? (st.votes.ADC > 1000 ? `${(st.votes.ADC / 1000).toFixed(0)}k` : st.votes.ADC) : '0'}
                      </div>
                    </div>
                    <div className="bg-slate-950/70 p-1.5 rounded-lg">
                      <div className="text-[9px] text-emerald-400 font-bold">APC</div>
                      <div className="text-xs font-bold text-slate-300 font-mono">
                        {st.votes?.APC ? (st.votes.APC > 1000 ? `${(st.votes.APC / 1000).toFixed(0)}k` : st.votes.APC) : '0'}
                      </div>
                    </div>
                    <div className="bg-slate-950/70 p-1.5 rounded-lg">
                      <div className="text-[9px] text-rose-400 font-bold">PDP</div>
                      <div className="text-xs font-bold text-slate-300 font-mono">
                        {st.votes?.PDP ? (st.votes.PDP > 1000 ? `${(st.votes.PDP / 1000).toFixed(0)}k` : st.votes.PDP) : '0'}
                      </div>
                    </div>
                    <div className="bg-slate-950/70 p-1.5 rounded-lg">
                      <div className="text-[9px] text-orange-400 font-bold">LP</div>
                      <div className="text-xs font-bold text-slate-300 font-mono">
                        {st.votes?.LP ? (st.votes.LP > 1000 ? `${(st.votes.LP / 1000).toFixed(0)}k` : st.votes.LP) : '0'}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* RIGHT COLUMN: 2-Way Command Dispatcher & Live Field Telemetry (5 Cols) */}
        <div className="lg:col-span-5 space-y-4">
          
          {/* Situation Room Broadcast Dispatcher */}
          <div className="bg-slate-900/95 rounded-3xl p-5 border border-purple-500/40 shadow-xl space-y-4">
            <div className="flex items-center justify-between pb-3 border-b border-slate-800">
              <div className="flex items-center space-x-2.5">
                <div className="h-8 w-8 rounded-xl bg-purple-600 flex items-center justify-center text-white font-bold shadow-md shadow-purple-600/30">
                  <Radio className="h-4 w-4" />
                </div>
                <div>
                  <h3 className="text-xs font-black text-white uppercase tracking-wider">
                    Situation Room Dispatcher Desk
                  </h3>
                  <p className="text-[10px] text-purple-300">Broadcast Encrypted SMS &amp; Radio Directives</p>
                </div>
              </div>
              <span className="text-[10px] font-mono text-emerald-400 font-bold bg-emerald-950/60 px-2 py-0.5 rounded border border-emerald-500/30">
                176,846 Agents
              </span>
            </div>

            <form onSubmit={handleSendBroadcast} className="space-y-3">
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <label className="block text-[10px] font-bold text-slate-400 mb-1">Target Audience (Downward Only)</label>
                  <select
                    value={targetAudience}
                    onChange={(e) => setTargetAudience(e.target.value)}
                    className="w-full rounded-xl bg-slate-950 border border-slate-700 px-2.5 py-1.5 text-xs text-white focus:outline-none focus:ring-1 focus:ring-purple-500"
                  >
                    {userScopeType === 'NATIONAL' && (
                      <>
                        <option value="ALL_NIGERIA">📢 All 36 States + FCT (176,846 PUs)</option>
                        <optgroup label="Geopolitical Zones">
                          {GEOPOLITICAL_ZONES.map((z) => (
                            <option key={z.code} value={`ZONE_${z.code}`}>{z.name}</option>
                          ))}
                        </optgroup>
                        <optgroup label="All 36 States + FCT">
                          {NIGERIAN_STATES.map((s) => (
                            <option key={s.id} value={`STATE_${s.id}`}>{s.name} State Command ({s.total_pus.toLocaleString()} PUs)</option>
                          ))}
                        </optgroup>
                      </>
                    )}

                    {userScopeType === 'REGION' && (
                      <>
                        <option value={`ZONE_${userScopeId}`}>📢 All States in {userScopeId.replace(/_/g, ' ')}</option>
                        {visibleStates.map((s) => (
                          <option key={s.id} value={`STATE_${s.id}`}>{s.name} State Command</option>
                        ))}
                      </>
                    )}

                    {userScopeType === 'STATE' && (
                      <>
                        <option value={`STATE_${userScopeId}`}>📢 All LGAs in this State ({visibleStates[0]?.name || 'State'})</option>
                        {(LGAS_BY_STATE[userScopeId] || []).map((l) => (
                          <option key={l.id} value={`LGA_${l.id}`}>{l.name} LGA ({l.code})</option>
                        ))}
                      </>
                    )}

                    {userScopeType === 'LGA' && (
                      <>
                        <option value={`LGA_${userScopeId}`}>📢 All Wards in this LGA</option>
                        {(WARDS_BY_LGA[userScopeId] || []).map((w) => (
                          <option key={w.id} value={`WARD_${w.id}`}>{w.name} Ward</option>
                        ))}
                      </>
                    )}

                    {userScopeType === 'WARD' && (
                      <option value={`WARD_${userScopeId}`}>📢 All Polling Unit Agents in this Ward</option>
                    )}
                  </select>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-slate-400 mb-1">Directive Priority</label>
                  <select
                    value={directiveType}
                    onChange={(e: any) => setDirectiveType(e.target.value)}
                    className="w-full rounded-xl bg-slate-950 border border-slate-700 px-2.5 py-1.5 text-xs text-white focus:outline-none focus:ring-1 focus:ring-purple-500"
                  >
                    <option value="SITUATION_ROOM_BROADCAST">🚨 High Priority Broadcast</option>
                    <option value="LEGAL_DIRECTIVE">⚖️ Legal &amp; Section 51 EC8A Audit</option>
                    <option value="SOS_ALERT">⚠️ Emergency / Incident Alert</option>
                    <option value="LOGISTICS_UPDATE">📦 Logistics &amp; Field Welfare</option>
                  </select>
                </div>
              </div>

              <div>
                <textarea
                  rows={3}
                  required
                  placeholder="Type official presidential situation room directive to transmit immediately to field agents' devices..."
                  value={broadcastText}
                  onChange={(e) => setBroadcastText(e.target.value)}
                  className="w-full rounded-xl bg-slate-950 border border-slate-700 p-3 text-xs text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-purple-500"
                ></textarea>
              </div>

              <button
                type="submit"
                disabled={isSending}
                className="w-full py-2.5 rounded-xl bg-gradient-to-r from-purple-600 via-purple-700 to-amber-500 hover:from-purple-500 hover:to-amber-400 text-white font-black text-xs transition shadow-lg shadow-purple-900/40 flex items-center justify-center space-x-2"
              >
                {isSending ? (
                  <span>Transmitting Encrypted National Directive...</span>
                ) : (
                  <>
                    <Send className="h-3.5 w-3.5" />
                    <span>Transmit Encrypted Directive to Field Network</span>
                  </>
                )}
              </button>
            </form>
          </div>

          {/* Live 2-Way Message Stream */}
          <div className="bg-slate-900/90 rounded-3xl p-5 border border-slate-800 space-y-3">
            <div className="flex items-center justify-between pb-2 border-b border-slate-800">
              <div className="flex items-center space-x-2">
                <MessageSquare className="h-4 w-4 text-purple-400" />
                <h4 className="text-xs font-black text-white uppercase tracking-wider">
                  Live Field Telemetry Feed
                </h4>
              </div>
              <span className="text-[10px] text-slate-400 flex items-center gap-1 font-mono">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-ping"></span>
                Auto-refreshing &bull; {messages.length} Directives &amp; Reports
              </span>
            </div>

            <div className="space-y-2.5 max-h-[420px] overflow-y-auto pr-1">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`p-3 rounded-2xl border text-xs space-y-1.5 transition ${
                    msg.type === 'SOS_ALERT'
                      ? 'bg-rose-950/30 border-rose-500/40 text-rose-200'
                      : msg.type === 'LEGAL_DIRECTIVE'
                      ? 'bg-amber-950/30 border-amber-500/40 text-amber-200'
                      : msg.type === 'SITUATION_ROOM_BROADCAST'
                      ? 'bg-purple-950/40 border-purple-500/40 text-purple-200'
                      : 'bg-slate-950/80 border-slate-800 text-slate-300'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-1.5">
                      <span className="font-bold text-white text-[11px]">{msg.sender}</span>
                      <span className="text-[10px] text-slate-400">({msg.jurisdiction})</span>
                    </div>
                    <span className="text-[10px] font-mono text-slate-500">{msg.timestamp}</span>
                  </div>

                  <p className="text-[11px] leading-relaxed text-slate-200">{msg.message}</p>

                  <div className="flex items-center justify-between text-[10px] text-slate-400 pt-1 border-t border-slate-800/40">
                    <span className="font-mono text-purple-300 font-bold">{msg.role}</span>
                    <span className="flex items-center space-x-1 text-emerald-400 font-mono">
                      <CheckCircle2 className="h-3 w-3" />
                      <span>{msg.status}</span>
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

        </div>

      </div>

      {/* State Detail Inspection Modal */}
      {selectedStateDetail && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm">
          <div className="w-full max-w-xl rounded-3xl bg-slate-900 border border-purple-500/40 p-6 space-y-4 shadow-2xl">
            <div className="flex items-start justify-between border-b border-slate-800 pb-4">
              <div>
                <span className="text-xs font-bold text-purple-400">
                  {selectedStateDetail.geopolitical_zone.replace(/_/g, ' ')} &bull; State Code {selectedStateDetail.id}
                </span>
                <h3 className="text-xl font-black text-white">{selectedStateDetail.name} State Command</h3>
                <p className="text-xs text-slate-400">
                  {selectedStateDetail.total_lgas} LGAs &bull; {selectedStateDetail.total_wards} Wards &bull; {selectedStateDetail.total_pus.toLocaleString()} Polling Units
                </p>
              </div>
              <button
                onClick={() => setSelectedStateDetail(null)}
                className="text-slate-400 hover:text-white px-2.5 py-1 rounded-xl bg-slate-800 text-xs font-bold"
              >
                ✕ Close
              </button>
            </div>

            <div className="grid grid-cols-3 gap-3 text-center">
              <div className="bg-slate-950 p-3 rounded-xl border border-slate-800">
                <div className="text-[10px] text-slate-400">Registered Voters</div>
                <div className="text-base font-black text-white font-mono">
                  {selectedStateDetail.registered_voters.toLocaleString()}
                </div>
              </div>
              <div className="bg-slate-950 p-3 rounded-xl border border-slate-800">
                <div className="text-[10px] text-slate-400">PUs Reported</div>
                <div className="text-base font-black text-cyan-400 font-mono">
                  {(selectedStateDetail.pus_reported || 0).toLocaleString()}
                </div>
              </div>
              <div className="bg-slate-950 p-3 rounded-xl border border-slate-800">
                <div className="text-[10px] text-slate-400">IReV Uploads Synced</div>
                <div className="text-base font-black text-emerald-400 font-mono">
                  {(selectedStateDetail.irev_uploaded_count || 0).toLocaleString()}
                </div>
              </div>
            </div>

            <div className="space-y-2 bg-slate-950 p-4 rounded-2xl border border-slate-800">
              <div className="text-xs font-bold text-white mb-2">Vote Breakdown in {selectedStateDetail.name}:</div>
              
              <div className="flex items-center justify-between text-xs py-1 border-b border-slate-800/60">
                <span className="font-bold text-amber-300">ADC (H.E. Atiku Abubakar 🤝):</span>
                <span className="font-black text-white font-mono">
                  {(selectedStateDetail.votes?.ADC || 0).toLocaleString()} votes
                </span>
              </div>
              <div className="flex items-center justify-between text-xs py-1 border-b border-slate-800/60">
                <span className="font-bold text-emerald-400">APC:</span>
                <span className="font-mono text-slate-300">
                  {(selectedStateDetail.votes?.APC || 0).toLocaleString()} votes
                </span>
              </div>
              <div className="flex items-center justify-between text-xs py-1 border-b border-slate-800/60">
                <span className="font-bold text-rose-400">PDP:</span>
                <span className="font-mono text-slate-300">
                  {(selectedStateDetail.votes?.PDP || 0).toLocaleString()} votes
                </span>
              </div>
              <div className="flex items-center justify-between text-xs py-1">
                <span className="font-bold text-orange-400">LP:</span>
                <span className="font-mono text-slate-300">
                  {(selectedStateDetail.votes?.LP || 0).toLocaleString()} votes
                </span>
              </div>
            </div>

            <div className="flex items-center justify-between pt-2">
              <span className="text-[11px] text-purple-300">
                Official Tribunal Hash: #ADC-2027-{selectedStateDetail.id}-PVT
              </span>
              <button
                onClick={() => {
                  setTargetAudience(`STATE_${selectedStateDetail.id}`);
                  setSelectedStateDetail(null);
                }}
                className="px-3 py-1.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs flex items-center gap-1"
              >
                <Radio className="w-3.5 h-3.5" />
                <span>Target in Dispatcher</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
