/* Inspection Planner — MIC Setup. Split layout: decisions left, inherited right. */

function PlannerPage({ go, mic, site, setStage }) {
  site = site || (window.SITES || []).find(s => s.id === localStorage.getItem("skyops_site")) || (window.SITES || [])[2];
  mic = mic || (window.INSPECTIONS || []).find(i => i.id === localStorage.getItem("skyops_mic"));
  const prof = window.siteProfile ? window.siteProfile(site) : null;
  const [zoneSel, setZoneSel] = useState(() => new Set(prof ? prof.zones.map(z => z.id) : []));
  React.useEffect(() => { if (prof) setZoneSel(new Set(prof.zones.map(z => z.id))); }, [site && site.id]);
  const selZ = prof ? prof.zones.filter(z => zoneSel.has(z.id)) : [];
  const selHa = selZ.reduce((a, z) => a + z.ha, 0), selSort = selZ.reduce((a, z) => a + z.sorties, 0);
  const flightMin = selSort * (prof ? prof.P.usable : 32);
  const minIrr = window.setStore ? window.setStore.v.minIrr : 600;
  const [, force] = useState(0);
  const committed = mic && (mic.progress?.scheduled ?? 0) >= 1;
  const checks = [
    ["Zones selected", selZ.length > 0, selZ.length ? `${selZ.length} zones · ${selHa.toFixed(1)} ha` : "Select at least one zone"],
    ["Pilot assigned", !!(mic && mic.lead), (mic && mic.lead) || "Assign in New inspection"],
    ["Drone assigned", !!(mic && mic.drone), (mic && mic.drone) || "Assign in New inspection"],
    ["Flight date", !!(mic && mic.plannedFor), (mic && mic.plannedFor) || "Not scheduled"],
  ];
  const ready = mic && checks.every(c => c[1]);
  const commit = () => {
    if (!ready) return;
    mic.progress = { ...(mic.progress || {}), draft: 1, scheduled: 1 };
    mic.status = "scheduled"; mic.zones = selZ.map(z => z.id); mic.area_ha = +selHa.toFixed(1); mic.flights = selSort; mic.committedAt = new Date().toISOString().slice(0, 16).replace("T", " ");
    window.saveMicState && window.saveMicState(mic);
    try { const s = JSON.parse(localStorage.getItem("skyops_new_insps") || "[]"); const i = s.findIndex(x => x.id === mic.id); if (i >= 0) { s[i] = { ...s[i], ...mic }; localStorage.setItem("skyops_new_insps", JSON.stringify(s)); } } catch {}
    force(x => x + 1);
    setStage ? setStage("fly") : go("flight");
  };
  const toggleZ = (id) => setZoneSel(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const [purpose, setPurpose] = useState("routine");
  const [template, setTemplate] = useState("IEC TS 62446-3 · Standard");
  const [gsd, setGsd] = useState(prof ? prof.gsd : 3.0);
  const [weather, setWeather] = useState(15);
  const [tracker, setTracker] = useState("auto");
  const [baseline, setBaseline] = useState("MIC-2026-01-017");
  const [applyInherited, setApplyInherited] = useState(true);

  return (
    <div className="page">
      <div className="page-head">
        <div className="title">
          <div className="kicker">The MIC is not a form — it is an architectural construct</div>
          <h1>Inspection planner</h1>
          <div className="sub">{site.name} · <span className="mono">{mic ? mic.id : "new"}</span> · {mic ? mic.status : "draft"} · {mic && mic.plannedFor ? "flight " + mic.plannedFor : ""}</div>
        </div>
        <div className="actions">
          <button className="btn btn-secondary"><Icon name="history" />Version history</button>
          <button className="btn btn-secondary" onClick={() => go("flight")}><Icon name="drone" />Open flight planner</button>
          {committed ? <button className="btn btn-primary" onClick={() => setStage ? setStage("fly") : go("flight")}><Icon name="drone" />Go to Fly</button>
            : <button className="btn btn-primary" disabled={!ready} title={ready ? "" : "Complete the checklist below"} onClick={commit}><Icon name="send" />Commit & brief pilot</button>}
        </div>
      </div>
      {window.CoreStrip && <window.CoreStrip dom={["planning", "fleet"]} siteId={site.id} title="Argus · planning advice for this site"/>}
      {mic && <div className={`pl-gate ${committed ? "is-done" : ready ? "is-ready" : ""}`}>
        <span className="pl-gate-t">{committed ? <><Icon name="check_circle" size={13}/>Plan committed{mic.committedAt ? " · " + mic.committedAt : ""} — Fly is unlocked</> : ready ? <><Icon name="check_circle" size={13}/>Ready to commit</> : <><Icon name="lock" size={13}/>To unlock Fly</>}</span>
        {checks.map(([l, ok, d]) => <span key={l} className={`pl-chk ${ok ? "ok" : ""}`}><i>{ok ? <Icon name="check" size={9}/> : null}</i><b>{l}</b><em>{d}</em></span>)}
      </div>}

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 16 }}>
        <div className="col" style={{ gap: 16 }}>
          <div className="card">
            <div className="card-hd">Direction<span className="sub">What this inspection must answer</span></div>
            <div style={{ padding: 16, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div className="field">
                <label>Site</label>
                <div className="inp" style={{ display: "flex", alignItems: "center" }}>
                  <span className="mono" style={{ fontSize: 11, marginRight: 8, color: "var(--fg-muted)" }}>{site.id.toUpperCase()}</span>
                  {site.name}
                </div>
              </div>
              <div className="field">
                <label>Purpose</label>
                <select className="sel" value={purpose} onChange={e => setPurpose(e.target.value)}>
                  <option value="routine">Routine</option>
                  <option value="warranty">Warranty claim</option>
                  <option value="commissioning">Commissioning</option>
                  <option value="post_incident">Post-incident</option>
                  <option value="asset_sale">Asset sale</option>
                  <option value="regulatory">Regulatory audit</option>
                </select>
                <span className="hint">Drives report template, thresholds, evidence retention.</span>
              </div>
              <div className="field">
                <label>Report template</label>
                <select className="sel" value={template} onChange={e => setTemplate(e.target.value)}>
                  <option>IEC TS 62446-3 · Standard</option>
                  <option>IEC TS 62446-3 · Warranty (extended)</option>
                  <option>IEC TS 62446-3 · Post-incident</option>
                  <option>Iberdrola · Internal cadence</option>
                </select>
              </div>
              <div className="field">
                <label>Baseline</label>
                <select className="sel" value={baseline} onChange={e => setBaseline(e.target.value)}>
                  <option>MIC-2026-01-017 · Previous cycle (2026-01-14)</option>
                  <option>MIC-2025-10-008 · Q4 2025</option>
                  <option>None — first inspection</option>
                </select>
                <span className="hint">Drives temporal comparison: NEW / PERSISTENT / RESOLVED / DEGRADED.</span>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-hd">Collection parameters</div>
            <div style={{ padding: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
              <div className="field">
                <label>GSD target</label>
                <div className="row" style={{ gap: 10 }}>
                  <input type="range" min="1.5" max="6" step="0.1" value={gsd} onChange={e => setGsd(+e.target.value)} style={{ flex: 1 }}/>
                  <span className="mono num" style={{ minWidth: 60, textAlign: "right" }}>{gsd.toFixed(1)} cm/px</span>
                </div>
                <span className="hint">Thermal ≤ 3 cm/px for cell-level defects.</span>
              </div>
              <div className="field">
                <label>Weather cutoff — wind</label>
                <div className="row" style={{ gap: 10 }}>
                  <input type="range" min="5" max="30" step="1" value={weather} onChange={e => setWeather(+e.target.value)} style={{ flex: 1 }}/>
                  <span className="mono num" style={{ minWidth: 60, textAlign: "right" }}>{weather} km/h</span>
                </div>
                <span className="hint">Abort if forecast exceeds at launch.</span>
              </div>
              <div className="field">
                <label>Tracker mode instruction</label>
                <select className="sel" value={tracker} onChange={e => setTracker(e.target.value)}>
                  <option value="auto">Auto-follow sun</option>
                  <option value="flat">Lock flat (0°)</option>
                  <option value="bank_15">Lock bank 15°</option>
                  <option value="bank_25">Lock bank 25°</option>
                </select>
                <span className="hint">Issued to SCADA ≥ 30 min before launch.</span>
              </div>
              <div className="field">
                <label>Irradiance floor</label>
                <div className="inp mono">{minIrr} W/m²</div>
              </div>
              <div className="field">
                <label>Flight window</label>
                <div className="inp mono" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title="Local time">{(mic && mic.plannedFor) || "—"} · 10:40–14:20</div>
              </div>
              <div className="field">
                <label>Platform</label>
                <div className="inp">{(mic && mic.drone) || (prof && prof.platform)}</div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-hd">Zones in this inspection<span className="sub">From site setup · {prof ? prof.zones.length : 0} zones · {prof ? prof.area.toFixed(1) : "—"} ha fenced</span>
              <div className="actions"><button className="btn btn-ghost btn-xs" onClick={() => setZoneSel(new Set(prof.zones.map(z => z.id)))}>All</button><button className="btn btn-ghost btn-xs" onClick={() => setZoneSel(new Set())}>None</button></div></div>
            <div style={{ padding: 0 }}>
              {prof && <PlanZoneMap prof={prof} sel={zoneSel} toggle={toggleZ}/>}
              {prof && <div className="pz-list">{prof.zones.map(z => (
                <button key={z.id} className={`pz-it ${zoneSel.has(z.id) ? "on" : ""}`} onClick={() => toggleZ(z.id)}>
                  <i style={{ background: `hsl(${z.hue},70%,62%)` }}/><b className="mono">{z.id}</b><span className="mono">{z.ha.toFixed(1)} ha</span><span className="mono sec">{z.sorties} sorties</span>
                  <span className="pz-chk">{zoneSel.has(z.id) && <Icon name="check" size={10}/>}</span>
                </button>))}</div>}
              <div style={{ padding: "10px 14px", borderTop: "1px solid var(--border-base)", display: "flex", gap: 16, fontSize: 11, color: "var(--fg-secondary)" }}>
                <span>Selected <b className="num">{selZ.length}/{prof ? prof.zones.length : 0} zones</b></span>
                <span>Area <b className="num">{selHa.toFixed(1)} ha</b></span>
                <span>Sorties <b className="num">{selSort}</b></span>
                <span>Est. flight time <b className="num">{Math.floor(flightMin / 60)}h {String(flightMin % 60).padStart(2, "0")}m</b></span>
                <span>Flight days <b className="num">{Math.ceil(selSort / 8)}</b></span>
                <span className="grow"/>
                <button className="btn btn-ghost btn-xs" onClick={() => go("flight")}><Icon name="map"/>Plan flight routes</button>
              </div>
            </div>
          </div>
        </div>

        <aside className="col" style={{ gap: 16 }}>
          {prof && <div className="card">
            <div className="card-hd">Site setup<span className="sub">{site.poly ? "from New site" : "from site record"}</span><div className="actions"><button className="btn btn-ghost btn-xs" onClick={() => go("site")}>Open site</button></div></div>
            <div style={{ padding: "10px 14px", display: "flex", flexDirection: "column", gap: 6 }}>
              {[["Capacity", `${site.capacity_mw} MWp / ${prof.mwac} MWac`], ["Modules", `${(+prof.modules).toLocaleString()} · ${prof.model}`], ["Mounting", `${prof.mount} · ${prof.tilt} · ${prof.azimuth}`],
                ["Inverters · strings", `${prof.inverters} · ${(+prof.strings).toLocaleString()}`], ["Location", `${prof.lat}, ${prof.lng} · ${prof.crs.split(" · ")[0]}`], ["Default platform", `${prof.platform} · ${prof.gsd} cm/px`], ["Cadence", prof.cadence], ["Operator", prof.operator]].map(([k, v]) => (
                <div key={k} className="ps-kv"><span>{k}</span><b>{v}</b></div>))}
            </div>
          </div>}
          <div className="card" style={{ border: "1px solid var(--accent-primary)", boxShadow: "0 0 0 1px rgba(74,144,217,0.15)" }}>
            <div className="card-hd" style={{ background: "rgba(74,144,217,0.06)" }}>
              <Icon name="history" size={14} style={{ color: "var(--accent-primary)" }}/>
              Inherited from last cycle
              <label className="row" style={{ marginLeft: "auto", gap: 6, fontSize: 11, cursor: "pointer" }}>
                <input type="checkbox" checked={applyInherited} onChange={e => setApplyInherited(e.target.checked)}/>
                Apply
              </label>
            </div>
            <div style={{ padding: 14 }}>
              <div className="caps" style={{ marginBottom: 6 }}>From {INHERITED.from}</div>

              <div style={{ marginTop: 12 }}>
                <div className="caps" style={{ marginBottom: 6 }}>Thresholds — delta vs. previous</div>
                <table className="tbl" style={{ fontSize: 11 }}>
                  <tbody>
                    {INHERITED.thresholds.map(t => (
                      <tr key={t.key} style={{ cursor: "default" }}>
                        <td style={{ height: 32 }}>{t.key}</td>
                        <td className="r mono sec" style={{ height: 32 }}>{t.last}</td>
                        <td className="r mono" style={{ height: 32, color: "var(--fg-primary)", fontWeight: 500 }}>{t.now}</td>
                        <td className="r mono" style={{ height: 32, color: t.delta.startsWith("+") ? "var(--health-ok)" : "var(--sev-high)" }}>{t.delta}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div style={{ marginTop: 16 }}>
                <div className="caps" style={{ marginBottom: 6 }}>Priority zones</div>
                {INHERITED.priorityZones.map(z => (
                  <div key={z.name} style={{ display: "flex", gap: 10, padding: "8px 0", borderTop: "1px solid var(--border-base)" }}>
                    <Icon name="pin" size={13} style={{ color: "var(--accent-mission)", marginTop: 2 }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 500 }}>{z.name}</div>
                      <div className="sec" style={{ fontSize: 11 }}>{z.note}</div>
                    </div>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 14, paddingTop: 12, borderTop: "1px solid var(--border-base)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <div>
                  <div className="caps">Defects to re-verify</div>
                  <div className="num" style={{ fontSize: 22, fontWeight: 700 }}>{INHERITED.toReverify}</div>
                </div>
                <div>
                  <div className="caps">Carried over</div>
                  <div className="num" style={{ fontSize: 22, fontWeight: 700, color: "var(--fg-secondary)" }}>{INHERITED.defectsCarriedOver}</div>
                </div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-hd">Version history</div>
            <div style={{ padding: 10 }}>
              {[
                ["v3","draft", "You · 14s ago", "Tightened hot-cell ΔT to 18.0 °C"],
                ["v2","archived", "T. Aragón · 2h ago", "Adjusted tracker instruction to auto"],
                ["v1","archived", "M. Rivera · yesterday", "Initial draft from baseline"],
              ].map(([v,st,who,note]) => (
                <div key={v} style={{ display: "flex", gap: 10, padding: "8px 10px", borderBottom: "1px solid var(--border-base)" }}>
                  <span className="mono" style={{ fontSize: 11, fontWeight: 600, minWidth: 22 }}>{v}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11 }}>{note}</div>
                    <div className="sec" style={{ fontSize: 10 }}>{who}</div>
                  </div>
                  <Pill tone={st === "draft" ? "warn" : ""}><span className="dot"/>{st}</Pill>
                </div>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* Simple AOI map — placeholder with polygon + gap hatching */
function AOIMap() {
  return (
    <div style={{ height: 260, background: "var(--bg-inset)", position: "relative", overflow: "hidden" }}>
      {/* Terrain-ish placeholder */}
      <svg width="100%" height="100%" viewBox="0 0 800 260" preserveAspectRatio="none">
        <defs>
          <pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="#ef4444" strokeWidth="1.2" opacity="0.6"/>
          </pattern>
          <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#1e293b" strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="800" height="260" fill="url(#grid)"/>
        <path d="M 80 60 L 720 90 L 700 210 L 90 200 Z" fill="rgba(74,144,217,0.1)" stroke="#4a90d9" strokeWidth="1.5" strokeDasharray="6 4"/>
        <rect x="120" y="90" width="210" height="30" fill="rgba(212,145,12,0.12)" stroke="#d4910c" strokeWidth="1"/>
        <text x="125" y="85" fontSize="10" fill="#d4910c" fontFamily="var(--font-mono)">ZONE A · Inverters 3,7</text>
        <rect x="380" y="130" width="140" height="40" fill="rgba(212,145,12,0.12)" stroke="#d4910c" strokeWidth="1"/>
        <text x="385" y="125" fontSize="10" fill="#d4910c" fontFamily="var(--font-mono)">ZONE B · Comb 4.2</text>
        <rect x="560" y="100" width="120" height="50" fill="url(#hatch)" stroke="#ef4444" strokeWidth="1" strokeDasharray="4 2"/>
        <text x="565" y="95" fontSize="10" fill="#ef4444" fontFamily="var(--font-mono)">GAP · re-fly</text>
        <circle cx="200" cy="130" r="4" fill="#d4910c"/>
        <circle cx="500" cy="160" r="4" fill="#d4910c"/>
      </svg>
      <div style={{ position: "absolute", top: 10, left: 10, fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--fg-muted)", background: "rgba(15,23,42,0.85)", padding: "3px 8px", borderRadius: 4 }}>
        AOI · EPSG:25829
      </div>
    </div>
  );
}

function PlanZoneMap({ prof, sel, toggle }) {
  const [x0, y0, x1, y1] = [Math.min(...prof.poly.map(q => q[0])), Math.min(...prof.poly.map(q => q[1])), Math.max(...prof.poly.map(q => q[0])), Math.max(...prof.poly.map(q => q[1]))];
  const vb = [x0 - 30, y0 - 30, x1 - x0 + 60, y1 - y0 + 60];
  const pts = prof.poly.map(p => p.join(",")).join(" ");
  return (
    <svg viewBox={vb.join(" ")} preserveAspectRatio="xMidYMid meet" className="pz-map">
      <defs><clipPath id="pz-clip"><polygon points={pts}/></clipPath>
        <pattern id="pz-h" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="7" stroke="#ef4444" strokeWidth="1.3" opacity=".8"/></pattern></defs>
      <rect x={vb[0]} y={vb[1]} width={vb[2]} height={vb[3]} fill="#262b20"/>
      <g clipPath="url(#pz-clip)">{Array.from({ length: 40 }).map((_, i) => <rect key={i} x={x0} y={y0 + i * 11} width={x1 - x0} height="6" fill="#1c2f48" opacity=".85"/>)}</g>
      <g clipPath="url(#pz-clip)">{prof.zones.map(z => <rect key={z.id} x={z.x} y={z.y} width={z.w} height={z.h} onClick={() => toggle(z.id)} style={{ cursor: "pointer" }}
        fill={sel.has(z.id) ? `hsla(${z.hue},70%,55%,.3)` : "rgba(10,14,26,.55)"} stroke={`hsl(${z.hue},70%,62%)`} strokeWidth={sel.has(z.id) ? 2 : 1} strokeDasharray={sel.has(z.id) ? undefined : "5 3"}/>)}</g>
      <polygon points={pts} fill="none" stroke="#60a5fa" strokeWidth="2" pointerEvents="none"/>
      {prof.excl && prof.excl.length >= 3 && <polygon points={prof.excl.map(p => p.join(",")).join(" ")} fill="url(#pz-h)" stroke="#ef4444" strokeWidth="1.2" pointerEvents="none"/>}
      {prof.zones.map(z => <text key={z.id} x={z.cx} y={z.cy + 5} textAnchor="middle" fontSize="14" fontWeight="700" fill={sel.has(z.id) ? "#f8fafc" : "#64748b"} fontFamily="var(--font-mono)" pointerEvents="none" style={{ paintOrder: "stroke", stroke: "#0a0f1a", strokeWidth: 3 }}>{z.id}</text>)}
    </svg>
  );
}

window.PlannerPage = PlannerPage;
