// OPT-QC-12 · QC matrix configuration
const QcMatrix = ({ t, go }) => {
  const { Btn, Pill, Banner } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.matrix; // default | editor | empty | errors
  const rows = Object.values(QD.MATRIX);
  const [editor, setEditor] = useState(state === "editor");
  const [tab, setTab] = useState("DM");
  useEffect(() => { setEditor(state === "editor"); }, [state]);
  const empty = state === "empty";
  const errors = state === "errors";

  const samplingLabel = { "3-piece": "3-piece", "percent": "% of qty", "per-bin": "Per-bin", "random": "Random" };
  const decisionLabel = { majority: "Majority pass", anyBreach: "Any breach = reject", allBreach: "All breach = reject" };

  return (
    <div className="op-body">
      <div className="op-pad">
        <div className="op-sec" style={{ marginBottom: 14 }}>
          <div><div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.015em" }}>QC threshold matrix</div><div className="op-muted" style={{ fontSize: 13, marginTop: 2 }}>Per variety × stage — drives every QC decision</div></div>
          <div style={{ display: "flex", gap: 10 }}>
            <div className="op-search sm" style={{ width: 220 }}><Ic.Search size={16} className="op-search-ic"/><input className="op-input" placeholder="Search variety…"/></div>
            <Btn variant="outline" size="sm" icon={Ic.Upload}>Import CSV</Btn>
            <Btn variant="primary" size="sm" icon={Ic.Plus} onClick={() => setEditor(true)}>New matrix</Btn>
          </div>
        </div>

        {empty ? (
          <div className="op-empty" style={{ padding: "72px 36px" }}>
            <div className="op-empty-art"><Ic.Layers size={42}/></div>
            <div className="op-empty-title">No matrix configured</div>
            <div className="op-empty-desc">Create your first threshold matrix to enable QC inspections. Each matrix defines accept ranges, sampling, and decision rules for a variety and stage.</div>
            <Btn variant="primary" icon={Ic.Plus} style={{ marginTop: 18 }} onClick={() => setEditor(true)}>Create matrix</Btn>
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: editor ? "1fr 420px" : "1fr", gap: 16, alignItems: "start" }}>
            <div className="op-tbl-wrap">
              <table className="op-tbl">
                <thead><tr><th>Variety</th><th>Stage</th><th>DM min</th><th>DM target</th><th>FFA accept</th><th>Sampling</th><th>Decision rule</th><th>Updated</th><th></th></tr></thead>
                <tbody>
                  {rows.map((r, i) => (
                    <tr key={i} className={editor && i === 0 ? "selected" : ""} onClick={() => setEditor(true)}>
                      <td style={{ fontWeight: 600 }}>{r.variety} {r.recent && <span className="badge badge-soil" style={{ fontSize: 9, marginLeft: 4 }}>Updated</span>}</td>
                      <td><Pill tone={r.stage === "Intake" ? "avocado" : "soil"}>{r.stage}</Pill></td>
                      <td className="num">{r.dm ? `≥ ${r.dm.min}%` : "—"}</td>
                      <td className="num">{r.dm ? `${r.dm.target}%` : "—"}</td>
                      <td className="num">≤ {r.ffa.accept.toFixed(1)}% <span className="op-muted">/ {r.ffa.premium.toFixed(1)}</span></td>
                      <td>{samplingLabel[r.sampling]}</td>
                      <td style={{ fontSize: 12.5 }}>{decisionLabel[r.decision]}</td>
                      <td className="op-muted" style={{ fontSize: 12 }}>{r.updated}<br/><span style={{ fontSize: 11 }}>{r.by}</span></td>
                      <td><button className="op-iconbtn ghost" style={{ width: 36, height: 36 }} onClick={(e) => { e.stopPropagation(); setEditor(true); }}><Ic.Edit size={16}/></button></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Editor side panel */}
            {editor && (
              <div className="op-card op-card-pad" style={{ position: "sticky", top: 0 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 600 }}>Edit matrix · Hass / Intake</div>
                  <button className="op-iconbtn ghost" style={{ width: 36, height: 36 }} onClick={() => setEditor(false)}><Ic.X size={18}/></button>
                </div>
                <div className="op-tabs" style={{ display: "flex", width: "100%", marginBottom: 16 }}>
                  {["DM", "FFA", "Sampling", "Decision"].map(x => <button key={x} className={tab === x ? "on" : ""} style={{ flex: 1 }} onClick={() => setTab(x)}>{x}</button>)}
                </div>

                {errors && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title="Target is below the minimum" desc="Fix the highlighted fields before saving."/></div>}

                {tab === "DM" && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    <div className="op-grid-2" style={{ gap: 12 }}>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Minimum (%) <span className="req">*</span></div><input className={`op-input ${errors ? "err" : ""}`} defaultValue="25"/></div>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Target (%) <span className="op-muted" style={{ fontWeight: 400 }}>· optional</span></div><input className={`op-input ${errors ? "err" : ""}`} defaultValue={errors ? "23" : "27"}/></div>
                    </div>
                    {errors && <div className="op-err" style={{ marginTop: -6 }}><Ic.Warning size={12}/> Target should be at or above the minimum.</div>}
                    <div className="op-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>DM is a minimum floor — readings at or above the minimum pass. Hass &amp; Fuerte ≥ 25%, Local / Jumbo ≥ 23%.</div>
                    <div style={{ height: 8, borderRadius: 4, background: "var(--muted)", position: "relative", margin: "4px 0" }}>
                      <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>
                )}
                {tab === "FFA" && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    <div className="op-grid-2" style={{ gap: 12 }}>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Premium ≤ (%)</div><input className="op-input" defaultValue="1.0"/></div>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Accept ≤ (%)</div><input className="op-input" defaultValue="2.0"/></div>
                    </div>
                    <div className="op-field" style={{ margin: 0 }}><div className="op-label">Method</div><div className="op-select-wrap"><select className="op-select"><option>Titration</option><option>Refractometer</option><option>Other</option></select><Ic.ChevronDown size={16} className="op-select-chev"/></div></div>
                  </div>
                )}
                {tab === "Sampling" && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    <div className="op-field" style={{ margin: 0 }}><div className="op-label">Rule type</div><div className="op-select-wrap"><select className="op-select"><option>3-piece</option><option>Percent of qty</option><option>Per-bin</option><option>Random</option></select><Ic.ChevronDown size={16} className="op-select-chev"/></div></div>
                    <div className="op-field" style={{ margin: 0 }}><div className="op-label">Pieces per truck</div><input className="op-input" defaultValue="3"/></div>
                  </div>
                )}
                {tab === "Decision" && (
                  <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                    <div className="op-field" style={{ margin: 0 }}><div className="op-label">Decision rule</div><div className="op-select-wrap"><select className="op-select"><option>Majority pass</option><option>Any breach = reject</option><option>All breach = reject</option></select><Ic.ChevronDown size={16} className="op-select-chev"/></div></div>
                    <div className="op-grid-2" style={{ gap: 12 }}>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Effective from</div><input className="op-input" defaultValue="16 May 2026"/></div>
                      <div className="op-field" style={{ margin: 0 }}><div className="op-label">Effective to</div><input className="op-input" placeholder="optional"/></div>
                    </div>
                  </div>
                )}

                <div className="op-divider"/>
                <div style={{ display: "flex", gap: 10 }}>
                  <Btn variant="ghost" block onClick={() => setEditor(false)}>Cancel</Btn>
                  <Btn variant="primary" block icon={Ic.Check} disabled={errors}>Save matrix</Btn>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  matrix: { chrome: "tabs", tab: "Matrix", render: (ctx) => <QcMatrix {...ctx}/> },
});
