/* SkyOps — InspectionWorkspace
   The single page that owns the entire inspection lifecycle.
   Header (site + inspection context) → Stepper (8 stages) → Active stage slot.
   Stages are registered as components that receive { mic, site, go }. */

const { useState: useStateWS, useEffect: useEffectWS, useMemo: useMemoWS } = React;

/* ── Stage definitions ──────────────────────────────────────────
   Each stage has: key, label, short, icon, progress key (from mic.progress),
   gate (fn returning whether unlocked), and an optional description. */
const WORKSPACE_STAGES = [
  { key: "plan",     label: "Plan",     short: "1", icon: "crosshair",   progKey: "scheduled" },
  { key: "fly",      label: "Fly",      short: "2", icon: "drone",       progKey: "flying" },
  { key: "capture",  label: "Capture",  short: "3", icon: "upload",      progKey: "flying",   isCapture: true },
  { key: "process",  label: "Process",  short: "4", icon: "cpu",         progKey: "processing" },
  { key: "review",   label: "Review",   short: "5", icon: "eye",         progKey: "review" },
  { key: "files",    label: "Files",    short: "6", icon: "folder",      progKey: "files",    isFiles: true },
  { key: "report",   label: "Report",   short: "7", icon: "file",        progKey: "reported" },
  { key: "archive",  label: "Archive",  short: "8", icon: "check_circle",progKey: "closed" },
];

/* What counts as "unlocked" for each stage given mic progress. */
function stageUnlocked(stage, mic) {
  if (!mic) return false;
  const p = mic.progress || {};
  switch (stage.key) {
    case "plan":    return true;
    case "fly":     return (p.scheduled  ?? 0) >= 1;
    case "capture": return (p.flying     ?? 0) > 0;
    case "process": return (p.flying     ?? 0) >= 0.5 || (p.processing ?? 0) > 0;
    case "review":  return (p.processing ?? 0) >= 0.3;
    case "files":   return (p.processing ?? 0) >= 0.3;
    case "report":  return (p.processing ?? 0) >= 0.3 || (p.review ?? 0) >= 1;
    case "archive": return (p.reported   ?? 0) >= 1;
    default:        return false;
  }
}

function stageProgress(stage, mic) {
  if (!mic) return 0;
  const p = mic.progress || {};
  if (stage.isCapture) {
    // capture reads flying as well
    return Math.min(1, (p.flying ?? 0));
  }
  if (stage.isFiles) {
    // files exists once processing completes
    return (p.processing ?? 0) >= 1 ? (p.closed ?? (p.reported ?? (p.review ?? 1))) : 0;
  }
  return p[stage.progKey] ?? 0;
}

/* ── Workspace shell ───────────────────────────────────────────── */
function InspectionWorkspace({ activeSite, activeMic, stage, setStage, setActiveMic, setActiveSite, go, openCompare }) {
  const site = (window.SITES || []).find(s => s.id === activeSite);
  const siteInsps = useMemoWS(() =>
    (window.INSPECTIONS || [])
      .filter(i => i.siteId === activeSite)
      .sort((a,b) => (b.startedAt || b.plannedFor || "").localeCompare(a.startedAt || a.plannedFor || "")),
    [activeSite]);
  const mic = siteInsps.find(i => i.id === activeMic) || siteInsps[0];

  const [picker, setPicker] = useStateWS(false);
  useEffectWS(() => {
    const h = (e) => setStage(e.detail);
    window.addEventListener("skyops:stage", h);
    return () => window.removeEventListener("skyops:stage", h);
  }, [setStage]);

  if (!mic || !site) {
    return (
      <div className="page">
        <div className="card" style={{ padding: 60, textAlign: "center", color: "var(--fg-muted)" }}>
          No inspection found. <a href="#" onClick={(e) => { e.preventDefault(); go("portfolio"); }} style={{ color: "var(--accent-primary)" }}>Back to portfolio</a>.
        </div>
      </div>
    );
  }

  const stageObj = WORKSPACE_STAGES.find(s => s.key === stage) || WORKSPACE_STAGES[0];
  const curIdx = WORKSPACE_STAGES.findIndex(s => s.key === stageObj.key);

  return (
    <div className="ws">
      <WorkspaceHeader
        site={site}
        mic={mic}
        siteInsps={siteInsps}
        picker={picker} setPicker={setPicker}
        setActiveMic={setActiveMic}
        setActiveSite={setActiveSite}
        go={go}
        openCompare={openCompare}
      />
      <WorkspaceStepper
        stages={WORKSPACE_STAGES}
        curIdx={curIdx}
        mic={mic}
        setStage={setStage}
      />
      <div className="ws-body">
        <WorkspaceStageSlot stage={stageObj} mic={mic} site={site} go={go} setStage={setStage} openCompare={openCompare}/>
      </div>
    </div>
  );
}

