import { useState, useEffect } from "react";

const STEPS = [
  { title: "UTGÅNGSLÄGE", sub: "12 Fischer-plattformar i luften över AO" },
  { title: "RF EMISSION DETEKTERAD", sub: "Rysk FPV-operatör sänder på 2.4 GHz" },
  { title: "BÄRING 048° — F26E #1", sub: "Phased array mäter vinkel till sändaren" },
  { title: "BÄRING 079° — F26E #2", sub: "Andra bäringen, 3.2 km baslinle" },
  { title: "BÄRING 032° — F26E #3", sub: "Tredje bäringen — triangulering komplett" },
  { title: "RSSI FRÅN 8× FISCHER 26", sub: "Signalstyrka bekräftar avstånd ~5 km" },
  { title: "POSITION FUSIONERAD ±76m", sub: "Lisa 26 Dempster-Shafer — konfidens 94%" },
  { title: "ARCHER ELDUPPDRAG", sub: "BC godkänner — visuellt verifierad" },
  { title: "TRÄFF — GCS FÖRSTÖRD", sub: "3× 155mm HE — BDA bekräftad" },
  { title: "40 FPV/DAG ELIMINERADE", sub: "Kostnad: €10 500 — ROI: 12 timmar" },
];

const RU = { x: 540, y: 175 };
const E = [
  { x: 260, y: 195, c: "#22d3ee" },
  { x: 340, y: 340, c: "#a855f7" },
  { x: 185, y: 300, c: "#22c55e" },
  { x: 150, y: 175, c: "#64748b" },
];
const F = [
  { x: 290, y: 130 }, { x: 380, y: 175 }, { x: 420, y: 260 }, { x: 340, y: 275 },
  { x: 230, y: 255 }, { x: 190, y: 375 }, { x: 295, y: 375 }, { x: 140, y: 245 },
];

function brg(a, b) { return Math.atan2(b.x - a.x, -(b.y - a.y)); }
function dst(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); }
function bEnd(from, ang, len) { return { x: from.x + Math.sin(ang) * len, y: from.y - Math.cos(ang) * len }; }
function cone(from, ang, err, len) {
  const p1 = bEnd(from, ang - err, len), p2 = bEnd(from, ang + err, len);
  return `M ${from.x},${from.y} L ${p1.x},${p1.y} A ${len} ${len} 0 0 1 ${p2.x},${p2.y} Z`;
}

