/* SkyOps — Inspection report (stage 7) + Reports index
   An inspection covers N zones of the farm; each flown + processed zone has its own zone report.
   Overview → pick a zone → ZoneReport. */

const { useState: useStateIR, useMemo: useMemoIR } = React;
const irEur = (n) => "€" + Math.round(n).toLocaleString("en");

function InspectionReport({ mic, site, go }) {
  const zones = useMemoIR(() => window.zrZonesFor(mic), [mic.id]);
  const [zone, setZone] = useStateIR(() => {
    const z = localStorage.getItem("skyops_zr_zone");
    return z && zones.find(x => x.id === z && x.status === "ready") ? z : "overview";
  });
  const pick = (z) => { setZone(z); try { localStorage.setItem("skyops_zr_zone", z); } catch {} };

  if (zone !== "overview") {
    return <><window.DeliveryBar mic={mic} site={site} zones={zones}/><ZoneReport mic={mic} site={site} zone={zone} zones={zones} onPickZone={pick} onBack={() => pick("overview")} go={go} embedded/></>;
  }
  return <><InspectionReportOverview mic={mic} site={site} zones={zones} onPick={pick} bar={<window.DeliveryBar mic={mic} site={site} zones={zones}/>}/></>;
}

function InspectionReportOverview({ mic, site, zones, onPick, bar }) {
  const ready = zones.filter(z => z.status === "ready");
  const rows = useMemoIR(() => ready.map(z => ({ ...z, c: window.zrGet(mic.id, z.id).counts })), [mic.id]);
  const tot = rows.reduce((a, r) => ({
    modules: a.modules + r.c.total, thermal: a.thermal + r.c.thermal, cls3: a.cls3 + r.c.cls3, cls2: a.cls2 + r.c.cls2,
    cleaning: a.cleaning + r.c.cleaning, loss: a.loss + r.c.lossThermal + r.c.lossSoil,
  }), { modules: 0, thermal: 0, cls3: 0, cls2: 0, cleaning: 0, loss: 0 });
  const maxLoss = Math.max(1, ...rows.map(r => r.c.lossThermal + r.c.lossSoil));
  const worst = [...rows].sort((a, b) => (b.c.cls3 * 10 + b.c.cls2) - (a.c.cls3 * 10 + a.c.cls2))[0];
  const pending = zones.filter(z => z.status !== "ready" && z.status !== "notflown");

  return (
    <div className="ir" data-screen-label="Inspection report">
      <header className="ir-head">
        <div>
          <div className="kicker">Stage 7 · Report · {mic.id}</div>
          <h1>{mic.cycle} inspection report — {site.name}</h1>
          <div className="sub">{ready.length} of {zones.length} zones reported{pending.length ? ` · ${pending.length} still processing` : ""} · pick a zone to see module-level thermal and soiling results</div>
        </div>
        <div className="ir-head-r">
          <button className="btn btn-secondary" onClick={() => { window.skyDownload(`${mic.id}-site-summary.pdf`, window.reportPdf(mic, site, zones)); window.skyToast("Site summary PDF downloaded"); }}><Icon name="download" size={12}/>Site summary PDF</button>
          {worst && <button className="btn btn-primary" onClick={() => onPick(worst.id)}><Icon name="arrow_right" size={12}/>Open worst zone · {worst.id}</button>}
        </div>
      </header>
      {bar}

      <div className="ir-kpis">
        {[["Modules reported", tot.modules.toLocaleString(), `${ready.length} zones`],
          ["Thermal anomalies", tot.thermal, `${tot.cls3} CoA 3 · ${tot.cls2} CoA 2`, tot.cls3 ? "crit" : ""],
          ["Need cleaning", tot.cleaning.toLocaleString(), "modules"],
          ["Est. loss", irEur(tot.loss) + "/yr", "thermal + soiling", "crit"]].map(([k, v, s, t]) => (
          <div key={k} className={`ir-kpi ${t || ""}`}><span className="caps">{k}</span><b className="mono">{v}</b><em>{s}</em></div>
        ))}
      </div>

      <div className="ir-body">
        <div className="ir-map card">
          <div className="ir-card-hd"><span>Farm map · zones in this inspection</span><span className="muted mono">click a zone</span></div>
          <div className="ir-grid">
            {zones.map(z => {
              const r = rows.find(x => x.id === z.id);
              const sev = r ? (r.c.cls3 >= 10 ? 3 : r.c.cls3 >= 5 ? 2 : 1) : 0;
              return (
                <button key={z.id} className={`ir-zone ir-zone-${z.status} ${r ? "sev" + sev : ""}`} disabled={z.status !== "ready"} onClick={() => onPick(z.id)}>
                  <span className="ir-zone-id mono">{z.id}</span>
                  {r ? (
                    <>
                      <span className="ir-zone-n"><b style={{ color: "var(--sev-critical)" }}>{r.c.cls3}</b> CoA3 · <b>{r.c.cleaning}</b> clean</span>
                      <span className="ir-zone-bar"><i style={{ width: `${(r.c.lossThermal + r.c.lossSoil) / maxLoss * 100}%` }}/></span>
                    </>
                  ) : <span className="ir-zone-st">{z.status === "processing" ? "Processing…" : z.status === "queued" ? "Flown · queued" : "Not flown"}</span>}
                </button>
              );
            })}
          </div>
          <div className="ir-lg">
            <span><i className="sev3"/>≥10 CoA 3</span><span><i className="sev2"/>5–9 CoA 3</span><span><i className="sev1"/>&lt;5 CoA 3</span><span><i className="proc"/>Processing</span><span><i className="nf"/>Not flown</span>
          </div>
        </div>

        <div className="ir-list card">
          <div className="ir-card-hd"><span>Zone reports</span><span className="muted mono">{ready.length} ready</span></div>
          <table className="tbl">
            <thead><tr><th>Zone</th><th>Flown</th><th className="r">CoA 3</th><th className="r">CoA 2</th><th className="r">Clean</th><th className="r">Loss/yr</th><th/></tr></thead>
            <tbody>
              {[...rows].sort((a, b) => b.c.cls3 - a.c.cls3 || b.c.cls2 - a.c.cls2).map(r => (
                <tr key={r.id} onClick={() => onPick(r.id)}>
                  <td className="mono"><b>{r.id}</b></td>
                  <td className="mono sec">{r.date}</td>
                  <td className="r mono num" style={{ color: r.c.cls3 ? "var(--sev-critical)" : undefined }}>{r.c.cls3}</td>
                  <td className="r mono num" style={{ color: "var(--sev-high)" }}>{r.c.cls2}</td>
                  <td className="r mono num">{r.c.cleaning}</td>
                  <td className="r mono num">{irEur(r.c.lossThermal + r.c.lossSoil)}</td>
                  <td className="r"><Icon name="arrow_right" size={12} style={{ color: "var(--fg-muted)" }}/></td>
                </tr>
              ))}
              {pending.map(z => (
                <tr key={z.id} className="ir-pend"><td className="mono">{z.id}</td><td className="mono sec">{z.date || "—"}</td><td colSpan="5" className="muted">{z.status === "processing" ? "Pipeline running — report available when processing completes" : "Flown, waiting in processing queue"}</td></tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* Reports index — every inspection × its zone reports */
function ReportsIndexPage({ go, setActiveSite, setActiveMic, setWsStage }) {
  const all = (window.INSPECTIONS || []).filter(i => i.status !== "draft" && i.status !== "scheduled")
    .sort((a, b) => (b.startedAt || "").localeCompare(a.startedAt || ""));
  const open = (mic, zone) => {
    try { localStorage.setItem("skyops_zr_zone", zone || "overview"); } catch {}
    setActiveSite(mic.siteId); setActiveMic(mic.id); setWsStage("report"); go("workspace");
  };
  return (
    <div className="page">
      <div className="page-head">
        <div className="title">
          <div className="kicker">Operate</div>
          <h1>Reports</h1>
          <div className="sub">Every report belongs to an inspection. Each inspection produces one report per flown zone, plus a site summary.</div>
        </div>
      </div>
      <div className="card">
        <table className="tbl ir-idx">
          <thead><tr><th>Inspection</th><th>Site</th><th>Cycle</th><th>Zone reports</th><th className="r">Ready</th><th/></tr></thead>
          <tbody>
            {all.map(mic => {
              const site = (window.SITES || []).find(s => s.id === mic.siteId);
              const zones = window.zrZonesFor(mic);
              const ready = zones.filter(z => z.status === "ready").length;
              return (
                <tr key={mic.id} onClick={() => open(mic, "overview")}>
                  <td className="mono"><b>{mic.id}</b></td>
                  <td>{site?.name}</td>
                  <td className="sec">{mic.cycle} · {mic.startedAt}</td>
                  <td>
                    <div className="ir-chips">
                      {zones.map(z => (
                        <span key={z.id} className={`ir-chip ir-chip-${z.status}`} title={`${z.id} · ${z.status}`}
                          onClick={(e) => { if (z.status === "ready") { e.stopPropagation(); open(mic, z.id); } }}>{z.id}</span>
                      ))}
                    </div>
                  </td>
                  <td className="r mono num">{ready}/16</td>
                  <td className="r"><Icon name="arrow_right" size={12} style={{ color: "var(--fg-muted)" }}/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { InspectionReport, ReportsIndexPage });