/* ── Header ────────────────────────────────────────────────────── */
function WorkspaceHeader({ site, mic, siteInsps, picker, setPicker, setActiveMic, setActiveSite, go, openCompare }) {
  const statusColor = {
    draft: "--fg-muted", scheduled: "--accent-primary", flying: "--sev-med",
    processing: "--accent-primary", review: "--sev-med",
    reported: "--sev-low", closed: "--fg-muted",
  }[mic.status] || "--fg-muted";

  return (
    <div className="ws-head">
      <div className="ws-head-left">
        <button className="ws-crumb" onClick={() => go("portfolio")}>Portfolio</button>
        <span className="ws-crumb-sep">/</span>
        <button className="ws-crumb" onClick={() => { setActiveSite(site.id); go("site"); }}>{site.name}</button>
        <span className="ws-crumb-sep">/</span>
        <span className="ws-crumb-cur">Inspection</span>
      </div>

      <div className="ws-head-main">
        <div className="ws-head-title">
          <div className="ws-head-kicker">
            <span className={`mic-rail-status mic-rail-status-${mic.status}`}>
              <span className="mic-rail-dot" style={{ background: `var(${statusColor})` }}/>
              {mic.status}
            </span>
            <span className="mono ws-head-mic">{mic.id}</span>
            <span className="ws-head-cycle">· {mic.cycle}</span>
            <button className="ws-head-picker-btn" onClick={() => setPicker(v => !v)}>
              <Icon name="chevron_down" size={11}/> switch
            </button>
          </div>
          <h1 className="ws-head-h1">
            {mic.cycle} inspection · <span className="ws-head-site-name">{site.name}</span>
          </h1>
          <div className="ws-head-sub">
            {mic.startedAt ? `Started ${mic.startedAt}` : `Planned for ${mic.plannedFor || "—"}`}
            {" · "}
            {mic.lead} · {mic.drone}
            {mic.baseline && <> · baseline <span className="mono">{mic.baseline}</span></>}
          </div>
        </div>

        <div className="ws-head-actions">
          <div className="ws-head-meta">
            <div className="ws-head-meta-it">
              <span className="caps">Coverage</span>
              <span className="mono num">{mic.coverage ? `${mic.coverage}%` : "—"}</span>
            </div>
            <div className="ws-head-meta-it">
              <span className="caps">Detections</span>
              <span className="mono num">{mic.detections || 0}</span>
            </div>
            <div className="ws-head-meta-it">
              <span className="caps">Critical</span>
              <span className="mono num" style={{ color: mic.critical > 0 ? "var(--sev-critical)" : undefined }}>{mic.critical || 0}</span>
            </div>
            <div className="ws-head-meta-it">
              <span className="caps">Area</span>
              <span className="mono num">{mic.area_ha ? `${mic.area_ha} ha` : "—"}</span>
            </div>
          </div>
          <button className="btn btn-secondary btn-xs" onClick={() => { setActiveSite(site.id); go("site"); }}>
            <Icon name="layers" size={11}/> Open site
          </button>
        </div>
      </div>

      {picker && (
        <div className="ws-head-picker-menu" onMouseLeave={() => setPicker(false)}>
          <div className="ws-head-picker-hd">Inspection history · {site.name}</div>
          {siteInsps.map(i => (
            <button key={i.id}
                    className={`ws-head-picker-it ${i.id === mic.id ? "is-on" : ""}`}
                    onClick={() => { setActiveMic(i.id); setPicker(false); }}>
              <span className={`mic-rail-status mic-rail-status-${i.status}`}>
                <span className="mic-rail-dot"/>
                {i.status}
              </span>
              <span className="mono ws-head-picker-mic">{i.id}</span>
              <span className="ws-head-picker-cycle">{i.cycle}</span>
              <span className="ws-head-picker-date mono">{i.startedAt || i.plannedFor}</span>
              <span className="ws-head-picker-meta">{i.detections > 0 ? `${i.detections} det` : "—"}</span>
              {openCompare && i.id !== mic.id && (
                <span className="ws-head-picker-cmp"
                      onClick={(e) => { e.stopPropagation(); setPicker(false); openCompare(i.id, mic.id); }}>
                  vs current
                </span>
              )}
            </button>
          ))}
          <button className="ws-head-picker-new" onClick={() => { setPicker(false); window.dispatchEvent(new CustomEvent("skyops:new-insp",{detail:{siteId: site.id}})); }}>
            <Icon name="plus" size={11}/> New inspection cycle
          </button>
        </div>
      )}
    </div>
  );
}