export default function App() {
  const [step, setStep] = useState(0);
  const [auto, setAuto] = useState(false);
  const [tick, setTick] = useState(0);

  useEffect(() => { const t = setInterval(() => setTick(p => p + 1), 700); return () => clearInterval(t); }, []);
  useEffect(() => {
    if (!auto || step >= 9) return;
    const t = setTimeout(() => setStep(s => s + 1), 3500);
    return () => clearTimeout(t);
  }, [auto, step]);

  const s = STEPS[step];
  const bearings = E.map(e => brg(e, RU));
  const er = 0.06;
  const est = step >= 6 ? { x: RU.x + 6, y: RU.y - 4 } : null;

  return (
    <div style={{ minHeight: "100vh", background: "#030608", color: "#e2e8f0", fontFamily: "monospace", padding: 16 }}>
      <div style={{ maxWidth: 1000, margin: "0 auto" }}>

        {/* HEADER */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 10 }}>
          <div style={{ width: 18, height: 18, borderRadius: 9, background: "#22c55e" }} />
          <span style={{ fontSize: 32, fontWeight: 800, color: "#fff" }}>LISA 26</span>
          <span style={{ fontSize: 20, color: "#64748b", letterSpacing: 4 }}>RF TRIANGULERING</span>
        </div>

        {/* STEP PROGRESS */}
        <div style={{ display: "flex", gap: 3, marginBottom: 12 }}>
          {STEPS.map((_, i) => (
            <button key={i} onClick={() => { setStep(i); setAuto(false); }}
              style={{ flex: 1, height: 12, borderRadius: 6, border: "none", cursor: "pointer",
                background: i <= step ? "#22d3ee" : "#1e293b" }} />
          ))}
        </div>

        {/* CURRENT STEP - LARGE */}
        <div style={{ background: "#0f172a", border: "3px solid #1e293b", borderRadius: 12, padding: 20, marginBottom: 14,
          display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
          <div>
            <div style={{ fontSize: 18, color: "#64748b", marginBottom: 4 }}>STEG {step + 1} / 10</div>
            <div style={{ fontSize: 36, fontWeight: 800, color: "#22d3ee", lineHeight: 1.2 }}>{s.title}</div>
            <div style={{ fontSize: 22, color: "#94a3b8", marginTop: 6 }}>{s.sub}</div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setStep(Math.max(0, step - 1))}
              style={{ padding: "12px 22px", background: "#1e293b", color: "#94a3b8", border: "none", borderRadius: 8, fontSize: 24, cursor: "pointer", fontFamily: "monospace" }}>◀</button>
            <button onClick={() => setAuto(!auto)}
              style={{ padding: "12px 28px", background: auto ? "#450a0a" : "#052e16", color: auto ? "#ef4444" : "#22c55e", border: "none", borderRadius: 8, fontSize: 22, fontWeight: 700, cursor: "pointer", fontFamily: "monospace" }}>
              {auto ? "⏸ STOPP" : "▶ SPELA"}
            </button>
            <button onClick={() => setStep(Math.min(9, step + 1))}
              style={{ padding: "12px 22px", background: "#1e293b", color: "#94a3b8", border: "none", borderRadius: 8, fontSize: 24, cursor: "pointer", fontFamily: "monospace" }}>▶</button>
          </div>
        </div>

        {/* MAP */}
        <div style={{ background: "#0a0e14", border: "2px solid #1e293b", borderRadius: 10, overflow: "hidden" }}>
          <svg viewBox="0 0 700 430" style={{ width: "100%", display: "block", background: "#070b10" }}>

            {/* Contours */}
            {[[100, "#0d2a1a", 350], [180, "#123520", 280], [260, "#174020", 215], [330, "#1c4a28", 155]].map(([e, c, y], i) => (
              <g key={i}><path d={`M 10,${y} Q 180,${y - 12} 350,${y - 2} Q 530,${y + 8} 690,${y - 10}`} fill="none" stroke={c} strokeWidth={1} />
                <text x={680} y={y - 2} fill={c} fontSize={11} fontWeight="bold">{e}m</text></g>
            ))}

            {/* River */}
            <path d="M 20,265 Q 180,252 350,262 Q 510,273 690,258" fill="none" stroke="#0c2a4a" strokeWidth={3} opacity={0.4} />
            <text x={350} y={280} fill="#1a4a6a" fontSize={12} textAnchor="middle" fontStyle="italic">Piteälven</text>

            {/* AO */}
            <rect x={70} y={70} width={570} height={340} fill="none" stroke="#1e293b" strokeWidth={1} strokeDasharray="8,5" rx={6} />
            <text x={80} y={88} fill="#334155" fontSize={12} fontWeight="bold">AO 100 km²</text>

            {/* RSSI rings step 5+ */}
            {step >= 5 && F.map((f, i) => {
              const d = dst(f, RU);
              return <g key={`rs${i}`} opacity={0.1}>
                <circle cx={f.x} cy={f.y} r={d * 0.65} fill="none" stroke="#3b82f6" strokeWidth={1} strokeDasharray="3,4" />
                <circle cx={f.x} cy={f.y} r={d * 1.35} fill="none" stroke="#3b82f6" strokeWidth={1} strokeDasharray="3,4" />
              </g>;
            })}

            {/* Bearing cones */}
            {step >= 2 && <path d={cone(E[0], bearings[0], er, 380)} fill={E[0].c} opacity={0.12} />}
            {step >= 3 && <path d={cone(E[1], bearings[1], er, 380)} fill={E[1].c} opacity={0.12} />}
            {step >= 4 && <path d={cone(E[2], bearings[2], er, 380)} fill={E[2].c} opacity={0.12} />}

            {/* Bearing center lines */}
            {step >= 2 && (() => { const end = bEnd(E[0], bearings[0], 380); return <line x1={E[0].x} y1={E[0].y} x2={end.x} y2={end.y} stroke={E[0].c} strokeWidth={1.5} strokeDasharray="6,4" opacity={0.6} />; })()}
            {step >= 3 && (() => { const end = bEnd(E[1], bearings[1], 380); return <line x1={E[1].x} y1={E[1].y} x2={end.x} y2={end.y} stroke={E[1].c} strokeWidth={1.5} strokeDasharray="6,4" opacity={0.6} />; })()}
            {step >= 4 && (() => { const end = bEnd(E[2], bearings[2], 380); return <line x1={E[2].x} y1={E[2].y} x2={end.x} y2={end.y} stroke={E[2].c} strokeWidth={1.5} strokeDasharray="6,4" opacity={0.6} />; })()}

            {/* Bearing labels - LARGE */}
            {step >= 2 && <text x={E[0].x + 35} y={E[0].y - 18} fill={E[0].c} fontSize={20} fontWeight="800">048°</text>}
            {step >= 3 && <text x={E[1].x + 30} y={E[1].y - 14} fill={E[1].c} fontSize={20} fontWeight="800">079°</text>}
            {step >= 4 && <text x={E[2].x + 25} y={E[2].y - 18} fill={E[2].c} fontSize={20} fontWeight="800">032°</text>}

            {/* Fusion ellipse */}
            {step >= 6 && est && <g>
              <ellipse cx={est.x} cy={est.y} rx={22} ry={17} fill="none" stroke="#f59e0b" strokeWidth={2.5} strokeDasharray="4,3" />
              <line x1={est.x - 10} y1={est.y} x2={est.x + 10} y2={est.y} stroke="#f59e0b" strokeWidth={1.5} />
              <line x1={est.x} y1={est.y - 10} x2={est.x} y2={est.y + 10} stroke="#f59e0b" strokeWidth={1.5} />
              <text x={est.x + 28} y={est.y - 6} fill="#f59e0b" fontSize={20} fontWeight="800">±76m</text>
              <text x={est.x + 28} y={est.y + 10} fill="#f59e0b" fontSize={14}>94% konfidens</text>
            </g>}

            {/* Archer arc step 8+ */}
            {step >= 8 && <g>
              <path d={`M 110,390 Q ${(110 + RU.x) / 2},${Math.min(200, RU.y) - 100} ${RU.x},${RU.y}`}
                fill="none" stroke="#f97316" strokeWidth={1.5} strokeDasharray="5,5" opacity={0.5} />
              <text x={230} y={220} fill="#f97316" fontSize={18} fontWeight="700">ARCHER 155mm ×3</text>
              <circle cx={RU.x} cy={RU.y} r={15} fill="#ff4400" opacity={0.2}>
                <animate attributeName="r" from="8" to="30" dur="0.8s" repeatCount="indefinite" />
                <animate attributeName="opacity" from="0.25" to="0" dur="0.8s" repeatCount="indefinite" />
              </circle>
            </g>}

            {/* Destroyed */}
            {step >= 9 && <g>
              <text x={RU.x} y={RU.y + 6} textAnchor="middle" fill="#ff4400" fontSize={32} opacity={0.7}>✕</text>
              <text x={RU.x} y={RU.y + 28} textAnchor="middle" fill="#ff4400" fontSize={16} fontWeight="700">GCS FÖRSTÖRD</text>
            </g>}

            {/* Russian GCS */}
            {step >= 1 && step < 9 && <g>
              {[1, 2, 3].map(i => (
                <circle key={i} cx={RU.x} cy={RU.y} r={18 * i} fill="none" stroke="#ff4444" strokeWidth={0.8} opacity={0.2}>
                  <animate attributeName="r" from={12 * i} to={35 * i} dur={`${1.2 + i * 0.3}s`} repeatCount="indefinite" />
                  <animate attributeName="opacity" from={0.25} to={0} dur={`${1.2 + i * 0.3}s`} repeatCount="indefinite" />
                </circle>
              ))}
              <circle cx={RU.x} cy={RU.y} r={12} fill="#1a0000" stroke="#ff4444" strokeWidth={2} />
              <text x={RU.x} y={RU.y + 5} textAnchor="middle" fill="#ff4444" fontSize={12}>📡</text>
              <text x={RU.x} y={RU.y - 18} textAnchor="middle" fill="#cc2020" fontSize={14} fontWeight="700">
                {step < 6 ? "RU FPV GCS" : "LOKALISERAD"}
              </text>
              <text x={RU.x} y={RU.y - 6} textAnchor="middle" fill="#882020" fontSize={10}>2.4 GHz emission</text>
            </g>}

            {/* RU FPVs */}
            {step >= 1 && step < 9 && [{ x: RU.x - 45, y: RU.y - 35 }, { x: RU.x + 25, y: RU.y - 50 }, { x: RU.x - 18, y: RU.y + 40 }].map((fp, i) => (
              <g key={`rf${i}`}>
                <line x1={RU.x} y1={RU.y} x2={fp.x} y2={fp.y} stroke="#661010" strokeWidth={0.6} strokeDasharray="2,3" />
                <circle cx={fp.x} cy={fp.y} r={4} fill="#200000" stroke="#cc2020" strokeWidth={0.8} />
                <text x={fp.x} y={fp.y + 2.5} textAnchor="middle" fill="#ff4444" fontSize={6}>⚡</text>
              </g>
            ))}

            {/* F26E platforms - LARGE LABELS */}
            {E.map((e, i) => {
              const active = step >= 2 + i && i < 3;
              return <g key={`e${i}`}>
                <circle cx={e.x} cy={e.y} r={14} fill={`${e.c}15`} stroke={e.c} strokeWidth={active ? 3 : 1.2} />
                <text x={e.x} y={e.y + 5} textAnchor="middle" fill={e.c} fontSize={14} fontWeight="800">E{i + 1}</text>
                <text x={e.x} y={e.y - 18} textAnchor="middle" fill={e.c} fontSize={12} fontWeight="700">F26E #{i + 1}</text>
                <text x={e.x} y={e.y - 8} textAnchor="middle" fill={`${e.c}99`} fontSize={9}>700m • AD9361</text>
                {tick % 3 === 0 && <circle cx={e.x} cy={e.y} r={14} fill="none" stroke={e.c} strokeWidth={0.8} opacity={0.3}>
                  <animate attributeName="r" from="14" to="26" dur="0.6s" /><animate attributeName="opacity" from="0.3" to="0" dur="0.6s" />
                </circle>}
                {active && <circle cx={e.x + 16} cy={e.y - 16} r={5} fill={e.c}>
                  <animate attributeName="opacity" from="1" to="0.2" dur="0.5s" repeatCount="indefinite" />
                </circle>}
              </g>;
            })}

            {/* F26 standard - labeled */}
            {F.map((f, i) => (
              <g key={`f${i}`}>
                <circle cx={f.x} cy={f.y} r={8} fill="#0a1530" stroke="#3b82f6" strokeWidth={step >= 5 ? 2 : 0.8} />
                <text x={f.x} y={f.y + 3} textAnchor="middle" fill="#3b82f6" fontSize={10} fontWeight="700">{i + 1}</text>
                {step >= 5 && <text x={f.x + 12} y={f.y - 4} fill="#3b82f6" fontSize={10} fontWeight="700">RSSI</text>}
              </g>
            ))}

            {/* Archer */}
            <g>
              <rect x={90} y={383} width={28} height={18} fill="#0a200a" stroke="#4a8a4a" strokeWidth={1.5} rx={3} />
              <text x={104} y={396} textAnchor="middle" fill="#6aaa6a" fontSize={10} fontWeight="700">ARC</text>
              <text x={104} y={410} textAnchor="middle" fill="#4a7a4a" fontSize={9}>Archer 155mm</text>
            </g>

            {/* BDE TOC */}
            <rect x={73} y={282} width={24} height={18} fill="#0a1a30" stroke="#3a6a90" strokeWidth={1.5} rx={3} />
            <text x={85} y={295} textAnchor="middle" fill="#7abaee" fontSize={12}>⌂</text>
            <text x={85} y={310} textAnchor="middle" fill="#5a8aaa" fontSize={9} fontWeight="700">BDE TOC</text>

            {/* Scale */}
            <line x1={25} y1={415} x2={110} y2={415} stroke="#3a5a6a" strokeWidth={2} />
            <line x1={25} y1={408} x2={25} y2={422} stroke="#3a5a6a" strokeWidth={1.5} />
            <line x1={110} y1={408} x2={110} y2={422} stroke="#3a5a6a" strokeWidth={1.5} />
            <text x={67} y={408} textAnchor="middle" fill="#3a5a6a" fontSize={12} fontWeight="700">5 km</text>
          </svg>
        </div>

        {/* EXPLANATION - VERY LARGE TEXT */}
        <div style={{ background: "#0f172a", border: "3px solid #1e293b", borderRadius: 12, padding: 24, marginTop: 14 }}>
          <div style={{ fontSize: 22, lineHeight: 1.7, color: step >= 8 ? "#4ade80" : step >= 6 ? "#fbbf24" : step >= 1 ? "#cbd5e1" : "#94a3b8" }}>
            {step === 0 && "4 stycken Fischer 26E på 700 meters höjd med AD9361 SDR som lyssnar passivt på allt mellan 70 MHz och 6 GHz. 8 stycken Fischer 26 standard med Silvus SL5200 radio. Lisa 26 visar alla vänliga som blå (IFF heartbeat). Inga fiender detekterade ännu."}
            {step === 1 && <>En rysk FPV-operatör startar sin sändarutrustning på <span style={{ color: "#ff4444", fontWeight: 700, fontSize: 26 }}>2.4 GHz</span>. RF-emissionen sprider sig i alla riktningar. Alla F26E:s AD9361 detekterar den nya signalen. <span style={{ color: "#ff4444", fontWeight: 700, fontSize: 26 }}>Inget IFF heartbeat → FIENTLIG.</span></>}
            {step === 2 && <>F26E #1 mäter <span style={{ color: "#22d3ee", fontWeight: 700, fontSize: 26 }}>bäring 048°</span> med sin 4-elements phased array. Den cyanblå konen visar osäkerhetsområdet (±3.4°). Fienden är någonstans längs denna linje — men vi vet inte exakt var ännu.</>}
            {step === 3 && <>F26E #2, som flyger <span style={{ color: "#a855f7", fontWeight: 700, fontSize: 26 }}>3.2 km söder om #1</span>, mäter bäring 079°. Den lila konen skär den cyanblå. Där konerna överlappar finns fienden — området har krympt dramatiskt.</>}
            {step === 4 && <>F26E #3 mäter <span style={{ color: "#22c55e", fontWeight: 700, fontSize: 26 }}>bäring 032°</span>. Tre bäringar = triangulering. Skärningspunkten ger position <span style={{ color: "#22c55e", fontWeight: 700, fontSize: 26 }}>±119 meter</span>. Tillräckligt för Archer — men vi kan göra bättre.</>}
            {step === 5 && <>Alla <span style={{ color: "#3b82f6", fontWeight: 700, fontSize: 26 }}>8 stycken Fischer 26 standard</span> mäter signalstyrka (RSSI) via Silvus-radion. Varje mätning ger ett avstånd med ±50% osäkerhet. 8 mätningar tillsammans → ±707m. Grovt men bekräftar AoA-resultatet.</>}
            {step === 6 && <>Lisa 26 fusionerar <span style={{ color: "#fbbf24", fontWeight: 700, fontSize: 26 }}>alla 12 mätningar</span> (4 AoA + 8 RSSI) med Dempster-Shafer. Fusionerad position: <span style={{ color: "#fbbf24", fontWeight: 700, fontSize: 30 }}>±76 meter, 94% konfidens</span>. Den gula ellipsen visar osäkerhetsområdet.</>}
            {step === 7 && <>Lisa 26 genererar L2-rekommendation: Archer elduppdrag. Bataljonchefen godkänner. <span style={{ color: "#22d3ee", fontWeight: 700, fontSize: 26 }}>KRITISKT: F26 ISR verifierar VISUELLT — inte en decoy.</span> Archer beräknar lösning.</>}
            {step === 8 && <><span style={{ color: "#f97316", fontWeight: 700, fontSize: 28 }}>3 × Archer 155mm HE avfyrade.</span> F26 ISR observerar nedslag. Rund 1: 30m kort — Lisa 26 auto-korrigerar. Rund 2 och 3: TRÄFF. GCS bekräftad förstörd.</>}
            {step === 9 && <><span style={{ color: "#4ade80", fontWeight: 700, fontSize: 30 }}>RESULTAT:</span> 3 operatörer + utrustning förstörd. <span style={{ color: "#4ade80", fontWeight: 700, fontSize: 26 }}>40 FPV/dag kapacitet ELIMINERAD.</span> Kostnad: 3 granater (€10 500). Tid: 3 minuter. <span style={{ fontSize: 26, fontWeight: 700 }}>ROI: betalt på 12 timmar.</span></>}
          </div>
        </div>

        {/* MATH - LARGE */}
        <div style={{ background: "#0f172a", border: "2px solid #1e293b", borderRadius: 10, padding: 16, marginTop: 10, fontSize: 17, color: "#64748b", lineHeight: 1.6 }}>
          <span style={{ color: "#475569", fontWeight: 700, fontSize: 18 }}>MATEMATIK: </span>
          {step < 2 && "IFF identifierar vänner (heartbeat). SDR lokaliserar fiender (passiv mottagning). Två separata system."}
          {step >= 2 && step < 5 && "AoA-precision: beamwidth 34° / √SNR(20dB) = ±3.4° per F26E. Tre bäringar → skärningspunkt ±119m."}
          {step === 5 && "RSSI: P_rx = P_tx − FSPL → avstånd. 8 mätningar: precision förbättras med √8. Resultat ±707m."}
          {step >= 6 && step < 8 && "Fusion: σ = 1/√(1/119² + 1/707²) = ±76m. Dempster-Shafer: 1−(1−0.85)(1−0.60) = 94%."}
          {step >= 8 && "Archer Pk vs GCS: 1−exp(−(15/8)²×0.6931) = 91.3% per granat. P(miss alla 3) = 0.07%."}
        </div>

        <div style={{ marginTop: 14, textAlign: "center", fontSize: 14, color: "#334155", letterSpacing: 3 }}>
          FSG-A // LISA 26 RF TRIANGULERING // CC BY-SA 4.0
        </div>
      </div>
    </div>
  );
}
