// OPT-QC-02 · QC entry — start
const QcEntryStart = ({ t, go }) => {
  const { Btn, Pill, Stepper, Banner, SRow } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.entry; // default | noMatrix | mismatch | loading
  const E = QD.EVENT;
  const loading = state === "loading";
  const m = QD.matrixFor(E.variety, E.stage);
  const [stage, setStage] = useState(E.stage);
  const [bins, setBins] = useState(E.bins);
  const [checks, setChecks] = useState(() => E.checklist.map(c => ({ ...c })));
  const setRow = (i, patch) => setChecks(cs => cs.map((c, j) => (j === i ? { ...c, ...patch } : c)));
  const unmatured = checks.some(c => c.point === "Fruits Status" && /unmatured/i.test(c.actual));
  const anyFail = checks.some(c => !c.ok);

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "center", margin: "2px 0 18px" }}>
          <Stepper steps={["Start", "Sampling & parameters", "Decision"]} current={0}/>
        </div>

        {state === "noMatrix" && (
          <div style={{ marginBottom: 16 }}>
            <Banner tone="warning" icon={Ic.Warning} title={`No QC matrix configured for ${E.variety} · ${stage}`}
              desc="Configure a matrix in OPT-QC-12, or request a manager override to proceed with facility defaults. The override is logged.">
              <div style={{ display: "flex", gap: 10, marginTop: 10 }}>
                <Btn variant="outline" size="sm" icon={Ic.Layers} onClick={() => go("matrix")}>Configure matrix</Btn>
                <Btn variant="ghost" size="sm" icon={Ic.HelpCircle}>Override with defaults</Btn>
              </div>
            </Banner>
          </div>
        )}
        {state === "mismatch" && (
          <div style={{ marginBottom: 16 }}>
            <Banner tone="info" icon={Ic.Info} title="Variety differs from the order"
              desc={`Order ${E.po} expected Fuerte; the load is being recorded as Hass. Confirm the captured variety — a soft mismatch is logged but does not block QC.`}/>
          </div>
        )}

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18, alignItems: "start" }}>
          {/* Load context */}
          <div className="op-card flush">
            <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "16px 18px 13px" }}>
              <span className="op-row-thumb" style={{ width: 48, height: 48 }}><Ic.Leaf size={22}/></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 17, fontWeight: 600 }}>{E.who}</span>
                  <Pill tone={E.tier === "A" ? "approved" : E.tier === "new" ? "soil" : "closed"}>{E.tier === "new" ? "New farmer" : "Tier " + E.tier}</Pill>
                </div>
                <div className="op-gpn" style={{ marginTop: 3, color: "var(--muted-foreground)" }}>{E.gpn}</div>
              </div>
              <Pill tone="avocado">Inbound</Pill>
            </div>
            {loading
              ? <div style={{ padding: "0 18px 18px" }}>{Array.from({ length: 5 }).map((_, i) => <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "13px 0", borderBottom: "1px solid var(--border)" }}><div className="op-skel" style={{ height: 12, width: 90 }}/><div className="op-skel" style={{ height: 12, width: 120 }}/></div>)}</div>
              : <>
                <SRow k="Source order" v={E.po}/>
                <SRow k="Product variety" v={<>{E.variety}{state === "mismatch" && <Ic.Warning size={13} style={{ color: "var(--warning)", verticalAlign: "-2px", marginLeft: 5 }}/>}</>}/>
                <SRow k="Net weight" v={QD.KG(E.net)}/>
                <SRow k="Origin" v={E.location}/>
                <SRow k="Weighbridge" v={E.weighbridge}/>
                <div className="op-srow"><span className="k"><Ic.Box size={15}/> Bins / units</span>
                  <span className="v" style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <input className="op-input" value={bins} onChange={(e) => setBins(e.target.value.replace(/\D/g, ""))} style={{ width: 70, height: 38, textAlign: "center", fontSize: 14 }}/>
                    <span className="op-muted" style={{ fontSize: 11.5, fontWeight: 500 }}>editable</span>
                  </span>
                </div>
              </>}
          </div>

          {/* Sampling rule + threshold preview + stage */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="op-field" style={{ margin: 0 }}>
              <div className="op-label">QC stage <span className="req">*</span></div>
              <div className="op-tabs" style={{ display: "flex", width: "100%" }}>
                {["Intake", "Production"].map(s => (
                  <button key={s} className={stage === s ? "on" : ""} style={{ flex: 1 }} onClick={() => setStage(s)}>{s}</button>
                ))}
              </div>
            </div>

            <div className="op-card op-card-pad">
              <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 8 }}><Ic.ClipboardList size={17} style={{ color: "var(--avocado-fg)" }}/><div style={{ fontSize: 14.5, fontWeight: 600 }}>Sampling rule</div></div>
              <div style={{ fontSize: 13.5, lineHeight: 1.5 }}>{E.samplingRule}</div>
              <div className="op-muted" style={{ fontSize: 12, marginTop: 6 }}>From the active matrix for {E.variety}. Minimum 3 samples required.</div>
            </div>

            <div className="op-card op-card-pad">
              <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}><Ic.Gauge size={17} style={{ color: "var(--avocado-fg)" }}/><div style={{ fontSize: 14.5, fontWeight: 600 }}>Threshold preview</div></div>
              {state === "noMatrix"
                ? <div className="op-muted" style={{ fontSize: 13 }}>No thresholds — matrix not configured.</div>
                : <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}><span style={{ fontSize: 13, fontWeight: 600 }}><Ic.Thermometer size={13} style={{ verticalAlign: "-2px", marginRight: 5 }}/>Dry Matter</span><span style={{ fontSize: 13, fontVariantNumeric: "tabular-nums" }}>≥ {m.dm.min}% <span className="op-muted">· target {m.dm.target}%</span></span></div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}><span style={{ fontSize: 13, fontWeight: 600 }}><Ic.Drop size={13} style={{ verticalAlign: "-2px", marginRight: 5 }}/>Free Fatty Acid</span><span style={{ fontSize: 13, fontVariantNumeric: "tabular-nums" }}>≤ {m.ffa.accept.toFixed(1)}% <span className="op-muted">· premium ≤ {m.ffa.premium.toFixed(1)}%</span></span></div>
                </div>}
            </div>
          </div>
        </div>

        {/* IMTR — incoming inspection checklist (visual checkpoints; DM is measured in the parameters step) */}
        <div className="op-sec" style={{ marginTop: 22 }}><span className="op-sec-title">Incoming inspection checklist <span className="op-muted" style={{ fontWeight: 500 }}>· IMTR</span></span><span className="op-muted" style={{ fontSize: 12 }}>Standard · Actual · OK / NO · Remarks</span></div>
        <div className="op-card flush" style={{ marginTop: 10 }}>
          {checks.map((c, i) => (
            <div key={c.id} style={{ display: "grid", gridTemplateColumns: "210px 1fr 168px 116px 1.25fr", gap: 14, alignItems: "center", padding: "12px 16px", borderBottom: i < checks.length - 1 ? "1px solid var(--border)" : "none", background: !c.ok ? "oklch(from var(--destructive) l c h / 0.05)" : "transparent" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="op-check-num" style={{ background: c.ok ? "var(--foreground)" : "var(--destructive)" }}>{c.id}</span>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>{c.point}</span>
              </div>
              <span className="op-muted" style={{ fontSize: 12.5 }}>{c.standard}</span>
              <div className="op-select-wrap">
                <select className="op-select" style={{ height: 42, fontSize: 13.5 }} value={c.actual} onChange={(e) => setRow(i, { actual: e.target.value })}>
                  {c.options.map(o => <option key={o}>{o}</option>)}
                </select>
                <Ic.ChevronDown size={15} className="op-select-chev"/>
              </div>
              <div style={{ display: "inline-flex", background: "var(--muted)", padding: 3, borderRadius: 9, gap: 3 }}>
                {[["OK", true], ["NO", false]].map(([lbl, val]) => {
                  const on = c.ok === val;
                  return (
                    <button key={lbl} onClick={() => setRow(i, { ok: val })} style={{ flex: 1, height: 34, minWidth: 50, border: "none", borderRadius: 7, cursor: "pointer", fontSize: 12.5, fontWeight: 700, fontFamily: "inherit", background: on ? (val ? "var(--success)" : "var(--destructive)") : "transparent", color: on ? "#fff" : "var(--muted-foreground)" }}>{lbl}</button>
                  );
                })}
              </div>
              <input className="op-input" style={{ height: 42, fontSize: 13 }} placeholder={c.ok ? "Remarks (optional)…" : "Remark required…"} value={c.note} onChange={(e) => setRow(i, { note: e.target.value })}/>
            </div>
          ))}
          <div style={{ display: "grid", gridTemplateColumns: "210px 1fr 168px 116px 1.25fr", gap: 14, alignItems: "center", padding: "12px 16px", borderTop: "1px solid var(--border)", background: "var(--surface)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span className="op-check-num" style={{ background: "var(--avocado)", color: "var(--avocado-fg)" }}>5</span>
              <span style={{ fontSize: 13.5, fontWeight: 600 }}>Dry Matter</span>
            </div>
            <span className="op-muted" style={{ fontSize: 12.5 }}>{E.variety === "Local" || E.variety === "Jumbo" ? "Local / Jumbo: ≥ 23%" : "Hass & Fuerte: ≥ 25%"}</span>
            <span className="badge badge-closed" style={{ gridColumn: "3 / span 2", justifySelf: "start" }}><Ic.Thermometer size={12}/> Measured with sampling</span>
            <span className="op-muted" style={{ fontSize: 12 }}>Lab test · next step</span>
          </div>
        </div>
        {(unmatured || anyFail) && (
          <div style={{ marginTop: 12 }}>
            <Banner tone={anyFail ? "danger" : "warning"} icon={Ic.Warning}
              title={anyFail ? "One or more checkpoints failed (NO)" : "Fruits Status: Unmatured"}
              desc={anyFail ? "A failed checkpoint normally drives a reject at the decision step. Record a remark explaining each NO." : "Unmatured fruit is flagged but does not block acceptance — add a remark; it carries onto the GRN received condition."}/>
          </div>
        )}
      </div>

      <div className="op-actionbar">
        <Btn variant="ghost" onClick={() => go("queue")}>Save &amp; exit</Btn>
        <div className="op-ab-grow"/>
        <Btn variant="primary" icon={Ic.ArrowRight} iconRight={Ic.ArrowRight} onClick={() => go("sampling")} disabled={state === "noMatrix"}>Continue to sampling &amp; parameters</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  entry: { chrome: "flow", title: "QC inspection — GPN-…0041", sub: "Step 1 of 3 · Start", back: "queue", render: (ctx) => <QcEntryStart {...ctx}/> },
});