/* ── Stepper ───────────────────────────────────────────────────── */
function WorkspaceStepper({ stages, curIdx, mic, setStage }) {
  return (
    <div className="ws-stepper" role="tablist" aria-label="Inspection stages">
      {stages.map((s, i) => {
        const p = stageProgress(s, mic);
        const unlocked = stageUnlocked(s, mic);
        const done = p >= 1;
        const active = i === curIdx;
        const cls = [
          "ws-step",
          active ? "is-cur" : "",
          done ? "is-done" : "",
          !unlocked ? "is-locked" : "",
          p > 0 && p < 1 ? "is-part" : "",
        ].join(" ");
        return (
          <React.Fragment key={s.key}>
            {i > 0 && <span className={`ws-step-link ${p > 0 ? "is-on" : ""} ${done ? "is-done" : ""}`}/>}
            <button className={cls}
                    disabled={!unlocked}
                    onClick={() => unlocked && setStage(s.key)}
                    role="tab"
                    aria-selected={active}>
              <span className="ws-step-num">{done ? <Icon name="check" size={10}/> : !unlocked ? <Icon name="lock" size={10}/> : s.short}</span>
              <span className="ws-step-ic"><Icon name={s.icon} size={13}/></span>
              <span className="ws-step-lbl">{s.label}</span>
              {p > 0 && p < 1 && (
                <span className="ws-step-bar"><span style={{ width: `${p*100}%` }}/></span>
              )}
            </button>
          </React.Fragment>
        );
      })}
    </div>
  );
}

/* ── Stage slot — dispatches to the right stage component ───── */
function WorkspaceStageSlot({ stage, mic, site, go, setStage, openCompare }) {
  // Map stages to existing pages where possible; show gate when locked
  const unlocked = stageUnlocked(stage, mic);
  if (!unlocked) {
    return <StageLockedGate stage={stage} mic={mic} setStage={setStage}/>;
  }

  const bar = ["process", "review", "report", "archive"].includes(stage.key) ? <StageAdvanceBar stage={stage} mic={mic} setStage={setStage}/> : null;
  const body = WorkspaceStageBody({ stage, mic, site, go, setStage, openCompare });
  return bar ? <>{bar}{body}</> : body;
}

