/* SkyOps — Site › Inspections tab.
   Active & upcoming cycles as cards with the next action; history as a compact table with deltas vs the previous cycle;
   pick two cycles to compare. */

const { useState: useStateIL } = React;

const IL_STAGES = [["plan", "Plan"], ["fly", "Fly"], ["capture", "Capture"], ["process", "Process"], ["review", "Review"], ["report", "Report"]];
const IL_AT = { draft: 0, scheduled: 0, flying: 1, capture: 2, processing: 3, review: 4, reported: 5, closed: 6, archived: 6 };
const IL_NEXT = { draft: ["Finish plan", "plan"], scheduled: ["Open flight plan", "plan"], flying: ["Monitor flight", "fly"], capture: ["Upload capture", "capture"], processing: ["View processing", "process"], review: ["Continue review", "review"], reported: ["Finalise report", "report"] };
const IL_ST = { draft: "Draft", scheduled: "Scheduled", flying: "Flying", capture: "Capture", processing: "Processing", review: "In review", reported: "Report draft", closed: "Closed", archived: "Archived" };

function InspectionsList({ siteId, go, setActiveMic, openCompare }) {
  const all = (window.INSPECTIONS || []).filter(i => i.siteId === siteId)
    .sort((a, b) => (b.startedAt || b.plannedFor || "").localeCompare(a.startedAt || a.plannedFor || ""));
  const [sel, setSel] = useStateIL([]);
  const active = all.filter(i => !["closed", "archived"].includes(i.status));
  const hist = all.filter(i => ["closed", "archived"].includes(i.status));
  const open = (mic, stage) => { setActiveMic && setActiveMic(mic.id); try { localStorage.setItem("skyops_ws_stage", stage || "plan"); } catch {} go("workspace"); };
  const toggle = (id) => setSel(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id].slice(-2));
  const done = all.filter(i => i.detections > 0);
  const avgCov = done.length ? done.reduce((a, i) => a + (i.coverage || 0), 0) / done.length : 0;
  const maxDet = Math.max(1, ...done.map(i => i.detections));
  const site = (window.SITES || []).find(s => s.id === siteId);

  return (
    <div className="il">
      <div className="il-sum">
        <div><span className="il-l">Cycles on record</span><b className="mono">{all.length}</b></div>
        <div><span className="il-l">Cadence</span><b>Quarterly</b></div>
        <div><span className="il-l">Average coverage</span><b className="mono">{avgCov.toFixed(1)}%</b></div>
        <div className="il-trend"><span className="il-l">Detections per cycle</span>
          <div className="il-spark">{[...done].reverse().map(i => <i key={i.id} title={`${i.cycle} · ${i.detections.toLocaleString("en-US")}`} style={{ height: Math.max(8, i.detections / maxDet * 100) + "%" }}/>)}</div>
        </div>
        <button className="btn btn-primary btn-sm" onClick={() => window.dispatchEvent(new CustomEvent("skyops:new-insp", { detail: { siteId } }))}><Icon name="plus" size={11}/>New inspection</button>
      </div>

      {active.length > 0 && <>
        <div className="il-h">Active & upcoming <span className="il-n">{active.length}</span></div>
        <div className="il-cards">
          {active.map(m => { const at = IL_AT[m.status] ?? 0; const [nl, ns] = IL_NEXT[m.status] || ["Open", "plan"];
            return <div key={m.id} className={`il-card il-st-${m.status}`}>
              <div className="il-card-hd">
                <span className={`mic-rail-status mic-rail-status-${m.status}`}><span className="mic-rail-dot"/>{IL_ST[m.status] || m.status}</span>
                <span className="mono il-date">{m.startedAt || m.plannedFor}</span>
              </div>
              <div className="il-card-id"><b className="mono">{m.id}</b><span>{m.cycle}{m.purpose ? " · " + m.purpose : ""}</span></div>
              <div className="il-steps">{IL_STAGES.map(([k, l], i) => <div key={k} className={i < at ? "done" : i === at ? "cur" : ""}><i/><span>{l}</span></div>)}</div>
              <div className="il-card-meta">
                <span><Icon name="user" size={11}/>{m.lead || "—"}</span>
                <span><Icon name="drone" size={11}/>{m.drone || "—"}</span>
                {m.coverage > 0 && <span className="mono">{m.coverage}% coverage</span>}
                {m.detections > 0 && <span className="mono">{m.detections} detections</span>}
              </div>
              <div className="il-card-ft">
                <button className="btn btn-ghost btn-xs" onClick={() => open(m, "plan")}>Plan</button>
                <span className="grow"/>
                <button className="btn btn-primary btn-xs" onClick={() => open(m, ns)}>{nl}<Icon name="arrow_right" size={10}/></button>
              </div>
            </div>; })}
        </div>
      </>}

      <div className="il-h">History <span className="il-n">{hist.length}</span><span className="grow"/>
        {sel.length > 0 ? <span className="il-cmp"><span className="mono">{sel.length}/2</span>{sel.length === 2 ? "Ready to compare" : "Select one more cycle"}
          <button className="btn btn-ghost btn-xs" onClick={() => setSel([])}>Clear</button>
          <button className="btn btn-primary btn-xs" disabled={sel.length !== 2} onClick={() => openCompare && openCompare(sel[0], sel[1])}>Compare cycles<Icon name="arrow_right" size={10}/></button></span>
          : <span className="sec il-hint">Tick two cycles to compare them</span>}
      </div>
      <div className="il-tbl">
        <div className="il-row il-row-hd"><span/><span>Cycle</span><span>Coverage</span><span>Detections</span><span>Change vs previous</span><span>Lead</span><span/></div>
        {hist.map((m, idx) => { const prev = hist[idx + 1]; const d = prev ? m.detections - prev.detections : null; const on = sel.includes(m.id);
          return <div key={m.id} className={`il-row ${on ? "on" : ""}`} onClick={() => open(m, "report")}>
            <label className="il-ck" onClick={e => e.stopPropagation()}><input type="checkbox" checked={on} onChange={() => toggle(m.id)} aria-label={`Select ${m.id} for compare`}/></label>
            <span className="il-cyc"><b className="mono">{m.id}</b><em>{m.cycle} · {m.startedAt}</em></span>
            <span className="il-cov"><i style={{ width: (m.coverage || 0) + "%" }}/><b className="mono">{m.coverage ? m.coverage + "%" : "—"}</b></span>
            <span className="mono">{m.detections ? m.detections.toLocaleString("en-US") : "—"}{m.critical ? <em className="il-crit">{m.critical} critical</em> : null}</span>
            <span className="mono">{d == null ? <em className="sec">baseline</em> : <em className={d > 0 ? "il-up" : "il-down"}>{d > 0 ? "▲ +" : "▼ "}{d.toLocaleString("en-US")}</em>}</span>
            <span>{m.lead}</span>
            <span className="il-act"><button className="btn btn-ghost btn-xs" onClick={e => { e.stopPropagation(); open(m, "report"); }}><Icon name="file" size={11}/>Report</button><button className="btn btn-secondary btn-xs" onClick={e => { e.stopPropagation(); open(m, "review"); }}>Open<Icon name="arrow_right" size={10}/></button></span>
          </div>; })}
        {hist.length === 0 && <div className="sec" style={{ padding: 16, fontSize: 12 }}>No completed inspections yet. The first cycle becomes the baseline for {site ? site.name : "this site"}.</div>}
      </div>
    </div>
  );
}

window.InspectionsList = InspectionsList;
