'use client';

import React, { useState, useEffect, useMemo } from 'react';
import {
  X,
  QrCode,
  Smartphone,
  Copy,
  ExternalLink,
  Code2,
  Terminal,
  Zap,
  CheckCircle2,
  Share2,
  Globe,
  Key,
  Layers,
  ArrowRight,
  Send,
  AlertTriangle,
  Play,
} from 'lucide-react';
import { generateQrSvg } from '@/lib/qrCode';

interface Props {
  isOpen: boolean;
  onClose: () => void;
  defaultTab?: 'LINK_APP' | 'API_DOCS' | 'CODE_SNIPPETS' | 'TEST_API';
}

export const MobileAppCenterModal: React.FC<Props> = ({
  isOpen,
  onClose,
  defaultTab = 'LINK_APP',
}) => {
  const [activeTab, setActiveTab] = useState<'LINK_APP' | 'API_DOCS' | 'CODE_SNIPPETS' | 'TEST_API'>(defaultTab);
  const [copiedKey, setCopiedKey] = useState<string | null>(null);
  const [appUrl, setAppUrl] = useState('https://atiku2027-situation-room.vercel.app/agent');
  const [baseUrl, setBaseUrl] = useState('https://atiku2027-situation-room.vercel.app/api/v1');
  const [selectedSnippet, setSelectedSnippet] = useState<'FLUTTER' | 'REACT_NATIVE' | 'CURL' | 'KOTLIN'>('FLUTTER');

  // Test Console State
  const [testPuCode, setTestPuCode] = useState('19-01-01-001');
  const [testAgentName, setTestAgentName] = useState('Bello Haruna (Kano Field Agent)');
  const [testAdcVotes, setTestAdcVotes] = useState(380);
  const [testApcVotes, setTestApcVotes] = useState(95);
  const [testPdpVotes, setTestPdpVotes] = useState(35);
  const [testRunning, setTestRunning] = useState(false);
  const [testResponse, setTestResponse] = useState<any>(null);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const origin = window.location.origin;
      setBaseUrl(`${origin}/api/v1`);
      // Default external app link to the dedicated agent URL on this domain or custom
      if (!appUrl || appUrl.includes('localhost')) {
        setAppUrl(`${origin}/agent`);
      }
    }
  }, [isOpen]);

  const qrSvgMarkup = useMemo(() => {
    return generateQrSvg(appUrl, 210, '#020617');
  }, [appUrl]);

  if (!isOpen) return null;

  const handleCopy = (text: string, keyName: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(keyName);
    setTimeout(() => setCopiedKey(null), 3000);
  };

  const runLiveApiTest = async () => {
    setTestRunning(true);
    setTestResponse(null);
    try {
      const payload = {
        pu_code: testPuCode,
        party_votes: {
          ADC: Number(testAdcVotes),
          APC: Number(testApcVotes),
          PDP: Number(testPdpVotes),
          LP: 12,
          NNPP: 8,
        },
        accredited_voters: Number(testAdcVotes) + Number(testApcVotes) + Number(testPdpVotes) + 20,
        rejected_ballots: 0,
        agent_name: testAgentName,
        agent_phone: '08031234567',
        form_ec8a_url: '/sample_ec8a_snap.jpg',
        bvas_zero_accredited_verified: true,
        agent_signature_confirmed: true,
      };

      const res = await fetch(`${baseUrl}/results`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': 'ATIKU2027_LIVE_PU_AGENT_KEY',
        },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      setTestResponse({ status: res.status, ok: res.ok, data });
    } catch (err: any) {
      setTestResponse({ status: 500, ok: false, data: { error: err.message } });
    } finally {
      setTestRunning(false);
    }
  };

  const curlExample = `curl -X POST "${baseUrl}/results" \\
  -H "Content-Type: application/json" \\
  -H "X-API-Key: ATIKU2027_LIVE_PU_AGENT_KEY" \\
  -d '{
    "pu_code": "19-01-01-001",
    "party_votes": { "ADC": 340, "APC": 110, "PDP": 45, "LP": 10, "NNPP": 5 },
    "accredited_voters": 510,
    "rejected_ballots": 0,
    "form_ec8a_url": "https://storage.atiku2027.org/ec8a/19-01-01-001.jpg",
    "agent_name": "Malam Haruna",
    "agent_phone": "08031234567"
  }'`;

  const flutterExample = `// Flutter / Dart (http package)
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<bool> transmitPuResult({
  required String puCode,
  required Map<String, int> partyVotes,
  required int accreditedVoters,
  required String agentName,
  required String agentPhone,
  String? ec8aPhotoUrl,
}) async {
  final url = Uri.parse('${baseUrl}/results');
  final response = await http.post(
    url,
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'ATIKU2027_LIVE_PU_AGENT_KEY',
    },
    body: jsonEncode({
      'pu_code': puCode,
      'party_votes': partyVotes,
      'accredited_voters': accreditedVoters,
      'rejected_ballots': 0,
      'form_ec8a_url': ec8aPhotoUrl ?? '/sample_ec8a_snap.jpg',
      'agent_name': agentName,
      'agent_phone': agentPhone,
    }),
  );

  return response.statusCode == 201 || response.statusCode == 200;
}`;

  const reactNativeExample = `// React Native / TypeScript (fetch)
export async function submitPuResults(payload: {
  puCode: string;
  votes: Record<string, number>;
  accreditedVoters: number;
  agentName: string;
  photoUrl?: string;
}) {
  const response = await fetch('${baseUrl}/results', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'ATIKU2027_LIVE_PU_AGENT_KEY',
    },
    body: JSON.stringify({
      pu_code: payload.puCode,
      party_votes: payload.votes,
      accredited_voters: payload.accreditedVoters,
      form_ec8a_url: payload.photoUrl || '/sample_ec8a_snap.jpg',
      agent_name: payload.agentName,
    }),
  });

  return await response.json();
}`;

  const kotlinExample = `// Kotlin / Android (OkHttp / Retrofit)
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody = JSONObject().apply {
    put("pu_code", "19-01-01-001")
    put("party_votes", JSONObject(mapOf("ADC" to 340, "APC" to 110, "PDP" to 45)))
    put("accredited_voters", 495)
    put("agent_name", "Field Agent")
}.toString()

val request = Request.Builder()
    .url("${baseUrl}/results")
    .addHeader("X-API-Key", "ATIKU2027_LIVE_PU_AGENT_KEY")
    .post(jsonBody.toRequestBody(jsonMediaType))
    .build()`;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-black/85 backdrop-blur-md animate-in fade-in overflow-y-auto">
      <div className="w-full max-w-3xl bg-slate-900 border border-purple-900/60 rounded-3xl shadow-2xl overflow-hidden flex flex-col my-auto max-h-[92vh]">
        {/* Header */}
        <div className="p-4 sm:p-5 bg-gradient-to-r from-purple-950 via-slate-900 to-amber-950/60 border-b border-purple-900/40 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 rounded-2xl overflow-hidden border border-amber-400/50 shadow-md bg-purple-950 flex items-center justify-center shrink-0 text-amber-400">
              <Code2 className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2 flex-wrap">
                <h3 className="text-base sm:text-lg font-black text-white tracking-wide">
                  External PU Agent App &amp; API Gateway
                </h3>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold">
                  Live API v1.0
                </span>
              </div>
              <p className="text-xs text-slate-300 mt-0.5">
                Link external field agent mobile apps &amp; transmit Form EC8A returns directly into Situation Room
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-slate-800 transition"
            title="Close"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tab Navigation */}
        <div className="flex border-b border-slate-800 bg-slate-950/60 px-3 pt-2 gap-1 overflow-x-auto">
          <button
            onClick={() => setActiveTab('LINK_APP')}
            className={`px-3.5 py-2.5 rounded-t-xl text-xs font-black transition flex items-center gap-1.5 whitespace-nowrap ${
              activeTab === 'LINK_APP'
                ? 'bg-slate-900 text-amber-400 border-t-2 border-amber-400 shadow'
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <Smartphone className="w-3.5 h-3.5" />
            <span>1. Link External Agent App</span>
          </button>

          <button
            onClick={() => setActiveTab('API_DOCS')}
            className={`px-3.5 py-2.5 rounded-t-xl text-xs font-black transition flex items-center gap-1.5 whitespace-nowrap ${
              activeTab === 'API_DOCS'
                ? 'bg-slate-900 text-emerald-400 border-t-2 border-emerald-400 shadow'
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <Layers className="w-3.5 h-3.5" />
            <span>2. REST API Endpoints</span>
          </button>

          <button
            onClick={() => setActiveTab('CODE_SNIPPETS')}
            className={`px-3.5 py-2.5 rounded-t-xl text-xs font-black transition flex items-center gap-1.5 whitespace-nowrap ${
              activeTab === 'CODE_SNIPPETS'
                ? 'bg-slate-900 text-purple-400 border-t-2 border-purple-400 shadow'
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <Terminal className="w-3.5 h-3.5" />
            <span>3. Mobile Code Snippets</span>
          </button>

          <button
            onClick={() => setActiveTab('TEST_API')}
            className={`px-3.5 py-2.5 rounded-t-xl text-xs font-black transition flex items-center gap-1.5 whitespace-nowrap ${
              activeTab === 'TEST_API'
                ? 'bg-slate-900 text-sky-400 border-t-2 border-sky-400 shadow'
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <Zap className="w-3.5 h-3.5" />
            <span>4. Test Connection Live</span>
          </button>
        </div>

        {/* Tab Content Body */}
        <div className="p-4 sm:p-6 overflow-y-auto space-y-5 text-slate-200">
          {/* TAB 1: LINK EXTERNAL APP */}
          {activeTab === 'LINK_APP' && (
            <div className="space-y-5">
              <div className="bg-gradient-to-br from-purple-950/40 via-slate-900 to-slate-900 border border-purple-800/40 rounded-2xl p-4 sm:p-5">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                  <div>
                    <h4 className="text-sm font-black text-white flex items-center gap-2">
                      <Globe className="w-4 h-4 text-amber-400" /> Set External PU Agent Application Link
                    </h4>
                    <p className="text-xs text-slate-400 mt-1">
                      Enter the download link or web portal address for your external PU Agent mobile app. Supervisors can share this link or QR code with field agents nationwide.
                    </p>
                  </div>
                  <span className="text-[10px] bg-amber-500/10 text-amber-300 border border-amber-500/30 px-2.5 py-1 rounded-full font-mono font-bold shrink-0">
                    Live Sync Ready
                  </span>
                </div>

                <div className="mt-4 flex flex-col sm:flex-row gap-2">
                  <input
                    type="text"
                    value={appUrl}
                    onChange={(e) => setAppUrl(e.target.value)}
                    placeholder="https://your-custom-app-domain.org/agent"
                    className="flex-1 px-3.5 py-2.5 bg-slate-950 border border-slate-700 rounded-xl text-xs font-mono text-amber-300 focus:outline-none focus:ring-2 focus:ring-amber-500"
                  />
                  <button
                    onClick={() => handleCopy(appUrl, 'appUrl')}
                    className="px-4 py-2.5 bg-amber-500 hover:bg-amber-400 text-slate-950 font-black text-xs rounded-xl flex items-center justify-center gap-1.5 shrink-0 shadow transition active:scale-95"
                  >
                    {copiedKey === 'appUrl' ? <CheckCircle2 className="w-3.5 h-3.5 text-slate-950" /> : <Copy className="w-3.5 h-3.5" />}
                    <span>{copiedKey === 'appUrl' ? 'Copied Link!' : 'Copy Link'}</span>
                  </button>
                  <a
                    href={appUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="px-3.5 py-2.5 bg-slate-800 hover:bg-slate-700 text-white font-bold text-xs rounded-xl flex items-center justify-center gap-1.5 shrink-0 transition"
                  >
                    <ExternalLink className="w-3.5 h-3.5" />
                    <span>Open</span>
                  </a>
                </div>
              </div>

              {/* QR Code & Share Instructions */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 items-center">
                <div className="bg-slate-950 border border-slate-800 rounded-2xl p-4 flex flex-col items-center text-center">
                  <div
                    className="p-3 bg-white rounded-2xl shadow-xl flex items-center justify-center"
                    dangerouslySetInnerHTML={{ __html: qrSvgMarkup }}
                  />
                  <span className="text-[11px] font-bold text-slate-300 mt-3 flex items-center gap-1">
                    <QrCode className="w-3.5 h-3.5 text-amber-400" /> Scan with Mobile Phone Camera
                  </span>
                  <span className="text-[10px] text-slate-500 mt-0.5">
                    Opens external PU agent portal directly on Android or iPhone
                  </span>
                </div>

                <div className="space-y-3">
                  <div className="bg-slate-950/80 border border-slate-800/80 rounded-xl p-3.5 space-y-1.5">
                    <span className="text-xs font-extrabold text-white block">
                      📲 Instant Agent Onboarding via WhatsApp / SMS
                    </span>
                    <p className="text-[11px] text-slate-400 leading-relaxed">
                      Copy the pre-formatted invite message to broadcast to your State, LGA, and Ward agent coordinators.
                    </p>
                    <button
                      onClick={() => {
                        const msg = `🗳️ OFFICIAL ATIKU 2027 ELECTION SITUATION ROOM\nAccredited Polling Unit Agent Portal Link:\n${appUrl}\n\nPlease tap the link on your mobile phone to login and submit Form EC8A returns on Election Day.`;
                        handleCopy(msg, 'whatsappMsg');
                      }}
                      className="mt-2 w-full py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-black rounded-lg flex items-center justify-center gap-1.5 shadow"
                    >
                      {copiedKey === 'whatsappMsg' ? <CheckCircle2 className="w-3.5 h-3.5" /> : <Share2 className="w-3.5 h-3.5" />}
                      <span>{copiedKey === 'whatsappMsg' ? 'Copied WhatsApp Message!' : 'Copy WhatsApp / SMS Broadcast Text'}</span>
                    </button>
                  </div>

                  <div className="bg-slate-950/80 border border-slate-800/80 rounded-xl p-3 text-[11px] text-slate-400 space-y-1">
                    <span className="text-xs font-bold text-amber-300 block">⚡ Direct Serverless Integration</span>
                    <p>
                      Any third-party app that posts JSON to the Situation Room API will automatically display live returns on the desktop command wall without delays.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: REST API ENDPOINTS */}
          {activeTab === 'API_DOCS' && (
            <div className="space-y-4">
              {/* Base URL and Key Box */}
              <div className="bg-slate-950 border border-slate-800 rounded-2xl p-4 space-y-3">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 border-b border-slate-800/80 pb-3">
                  <div>
                    <span className="text-[10px] text-slate-500 uppercase font-mono font-bold tracking-wider">
                      REST API Gateway Base URL
                    </span>
                    <div className="text-xs font-mono font-black text-emerald-400 mt-0.5">{baseUrl}</div>
                  </div>
                  <button
                    onClick={() => handleCopy(baseUrl, 'baseUrl')}
                    className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-xs font-bold rounded-lg text-slate-200 flex items-center gap-1"
                  >
                    {copiedKey === 'baseUrl' ? <CheckCircle2 className="w-3 h-3 text-emerald-400" /> : <Copy className="w-3 h-3" />}
                    <span>{copiedKey === 'baseUrl' ? 'Copied!' : 'Copy Base URL'}</span>
                  </button>
                </div>

                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
                  <div>
                    <span className="text-[10px] text-slate-500 uppercase font-mono font-bold tracking-wider flex items-center gap-1">
                      <Key className="w-3 h-3 text-amber-400" /> Production API Key Header
                    </span>
                    <div className="text-xs font-mono font-bold text-amber-300 mt-0.5">
                      X-API-Key: ATIKU2027_LIVE_PU_AGENT_KEY
                    </div>
                  </div>
                  <button
                    onClick={() => handleCopy('ATIKU2027_LIVE_PU_AGENT_KEY', 'apiKey')}
                    className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-xs font-bold rounded-lg text-slate-200 flex items-center gap-1"
                  >
                    {copiedKey === 'apiKey' ? <CheckCircle2 className="w-3 h-3 text-amber-400" /> : <Copy className="w-3 h-3" />}
                    <span>{copiedKey === 'apiKey' ? 'Copied Key!' : 'Copy Key'}</span>
                  </button>
                </div>
              </div>

              {/* Endpoints List */}
              <div className="space-y-3">
                {/* Endpoint 1 */}
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-3.5 space-y-2">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-mono text-[10px] font-black">
                        POST
                      </span>
                      <span className="text-xs font-mono font-bold text-white">/results</span>
                    </div>
                    <span className="text-[10px] text-slate-400 font-bold">Transmit Form EC8A Result</span>
                  </div>
                  <p className="text-[11px] text-slate-400 leading-relaxed">
                    Transmits ballot returns for all 18 parties, accredited voters, and EC8A photo. Validates mathematical balance and triggers real-time chime on the national dashboard.
                  </p>
                  <div className="bg-slate-900 p-2.5 rounded-lg border border-slate-800 text-[11px] font-mono text-slate-300 overflow-x-auto">
                    {`POST ${baseUrl}/results\nPayload: { "pu_code": "19-01-01-001", "party_votes": { "ADC": 340, "APC": 110, "PDP": 45 }, "accredited_voters": 495, "form_ec8a_url": "..." }`}
                  </div>
                </div>

                {/* Endpoint 2 */}
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-3.5 space-y-2">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="px-2 py-0.5 rounded bg-sky-500/20 text-sky-300 border border-sky-500/30 font-mono text-[10px] font-black">
                        GET
                      </span>
                      <span className="text-xs font-mono font-bold text-white">/pu/lookup?pu_code=...</span>
                    </div>
                    <span className="text-[10px] text-slate-400 font-bold">Query Statutory PU Baseline</span>
                  </div>
                  <p className="text-[11px] text-slate-400 leading-relaxed">
                    Fetches statutory registered voters, PU name, LGA name, State name, and the 18 registered INEC political parties list for any PU code.
                  </p>
                  <div className="bg-slate-900 p-2.5 rounded-lg border border-slate-800 text-[11px] font-mono text-slate-300 overflow-x-auto">
                    {`GET ${baseUrl}/pu/lookup?pu_code=19-01-01-001\nResponse: { "registered_voters": 599, "state_name": "Kano", "lga_name": "Kano Municipal", ... }`}
                  </div>
                </div>

                {/* Endpoint 3 */}
                <div className="bg-slate-950 border border-slate-800 rounded-xl p-3.5 space-y-2">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 font-mono text-[10px] font-black">
                        POST
                      </span>
                      <span className="text-xs font-mono font-bold text-white">/incidents</span>
                    </div>
                    <span className="text-[10px] text-slate-400 font-bold">Emergency Incident Beacon</span>
                  </div>
                  <p className="text-[11px] text-slate-400 leading-relaxed">
                    Sends emergency alarms (BVAS failure, thuggery, ballot snatching, late INEC arrival) with GPS coordinates to the Situation Room Rapid Response desk.
                  </p>
                </div>
              </div>

              <div className="pt-2 flex justify-between items-center text-xs text-slate-400">
                <span>Machine-readable OpenAPI 3.0 specification available:</span>
                <a
                  href="/api/v1/docs"
                  target="_blank"
                  rel="noreferrer"
                  className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-amber-300 font-bold text-xs rounded-lg flex items-center gap-1.5 transition"
                >
                  <ExternalLink className="w-3.5 h-3.5" />
                  <span>View OpenAPI JSON</span>
                </a>
              </div>
            </div>
          )}

          {/* TAB 3: CODE SNIPPETS */}
          {activeTab === 'CODE_SNIPPETS' && (
            <div className="space-y-4">
              <div className="flex items-center gap-2 border-b border-slate-800 pb-2">
                {(['FLUTTER', 'REACT_NATIVE', 'CURL', 'KOTLIN'] as const).map((lang) => (
                  <button
                    key={lang}
                    onClick={() => setSelectedSnippet(lang)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-bold font-mono transition ${
                      selectedSnippet === lang
                        ? 'bg-purple-600 text-white shadow'
                        : 'bg-slate-800 text-slate-400 hover:text-white'
                    }`}
                  >
                    {lang === 'FLUTTER'
                      ? 'Dart / Flutter'
                      : lang === 'REACT_NATIVE'
                      ? 'React Native / JS'
                      : lang === 'CURL'
                      ? 'cURL (Terminal)'
                      : 'Kotlin / Android'}
                  </button>
                ))}
              </div>

              <div className="relative">
                <button
                  onClick={() => {
                    const text =
                      selectedSnippet === 'FLUTTER'
                        ? flutterExample
                        : selectedSnippet === 'REACT_NATIVE'
                        ? reactNativeExample
                        : selectedSnippet === 'CURL'
                        ? curlExample
                        : kotlinExample;
                    handleCopy(text, 'snippet');
                  }}
                  className="absolute top-3 right-3 px-3 py-1.5 bg-slate-800/90 hover:bg-slate-700 text-white text-xs font-bold rounded-lg flex items-center gap-1 shadow border border-slate-700 transition"
                >
                  {copiedKey === 'snippet' ? <CheckCircle2 className="w-3 h-3 text-emerald-400" /> : <Copy className="w-3 h-3" />}
                  <span>{copiedKey === 'snippet' ? 'Copied!' : 'Copy Code'}</span>
                </button>

                <pre className="bg-slate-950 border border-slate-800 p-4 rounded-2xl text-xs font-mono text-emerald-300 overflow-x-auto leading-relaxed max-h-80">
                  {selectedSnippet === 'FLUTTER' && flutterExample}
                  {selectedSnippet === 'REACT_NATIVE' && reactNativeExample}
                  {selectedSnippet === 'CURL' && curlExample}
                  {selectedSnippet === 'KOTLIN' && kotlinExample}
                </pre>
              </div>

              <p className="text-[11px] text-slate-400">
                💡 Paste this function into your mobile app. When an agent submits Form EC8A, it immediately updates the Situation Room map and tally.
              </p>
            </div>
          )}

          {/* TAB 4: INTERACTIVE API TESTER */}
          {activeTab === 'TEST_API' && (
            <div className="space-y-4">
              <div className="bg-slate-950 border border-slate-800 rounded-2xl p-4 space-y-4">
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <span className="text-xs font-bold text-white flex items-center gap-1.5">
                    <Play className="w-4 h-4 text-sky-400" /> Live Endpoint Tester: POST /api/v1/results
                  </span>
                  <span className="text-[10px] text-slate-400 font-mono">Simulate External Mobile Transmission</span>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <label className="text-[10px] uppercase font-bold text-slate-400 block mb-1">
                      Polling Unit Code
                    </label>
                    <input
                      type="text"
                      value={testPuCode}
                      onChange={(e) => setTestPuCode(e.target.value)}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] uppercase font-bold text-slate-400 block mb-1">
                      Reporting Agent Name
                    </label>
                    <input
                      type="text"
                      value={testAgentName}
                      onChange={(e) => setTestAgentName(e.target.value)}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs text-white"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] uppercase font-bold text-emerald-400 block mb-1">
                      ADC Candidate Votes
                    </label>
                    <input
                      type="number"
                      value={testAdcVotes}
                      onChange={(e) => setTestAdcVotes(Number(e.target.value))}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono font-bold text-emerald-300"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] uppercase font-bold text-slate-400 block mb-1">
                      APC &amp; PDP Votes (Combined)
                    </label>
                    <div className="flex gap-2">
                      <input
                        type="number"
                        value={testApcVotes}
                        onChange={(e) => setTestApcVotes(Number(e.target.value))}
                        placeholder="APC"
                        className="w-1/2 px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
                      />
                      <input
                        type="number"
                        value={testPdpVotes}
                        onChange={(e) => setTestPdpVotes(Number(e.target.value))}
                        placeholder="PDP"
                        className="w-1/2 px-3 py-2 bg-slate-900 border border-slate-700 rounded-xl text-xs font-mono text-white"
                      />
                    </div>
                  </div>
                </div>

                <button
                  type="button"
                  disabled={testRunning}
                  onClick={runLiveApiTest}
                  className="w-full py-3 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white font-black text-xs rounded-xl shadow-lg flex items-center justify-center gap-2 transition active:scale-98 disabled:opacity-50"
                >
                  <Send className="w-4 h-4" />
                  <span>{testRunning ? 'Transmitting to /api/v1/results...' : 'Send Live API Transmission Test'}</span>
                </button>
              </div>

              {testResponse && (
                <div className="bg-slate-950 border border-slate-800 rounded-2xl p-4 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-slate-200">Server HTTP Response:</span>
                    <span
                      className={`px-2 py-0.5 rounded text-[10px] font-mono font-black ${
                        testResponse.ok
                          ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
                          : 'bg-rose-500/20 text-rose-300 border border-rose-500/30'
                      }`}
                    >
                      HTTP {testResponse.status} {testResponse.ok ? 'CREATED' : 'ERROR'}
                    </span>
                  </div>
                  <pre className="p-3 bg-black/60 rounded-xl text-[11px] font-mono text-slate-300 overflow-x-auto max-h-48">
                    {JSON.stringify(testResponse.data, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 bg-slate-950 border-t border-slate-800 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-400">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
            <span>CORS Enabled &bull; All 176,846 Polling Units Supported</span>
          </div>
          <button
            onClick={onClose}
            className="w-full sm:w-auto px-5 py-2 bg-slate-800 hover:bg-slate-700 text-white font-bold rounded-xl transition"
          >
            Done
          </button>
        </div>
      </div>
    </div>
  );
};
