// OPT-QC-03 · Sampling & parameters (DM) — merged capture + measurement
// For DM testing, sampling (step 2) and parameter entry (step 3) are captured on
// one screen: each sample records position/weight/condition AND its DM% + oil%.
const QcSampling = ({ t, go }) => {
  const { Btn, Stepper, Banner, PhotoTile } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.sampling; // ruleMet | empty | partial | over
  const E = QD.EVENT, m = QD.matrixFor(E.variety, E.stage), dm = m.dm;

  const baseRows = E.samples.map(s => ({ ...s, photo: true }));
  let rows = baseRows;
  if (state === "empty") rows = baseRows.map(s => ({ ...s, pos: "", weight: "", photo: false, blank: true }));
  if (state === "partial") rows = [{ ...baseRows[0] }, { ...baseRows[1], pos: "", weight: "", photo: false, blank: true }, { ...baseRows[2], pos: "", weight: "", photo: false, blank: true }];
  if (state === "over") rows = [...baseRows, { id: "S4", pos: "Extra — bin 11", weight: 255, condition: "Sound", dm: 25.9, oil: 6.0, photo: true, extra: true }];

  const filled = rows.filter(r => !r.blank).length;
  const min = 3;
  const ruleMet = filled >= min;
  const extra = Math.max(0, filled - min);

  const dmVals = rows.map(r => r.dm).filter(v => v != null);
  const oilVals = rows.map(r => r.oil).filter(v => v != null);
  const dmStat = QD.stats(dmVals), oilStat = QD.stats(oilVals);
  const evalOf = (v) => QD.evalDM(v, dm);
  const breachN = dmVals.map(evalOf).filter(e => e.state === "out").length;

  const Chip = ({ v }) => {
    if (v == null) return <span className="badge badge-closed">—</span>;
    const e = evalOf(v);
    return <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", justifyContent: "center", margin: "2px 0 16px" }}>
          <Stepper steps={["Start", "Sampling & parameters", "Decision"]} current={1}/>
        </div>

        {/* Rule + threshold reminder strip */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 16px", borderRadius: "var(--radius-lg)", background: "var(--avocado-soft)", marginBottom: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Ic.ClipboardList size={18} style={{ color: "var(--avocado-fg)" }}/>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--avocado-fg)" }}>3 pieces required · capture DM % and oil % per sample</span>
          </div>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--avocado-fg)", fontVariantNumeric: "tabular-nums" }}>DM ≥ {dm.min}% · target {dm.target}%</span>
        </div>

        {state === "empty" && <div style={{ marginBottom: 14 }}><Banner tone="warning" icon={Ic.Warning} title="Capture at least 3 samples" desc="Identify each fruit and record its DM %. Photos are recommended for variance defence."/></div>}
        {breachN > 0 && breachN === dmVals.length && dmVals.length > 0 && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`All ${dmVals.length} samples below the DM minimum (≥ ${dm.min}%)`} desc="Strong reject signal — approve-with-breach needs a supervisor PIN at the decision step."/></div>}
        {breachN > 0 && breachN < dmVals.length && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`${breachN} of ${dmVals.length} samples below the DM minimum`} desc="Affected rows are flagged in red."/></div>}

        {/* Sample list — merged sampling + measurement */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {rows.map((s, i) => {
            const bad = s.dm != null && evalOf(s.dm).state === "out";
            return (
              <div key={s.id} className="op-card op-card-pad" style={{ background: bad ? "oklch(from var(--destructive) l c h / 0.05)" : "var(--card)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
                  <span className="op-check-num" style={{ background: bad ? "var(--destructive)" : s.extra ? "var(--soil)" : "var(--foreground)" }}>{i + 1}</span>
                  <span style={{ fontSize: 14.5, fontWeight: 600 }}>Sample {s.id}</span>
                  {s.extra && <span className="badge badge-soil">Extra</span>}
                  <div style={{ flex: 1 }}/>
                  <Chip v={s.dm}/>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "96px 1fr 120px 150px", gap: 14, alignItems: "end", marginBottom: 12 }}>
                  <PhotoTile filled={s.photo} label="Photo" hint="Tap" tag={s.id} onTap={() => {}} aspect="1 / 1"/>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Position in load</div>
                    <input className="op-input" style={{ height: 44, fontSize: 14 }} defaultValue={s.pos} placeholder="e.g. Top of bin 2"/>
                  </div>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Weight (g)</div>
                    <input className="op-input" style={{ height: 44, fontSize: 14, textAlign: "center", fontVariantNumeric: "tabular-nums" }} defaultValue={s.weight} placeholder="optional"/>
                  </div>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Visual condition</div>
                    <div className="op-select-wrap">
                      <select className="op-select" style={{ height: 44, fontSize: 14 }} defaultValue={s.condition || "Sound"}>
                        {QD.VISUAL.map(v => <option key={v}>{v}</option>)}
                      </select>
                      <Ic.ChevronDown size={16} className="op-select-chev"/>
                    </div>
                  </div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "150px 150px 1fr", gap: 14, alignItems: "end" }}>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Dry matter <span className="req">*</span></div>
                    <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: 20, height: "100%" }} defaultValue={s.dm != null ? s.dm.toFixed(1) : ""} placeholder="0.0" inputMode="decimal"/>
                      <span style={{ fontSize: 12, color: "var(--muted-foreground)", padding: "0 10px", fontWeight: 600 }}>%</span>
                    </div>
                  </div>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Oil content</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: 20, height: "100%" }} defaultValue={s.oil != null ? s.oil.toFixed(1) : ""} placeholder="0.0" inputMode="decimal"/>
                      <span style={{ fontSize: 12, color: "var(--muted-foreground)", padding: "0 10px", fontWeight: 600 }}>%</span>
                    </div>
                  </div>
                  <div>
                    <div className="op-label" style={{ fontSize: 12, marginBottom: 5 }}>Remark</div>
                    <input className="op-input" style={{ height: 44, fontSize: 13 }} placeholder={bad ? "Remark required…" : "Remark (optional)"}/>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <button className="op-btn op-btn-ghost" style={{ marginTop: 14, width: "100%", border: "1.5px dashed var(--border)", height: 52 }}><Ic.Plus size={18}/> Add extra sample</button>

        {/* Derived statistics */}
        {dmVals.length > 0 && (
          <div className="op-card op-card-pad" style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>Derived statistics</div>
            {[["Avg DM", dmStat.mean?.toFixed(2), "%"], ["Min DM", dmStat.min?.toFixed(1), "%"], ["Max DM", dmStat.max?.toFixed(1), "%"], ["Avg oil", oilStat.mean?.toFixed(2), "%"]].map(([k, v, u]) => (
              <div key={k}><span className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, marginRight: 8 }}>{k}</span><span style={{ fontSize: 18, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{v}<small style={{ fontSize: 12, color: "var(--muted-foreground)" }}>{u}</small></span></div>
            ))}
            <div style={{ flex: 1 }}/>
            <span className="badge" style={{ background: breachN === 0 ? "var(--success-soft)" : breachN === dmVals.length ? "var(--status-rejected-soft)" : "var(--status-pending-soft)", color: breachN === 0 ? "var(--success)" : breachN === dmVals.length ? "var(--status-rejected-fg)" : "var(--status-pending-fg)", fontWeight: 600 }}>
              {breachN === 0 ? "Approve" : breachN === dmVals.length ? "Reject" : "Inspector's call"}
            </span>
          </div>
        )}
      </div>

      <div className="op-actionbar">
        <Btn variant="ghost" onClick={() => go("queue")}>Save &amp; exit</Btn>
        <div className="op-ab-grow"/>
        {!ruleMet && <span className="op-hint" style={{ margin: 0 }}><Ic.Info size={12} style={{ verticalAlign: "-2px" }}/> {filled} of {min} samples captured</span>}
        <Btn variant="primary" icon={Ic.ArrowRight} disabled={!ruleMet} onClick={() => go("decision")}>Continue to decision</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  sampling: { chrome: "flow", title: "Sampling & parameters — GPN-…0041", sub: "Step 2 of 3 · Sampling & DM", back: "entry", render: (ctx) => <QcSampling {...ctx}/> },
});