function WorkspaceStageBody({ stage, mic, site, go, setStage, openCompare }) {
  switch (stage.key) {
    case "plan":    return <window.PlannerPage go={go} mic={mic} site={site} embedded={true} setStage={setStage}/>;
    case "fly":     return <window.FlightPlannerPage go={go} mic={mic} site={site} embedded={true} setStage={setStage}/>;
    case "capture": return <StageCapture mic={mic} site={site} setStage={setStage}/>;
    case "process": return <window.ProcessingPage go={go} mic={mic} site={site} embedded={true}/>;
    case "review":  return <><PartialBanner mic={mic} what="detections from zones processed so far"/><window.ReviewPage go={go} mic={mic} site={site} embedded={true}/></>;
    case "files":   return <><PartialBanner mic={mic} what="artefacts produced so far; the rest appear as stages finish"/><window.StageFiles mic={mic} site={site} setStage={setStage}/></>;
    case "report":  return <window.InspectionReport go={go} mic={mic} site={site}/>;
    case "archive": return <StageArchive mic={mic} site={site} openCompare={openCompare} setStage={setStage}/>;
    default:        return null;
  }
}

function PartialBanner({ mic, what }) {
  const p = mic.progress?.processing ?? 0;
  if (p >= 1) return null;
  return (
    <div className="ws-partial">
      <span className="ws-partial-bar"><span style={{ width: p * 100 + "%" }}/></span>
      <span><b>Processing {Math.round(p * 100)}%</b> · showing {what}.</span>
    </div>
  );
}

/* Forward action for stages after capture — keeps the lifecycle moving */
function micAdvance(mic, patch, status) {
  mic.progress = { ...(mic.progress || {}), ...patch }; if (status) mic.status = status;
  window.saveMicState && window.saveMicState(mic);
}
window.micAdvance = micAdvance;
function StageAdvanceBar({ stage, mic, setStage }) {
  window.__activeMic = mic;
  const [, force] = React.useState(0);
  const [run, setRun] = React.useState(false);
  const p = mic.progress || {};
  React.useEffect(() => {
    if (!run) return;
    const t = setInterval(() => {
      const v = Math.min(1, (mic.progress.processing || 0) + 0.08);
      micAdvance(mic, { processing: +v.toFixed(2) }, v >= 1 ? "review" : "processing");
      if (v >= 1 && !mic.detections) {
        const ha = mic.area_ha || 100; mic.detections = Math.round(ha * 2.9); mic.critical = Math.max(1, Math.round(mic.detections * 0.025));
        mic.coverage = 97.6; mic.gsd = mic.gsd || 1.3; window.saveMicState && window.saveMicState(mic);
      }
      force(x => x + 1);
      if (v >= 1) { setRun(false); clearInterval(t); }
    }, 350);
    return () => clearInterval(t);
  }, [run]);
  const cfg = {
    process: (p.processing || 0) >= 1
      ? ["Pipeline complete · detections ready", "Go to review", () => setStage("review"), true]
      : run ? [`Processing · ${Math.round((p.processing || 0) * 100)}%`, null, null, false, p.processing || 0]
      : [(p.processing || 0) > 0 ? `Pipeline at ${Math.round(p.processing * 100)}%` : "Upload received · pipeline not started", (p.processing || 0) > 0 ? "Resume pipeline" : "Start pipeline", () => setRun(true), false, p.processing || 0],
    review: (p.review || 0) >= 1 ? ["Review signed off", "Go to report", () => setStage("report"), true]
      : ["Validate AI detections, then sign off", "Complete review", () => { micAdvance(mic, { review: 1 }, "reported"); force(x => x + 1); setStage("report"); }, false],
    report: mic.delivery ? ["Report delivered to client", "Go to archive", () => setStage("archive"), true]
      : ["Report draft generated from reviewed detections", "Deliver report", () => window.dispatchEvent(new CustomEvent("skyops:deliver")), false],
    archive: (p.closed || 0) >= 1 ? ["Inspection closed and archived", null, null, true]
      : ["Close the inspection — it becomes the baseline for the next cycle", "Close & archive", () => { micAdvance(mic, { closed: 1 }, "closed"); force(x => x + 1); }, false],
  }[stage.key];
  const [txt, btn, fn, done, prog] = cfg;
  return (
    <div className={`ws-adv ${done ? "is-done" : ""}`}>
      <Icon name={done ? "check_circle" : run ? "cpu" : "arrow_right"} size={13}/>
      <span>{txt}</span>
      {prog != null && !done && <span className="ws-adv-bar"><i style={{ width: prog * 100 + "%" }}/></span>}
      <span style={{ flex: 1 }}/>
      {btn && <button className="btn btn-primary btn-xs" onClick={fn}>{btn}<Icon name="arrow_right" size={11}/></button>}
    </div>
  );
}

