import { useState, useEffect } from "react";

function solarAzimuth() {
  const d = new Date();
  const doy = Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
  const h = d.getUTCHours() + d.getUTCMinutes() / 60;
  const dec = 23.45 * Math.sin((2 * Math.PI * (284 + doy)) / 365);
  const dR = (dec * Math.PI) / 180;
  const lR = (66 * Math.PI) / 180;
  const eq = 229.18 * (0.000075 + 0.001868 * Math.cos((2 * Math.PI * doy) / 365) - 0.032077 * Math.sin((2 * Math.PI * doy) / 365));
  const ha = (((h * 60 + eq + 4 * 20) / 4 - 180) * Math.PI) / 180;
  const az = (Math.atan2(-Math.cos(dR) * Math.sin(ha), Math.sin(dR) * Math.cos(lR) - Math.cos(dR) * Math.cos(ha) * Math.sin(lR)) * 180) / Math.PI;
  return Math.round(((az + 360) % 360) * 10) / 10;
}

const FPV_OPTIONS = [
  { label: 'FPV 5" (5km, €270)', range: 5 },
  { label: 'FPV 7" (20km, €550)', range: 20 },
  { label: "Fiber-optic (5km, €350)", range: 5 },
];

export default function MissionPlanner() {
  const [alt, setAlt] = useState(300);
  const [dist, setDist] = useState(6);
  const [mast, setMast] = useState(10);
  const [fpvIdx, setFpvIdx] = useState(1);
  const [sunAz, setSunAz] = useState(0);

  useEffect(() => setSunAz(solarAzimuth()), []);

  const lambda = 0.3454;
  const gcsTop = 190 + mast;
  const f1Mid = Math.sqrt((lambda * dist * 500 * dist * 500) / (dist * 1000));
  const losMid = gcsTop + (alt - gcsTop) * 0.5;
  const clearance = losMid - 220 - f1Mid * 0.6;
  const losKm = Math.sqrt((2 * 6371 * alt) / 1000);
  const fpvRange = FPV_OPTIONS[fpvIdx].range;
  const inRange = dist <= fpvRange;
  const linkOk = clearance > 0;
  const viable = linkOk && inRange;

  const statusColor = viable ? "#059669" : !linkOk ? "#dc2626" : "#d97706";
  const statusText = viable ? "STRIKE VIABLE — Link OK, target in FPV range" : !linkOk ? "LINK BLOCKED — Raise Fischer 26 altitude" : "TARGET OUT OF FPV RANGE";

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 p-4 md:p-8" style={{ fontFamily: "'JetBrains Mono', 'Fira Code', monospace" }}>
      <div className="max-w-2xl mx-auto">
        <div className="flex items-center gap-3 mb-1">
          <div className="w-2 h-2 rounded-full bg-sky-400 animate-pulse" />
          <span className="text-[10px] tracking-[4px] text-slate-500 uppercase">Lisa 26 // Mission Planning</span>
        </div>
        <h1 className="text-2xl font-bold tracking-tight mb-1 text-white">MISSION PLANNER</h1>
        <p className="text-xs text-slate-500 mb-6">GPS-Denied • Fresnel zone • Solar azimuth • FPV range</p>

        {/* Inputs */}
        <div className="grid grid-cols-3 gap-3 mb-4">
          {[
            { label: "F26 Altitude (m ASL)", value: alt, set: setAlt, min: 50, max: 1000, step: 10 },
            { label: "Distance to Target (km)", value: dist, set: setDist, min: 1, max: 50, step: 0.5 },
            { label: "Mast Height (m)", value: mast, set: setMast, min: 0, max: 50, step: 1 },
          ].map((inp) => (
            <div key={inp.label} className="bg-slate-900 border border-slate-800 rounded-lg p-3">
              <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">{inp.label}</label>
              <input
                type="number"
                value={inp.value}
                min={inp.min}
                max={inp.max}
                step={inp.step}
                onChange={(e) => inp.set(parseFloat(e.target.value) || 0)}
                className="w-full bg-slate-800 border border-slate-700 rounded px-3 py-2 text-lg font-bold text-white focus:outline-none focus:border-sky-500"
              />
            </div>
          ))}
        </div>

        {/* FPV selector + Solar */}
        <div className="grid grid-cols-2 gap-3 mb-6">
          <div className="bg-slate-900 border border-slate-800 rounded-lg p-3">
            <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">FPV Drone</label>
            <select
              value={fpvIdx}
              onChange={(e) => setFpvIdx(parseInt(e.target.value))}
              className="w-full bg-slate-800 border border-slate-700 rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-sky-500"
            >
              {FPV_OPTIONS.map((o, i) => (
                <option key={i} value={i}>{o.label}</option>
              ))}
            </select>
          </div>
          <div className="bg-slate-900 border border-slate-800 rounded-lg p-3 flex items-center">
            <div>
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Solar Azimuth</div>
              <div className="text-amber-400 text-sm font-bold">☀ {sunAz}° — FPV approach: {Math.round(sunAz)}° ±15°</div>
            </div>
          </div>
        </div>

        {/* Results */}
        <div className="bg-slate-900 border border-slate-800 rounded-xl p-6 mb-4">
          <div className="grid grid-cols-4 gap-4 mb-6">
            {[
              { label: "Fresnel F1", value: `${f1Mid.toFixed(1)}m`, color: "text-sky-400" },
              { label: "LOS Horizon", value: `${losKm.toFixed(0)}km`, color: "text-emerald-400" },
              { label: "Link", value: linkOk ? "OK" : "BLOCKED", color: linkOk ? "text-emerald-400" : "text-red-400" },
              { label: "FPV Range", value: inRange ? "IN" : "OUT", color: inRange ? "text-emerald-400" : "text-red-400" },
            ].map((m) => (
              <div key={m.label} className="text-center">
                <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">{m.label}</div>
                <div className={`text-2xl font-bold ${m.color}`}>{m.value}</div>
              </div>
            ))}
          </div>

          <div
            className="rounded-lg py-3 px-4 text-center text-sm font-bold tracking-wide"
            style={{ backgroundColor: statusColor + "22", color: statusColor, border: `1px solid ${statusColor}44` }}
          >
            {statusText}
          </div>
        </div>

        {/* Formula */}
        <div className="bg-slate-900 border border-slate-800 rounded-lg p-4 text-xs text-slate-500">
          λ=0.3454m (868MHz) · F1=√(λ×d1×d2/D) · GCS: {gcsTop}m · F26: {alt}m at {dist}km · Clearance: {clearance.toFixed(0)}m
        </div>

        <div className="mt-6 text-center text-[10px] text-slate-600 tracking-widest uppercase">
          FSG-A // Lisa 26 // CC BY-SA 4.0
        </div>
      </div>
    </div>
  );
}
