// OPT-QC-04 · Enter DM parameter
const QcDmParam = ({ t, go }) => {
  const { Btn, Stepper, Banner } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.dmParam; // inRange | someOut | allOut | calibration
  const E = QD.EVENT, m = QD.matrixFor(E.variety, E.stage), dm = m.dm;

  let vals = E.samples.map(s => s.dm);
  if (state === "someOut") vals = [25.4, 22.8, 26.2];
  if (state === "allOut") vals = [22.4, 21.8, 22.9];
  const oils = E.samples.map(s => s.oil);
  const oilStat = QD.stats(oils);

  const evals = vals.map(v => QD.evalDM(v, dm));
  const st = QD.stats(vals);
  const breachN = evals.filter(e => e.state === "out").length;

  const Chip = ({ e }) => (
    <span className={`badge ${e.tone === "green" ? "badge-approved" : e.tone === "amber" ? "badge-pending" : e.tone === "red" ? "badge-rejected" : "badge-closed"}`} style={{ whiteSpace: "nowrap" }}>
      {e.tone === "green" ? <Ic.Check size={12}/> : e.tone === "red" ? <Ic.Warning size={12}/> : null} {e.label}
    </span>
  );

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "2px 0 16px" }}>
          <Stepper steps={["Start", "Sampling", "Parameters", "Decision"]} current={2}/>
          <div className="op-tabs">
            <button className="on">DM</button>
            <button onClick={() => go("ffaParam")}>FFA</button>
            <button onClick={() => go("extReport")}>External</button>
          </div>
        </div>

        {state === "calibration" && <div style={{ marginBottom: 14 }}><Banner tone="warning" icon={Ic.Warning} title="DM tester calibration overdue" desc={`Last calibration ${E.calibration.dm} (limit 30 days). Recalibrate before continuing, or request a supervisor override.`}><div style={{ marginTop: 10 }}><Btn variant="outline" size="sm" icon={Ic.Settings}>Recalibrate now</Btn></div></Banner></div>}
        {breachN === vals.length && breachN > 0 && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`All ${vals.length} samples breach the DM threshold (below ${dm.min}%)`} desc="Strong reject signal. You can still reach the decision step — approve-with-breach needs a supervisor PIN."/></div>}
        {breachN > 0 && breachN < vals.length && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`${breachN} of ${vals.length} samples breach the DM threshold`} desc={<>Affected rows are flagged in red. <button className="op-scan-link" style={{ color: "var(--destructive)", fontSize: 13 }} onClick={() => go("breach")}>Why?</button></>}/></div>}
        {breachN === 0 && state !== "calibration" && <div style={{ marginBottom: 14 }}><Banner tone="success" icon={Ic.CheckCircle} title="All DM samples meet the minimum" desc={`≥ ${dm.min}% required · target ${dm.target}%`}/></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 18, alignItems: "start" }}>
          <div>
            {/* Threshold strip */}
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 16px", borderRadius: "var(--radius-lg)", border: "1px solid var(--border)", background: "var(--card)", marginBottom: 12 }}>
              <Ic.Thermometer size={18} style={{ color: "var(--avocado-fg)" }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{E.variety} · {E.stage} — Dry Matter</div>
                <div className="op-muted" style={{ fontSize: 12 }}>Minimum ≥ {dm.min}% · target {dm.target}%</div>
              </div>
              {/* mini range track */}
              <div style={{ width: 180, height: 8, borderRadius: 4, background: "var(--muted)", position: "relative" }}>
                <div style={{ position: "absolute", left: "40%", right: 0, top: 0, bottom: 0, borderRadius: 4, background: "oklch(from var(--success) l c h / 0.35)" }}/>
                <div style={{ position: "absolute", left: "40%", top: -3, width: 3, height: 14, background: "var(--avocado)", borderRadius: 2 }}/>
              </div>
            </div>

            {/* Sample entry list — each sample yields DM% and oil content% */}
            <div className="op-card flush">
              <div style={{ display: "grid", gridTemplateColumns: "38px 118px 118px 1fr", gap: 12, padding: "10px 16px", borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
                <span/>
                <span className="op-muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em" }}>DRY MATTER</span>
                <span className="op-muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em" }}>OIL CONTENT</span>
                <span className="op-muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em" }}>STATUS · REMARK</span>
              </div>
              {vals.map((v, i) => {
                const e = evals[i];
                const bad = e.state === "out";
                return (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "38px 118px 118px 1fr", gap: 12, alignItems: "center", padding: "12px 16px", borderBottom: i < vals.length - 1 ? "1px solid var(--border)" : "none", background: bad ? "oklch(from var(--destructive) l c h / 0.06)" : "transparent" }}>
                    <span className="op-check-num" style={{ background: bad ? "var(--destructive)" : "var(--foreground)" }}>{E.samples[i].id}</span>
                    <div style={{ display: "flex", alignItems: "center", height: 48, border: `1.5px solid ${bad ? "var(--destructive)" : "var(--input)"}`, borderRadius: "var(--radius-lg)", background: "var(--card)", overflow: "hidden" }}>
                      <input className="op-num-input" style={{ fontSize: 21, height: "100%" }} defaultValue={v.toFixed(1)} inputMode="decimal"/>
                      <span style={{ fontSize: 12, color: "var(--muted-foreground)", padding: "0 10px", fontWeight: 600 }}>%</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", height: 48, border: "1.5px solid var(--input)", borderRadius: "var(--radius-lg)", background: "var(--card)", overflow: "hidden" }}>
                      <input className="op-num-input" style={{ fontSize: 21, height: "100%" }} defaultValue={oils[i].toFixed(1)} inputMode="decimal"/>
                      <span style={{ fontSize: 12, color: "var(--muted-foreground)", padding: "0 10px", fontWeight: 600 }}>%</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <Chip e={e}/>
                      <input className="op-input" style={{ height: 40, fontSize: 13, flex: 1 }} placeholder={bad ? "Remark required…" : "Remark (optional)"}/>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Calibration footer */}
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, fontSize: 12.5, color: "var(--muted-foreground)" }}>
              <Ic.Settings size={14}/> Last DM calibration: {E.calibration.dm}. <button className="op-sec-link" style={{ fontSize: 12.5 }}>Recalibrate?</button>
            </div>
          </div>

          {/* Derived stats */}
          <div className="op-card op-card-pad">
            <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 14 }}>Derived statistics</div>
            <div className="op-grid-2" style={{ gap: 12 }}>
              {[["Avg DM", st.mean?.toFixed(2), "%"], ["Avg oil", oilStat.mean?.toFixed(2), "%"], ["Min DM", st.min?.toFixed(1), "%"], ["Max DM", st.max?.toFixed(1), "%"]].map(([k, v, u]) => (
                <div key={k} style={{ padding: "12px 14px", borderRadius: "var(--radius-lg)", background: "var(--surface)", border: "1px solid var(--border)" }}>
                  <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600 }}>{k}</div>
                  <div style={{ fontSize: 22, fontWeight: 700, fontVariantNumeric: "tabular-nums", marginTop: 3 }}>{v}<small style={{ fontSize: 13, color: "var(--muted-foreground)", marginLeft: 2 }}>{u}</small></div>
                </div>
              ))}
            </div>
            <div className="op-divider"/>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13 }}>
              <span className="op-muted">Decision support</span>
              <span className="badge" style={{ background: breachN === 0 ? "var(--success-soft)" : breachN === vals.length ? "var(--status-rejected-soft)" : "var(--status-pending-soft)", color: breachN === 0 ? "var(--success)" : breachN === vals.length ? "var(--status-rejected-fg)" : "var(--status-pending-fg)", fontWeight: 600 }}>
                {breachN === 0 ? "Approve" : breachN === vals.length ? "Reject" : "Inspector's call"}
              </span>
            </div>
          </div>
        </div>
      </div>

      <div className="op-actionbar">
        <Btn variant="ghost" icon={Ic.Edit} onClick={() => go("remarks")}>Add remarks</Btn>
        <div className="op-ab-grow"/>
        <Btn variant="outline" onClick={() => go("ffaParam")}>Continue to FFA</Btn>
        <Btn variant="primary" icon={Ic.ArrowRight} onClick={() => go("decision")}>Continue to decision</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  dmParam: { chrome: "flow", title: "Parameters — GPN-…0041", sub: "Step 3 of 4 · Dry Matter", back: "sampling", render: (ctx) => <QcDmParam {...ctx}/> },
});