/* Locked gate — explains what is needed */
function StageLockedGate({ stage, mic, setStage }) {
  const prev = WORKSPACE_STAGES[WORKSPACE_STAGES.findIndex(s => s.key === stage.key) - 1];
  return (
    <div className="ws-gate">
      <div className="ws-gate-ic"><Icon name="lock" size={20}/></div>
      <h3>{stage.label} is locked</h3>
      <p>This stage unlocks once <b>{prev ? prev.label : "the previous stage"}</b> is complete.{prev && prev.key === "plan" && <> In Plan, select the zones and press <b>Commit & brief pilot</b>.</>}</p>
      {prev && (
        <button className="btn btn-secondary btn-md" onClick={() => setStage(prev.key)}>
          <Icon name="arrow_right" size={12} style={{ transform: "rotate(180deg)" }}/>
          Go back to {prev.label}
        </button>
      )}
    </div>
  );
}

/* ── Capture stage — upload hub ─────────────────────────────── */
function StageCapture({ mic, site, setStage }) {
  const uploaded = mic.images || 0;
  const total = uploaded > 0 ? uploaded : 8729;
  const bytes = mic.bytes || 0;
  const gb = (bytes / 1e9).toFixed(1);
  const [up, setUp] = React.useState(false);
  const [, forceC] = React.useState(0);
  React.useEffect(() => {
    if (!up) return;
    const t = setInterval(() => {
      const v = Math.min(1, (mic.progress?.flying || 0) + 0.1);
      micAdvance(mic, { flying: +v.toFixed(2) }, v >= 1 ? "processing" : "flying");
      if (!mic.images && v >= 1) { mic.images = (mic.flights || 8) * 610; mic.bytes = mic.images * 26e6; window.saveMicState && window.saveMicState(mic); }
      forceC(x => x + 1);
      if (v >= 1) { setUp(false); clearInterval(t); }
    }, 300);
    return () => clearInterval(t);
  }, [up]);
  const captureDone = (mic.progress?.flying ?? 0) >= 1;

  return (
    <div className="ws-stage ws-stage-capture">
      <div className="ws-stage-hd">
        <div className="title">
          <div className="kicker">Stage 3 · Capture</div>
          <h1>Upload flight data</h1>
          <div className="sub">Ingests raw RGB + thermal frames, GNSS log, flight tracks. Kicks off pipeline on stage exit.</div>
        </div>
        <div className="actions">
          <button className="btn btn-secondary"><Icon name="radio" size={12}/>Connect DJI FlightHub</button>
          {captureDone && (
            <button className="btn btn-primary" onClick={() => setStage("process")}>
              <Icon name="arrow_right" size={12}/> Move to processing
            </button>
          )}
        </div>
      </div>

      <div className="cap-grid">
        <div className="cap-main">
          <div className={`cap-drop ${captureDone ? "is-done" : ""}`}>
            <div className="cap-drop-ic">
              <Icon name={captureDone ? "check_circle" : "upload"} size={28}/>
            </div>
            <div className="cap-drop-h">
              {captureDone ? "Capture complete" : "Drop flight folders here, or browse"}
            </div>
            <div className="cap-drop-sub">
              {captureDone
                ? `${total.toLocaleString()} frames · ${gb} GB · ready for pipeline`
                : "Accepts .JPG · .DNG · .R-JPEG · .tiff · .srt · DJI folders"}
            </div>
            {!captureDone && (
              <div className="cap-drop-actions">
                <button className="btn btn-primary" onClick={() => setUp(true)}><Icon name="upload" size={12}/>{up ? `Uploading · ${Math.round((mic.progress?.flying || 0) * 100)}%` : "Browse files"}</button>
                <button className="btn btn-secondary"><Icon name="folder" size={12}/>Browse folders</button>
              </div>
            )}
          </div>

          <div className="card ws-card">
            <div className="card-hd">Sorties uploaded<span className="sub">{mic.flights || 14} / {mic.flights || 14}</span></div>
            <div className="cap-sorties">
              {Array.from({ length: mic.flights || 14 }).map((_, i) => (
                <div key={i} className={`cap-sortie ${i < (mic.flights || 14) ? "is-done" : ""}`}>
                  <span className="cap-sortie-n mono">S{String(i+1).padStart(2,"0")}</span>
                  <span className="cap-sortie-ic"><Icon name="check" size={10}/></span>
                  <span className="cap-sortie-lbl">{i < 7 ? "RGB" : "LWIR"}</span>
                  <span className="cap-sortie-frames mono">{(580 + (i*47) % 240)} fr</span>
                  <span className="cap-sortie-dur mono">{17 + (i*3)%6}m</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <aside className="cap-side">
          <div className="card ws-card">
            <div className="card-hd">Capture summary</div>
            <div className="cap-summary">
              <div className="cap-summary-it"><span className="caps">Frames</span><span className="mono num">{total.toLocaleString()}</span></div>
              <div className="cap-summary-it"><span className="caps">Size</span><span className="mono num">{gb} GB</span></div>
              <div className="cap-summary-it"><span className="caps">Sorties</span><span className="mono num">{mic.flights || 14}</span></div>
              <div className="cap-summary-it"><span className="caps">GSD (avg)</span><span className="mono num">{mic.gsd ? `${mic.gsd} cm/px` : "—"}</span></div>
              <div className="cap-summary-it"><span className="caps">Area flown</span><span className="mono num">{mic.area_ha ? `${mic.area_ha} ha` : "—"}</span></div>
              <div className="cap-summary-it"><span className="caps">Transfer rate</span><span className="mono num">412 MB/s</span></div>
            </div>
          </div>

          <div className="card ws-card">
            <div className="card-hd">Pre-flight QA</div>
            <div className="cap-qa">
              {[
                ["GNSS log integrity", true, "14/14 tracks valid"],
                ["Thermal calibration present", true, "flat-field · 15.2 °C"],
                ["Image EXIF complete", true, `${total.toLocaleString()}/${total.toLocaleString()}`],
                ["Overlap ≥ 75%", true, "avg 82%"],
                ["Coverage gaps", false, "7.6% of AOI · sortie 11"],
              ].map(([l, ok, sub]) => (
                <div key={l} className={`cap-qa-it ${ok ? "ok" : "warn"}`}>
                  <Icon name={ok ? "check_circle" : "alert"} size={13}/>
                  <div>
                    <div className="cap-qa-l">{l}</div>
                    <div className="cap-qa-s mono">{sub}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ── Archive stage — close-out summary ─────────────────────── */
function StageArchive({ mic, site, openCompare, setStage }) {
  const [, fA] = React.useState(0);
  const d = mic.delivery;
  const closed = mic.status === "closed";
  const archive = () => { window.micAdvance(mic, { closed: 1 }, "closed"); mic.archivedAt = window.SKY_TODAY; window.saveMicState && window.saveMicState(mic); window.skyToast && window.skyToast(`${mic.id} archived · baseline set for next cycle`); fA(x => x + 1); };
  const nextDate = window.skyAdd ? window.skyAdd(90, mic.startedAt || window.SKY_TODAY) : "2026-07-10";
  return (
    <div className="ws-stage ws-stage-archive">
      <div className="ws-stage-hd">
        <div className="title">
          <div className="kicker">Stage 8 · Archive</div>
          <h1>Close the loop</h1>
          <div className="sub">Freeze artefacts, seed the next cycle, hand off to long-term storage.</div>
        </div>
      </div>

      <div className="arch-grid">
        <div className="card ws-card arch-close">
          <div className="card-hd">Close-out</div>
          <div className="arch-steps">
            {[
              ["Report delivered to client", !!d, d ? `v${d.version} · ${d.at} · ${d.to.length} recipients` : "not delivered — go to Report"],
              ["Artefacts frozen in cold storage", true, `${((mic.bytes||0)/1e9).toFixed(0)} GB · 12 objects`],
              ["Baseline registered for next cycle", closed, closed ? `${mic.id} is the baseline` : "on archive"],
              ["Thresholds propagated", closed, closed ? "Hot-cell ΔT = 18.0 °C" : "on archive"],
              ["Detections promoted to intel", true, `${mic.detections || 0} observations indexed`],
            ].map(([l, done, sub]) => (
              <div key={l} className={`arch-step ${done ? "is-done" : ""}`}>
                <span className="arch-step-ic"><Icon name={done ? "check_circle" : "clock"} size={14}/></span>
                <div>
                  <div className="arch-step-l">{l}</div>
                  <div className="arch-step-s mono">{sub}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="arch-cta">
            {closed ? <><span className="arch-done"><Icon name="check_circle" size={12}/>Archived {mic.archivedAt || ""}</span><button className="btn btn-primary" onClick={() => window.dispatchEvent(new CustomEvent("skyops:new-insp", { detail: { siteId: mic.siteId, date: nextDate } }))}><Icon name="plus" size={12}/>Schedule next cycle · {nextDate}</button></>
              : <>{!d && <span className="arch-warn"><Icon name="alert" size={11}/>Report not delivered yet</span>}
                {!d && <button className="btn btn-secondary" onClick={() => setStage("report")}>Go to report</button>}
                <button className="btn btn-primary" onClick={archive}><Icon name="check_circle" size={12}/>{d ? "Archive inspection" : "Archive without delivery"}</button></>}
          </div>
        </div>

        <div className="card ws-card">
          <div className="card-hd">Next cycle</div>
          <div className="arch-next">
            <div className="arch-next-h">Q3 2026</div>
            <div className="arch-next-date mono">{nextDate}</div>
            <div className="arch-next-sub">Quarterly cadence · pilot T. Aragón · M350 RTK</div>
            <div className="arch-next-inherit">
              <div className="caps">Will inherit from this cycle</div>
              <ul>
                <li>Thresholds (hot-cell, soiling, coverage)</li>
                <li>{mic.critical || 0} unresolved critical + all persistent observations</li>
                <li>Priority zones A, B, C</li>
                <li>AOI polygon</li>
              </ul>
            </div>
          </div>
        </div>

        <div className="card ws-card">
          <div className="card-hd">Compare & intel</div>
          <div className="arch-intel">
            <p>Every artefact produced in this cycle is available for comparison with past (or future) cycles.</p>
            <button className="btn btn-secondary btn-md" onClick={() => openCompare && openCompare(mic.baseline || mic.id, mic.id)}>
              <Icon name="arrow_right" size={12}/> Compare with {mic.baseline || "previous cycle"}
            </button>
            <button className="btn btn-secondary btn-md" onClick={() => setStage("files")}>
              <Icon name="folder" size={12}/> Browse all files
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InspectionWorkspace, WORKSPACE_STAGES });
