// OPT-QC-05 · Enter FFA parameter
const QcFfaParam = ({ t, go }) => {
  const { Btn, Stepper, Banner } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.ffaParam; // inRange | tiered | someBreach | allBreach
  const E = QD.EVENT, m = QD.matrixFor(E.variety, E.stage), ffa = m.ffa;

  const N = E.ffaConst.normality, MEQ = E.ffaConst.mnEq;
  const back = (targets) => targets.map((tg, i) => ({ ...E.samples[i], titrant: +(tg * E.samples[i].sampleWt / (N * MEQ)).toFixed(3) }));
  let rows = E.samples.slice();
  if (state === "tiered")     rows = back([0.42, 1.35, 0.48]);
  if (state === "someBreach") rows = back([0.42, 2.45, 0.48]);
  if (state === "allBreach")  rows = back([2.30, 2.45, 2.18]);

  const vals = rows.map(r => QD.ffaFrom(r.titrant, r.sampleWt, N, MEQ));
  const avs = vals.map(v => QD.avFrom(v));
  const evals = vals.map(v => QD.evalFFA(v, ffa));
  const st = QD.stats(vals);
  const avStat = QD.stats(avs);
  const breachN = evals.filter(e => e.state === "out").length;
  const stdN = evals.filter(e => e.state === "edge").length;
  const worstTier = breachN ? "reject" : stdN ? "standard" : "premium";

  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.Star 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 onClick={() => go("dmParam")}>DM</button>
            <button className="on">FFA</button>
            <button onClick={() => go("extReport")}>External</button>
          </div>
        </div>

        {breachN === vals.length && breachN > 0 && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`All ${vals.length} samples exceed the FFA limit (> ${ffa.accept.toFixed(1)}%)`} desc="Strong reject signal for oil quality."/></div>}
        {breachN > 0 && breachN < vals.length && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Warning} title={`${breachN} of ${vals.length} samples exceed the FFA limit`} desc={<>Affected rows flagged in red. <button className="op-scan-link" style={{ color: "var(--destructive)", fontSize: 13 }} onClick={() => go("breach")}>Why?</button></>}/></div>}
        {breachN === 0 && stdN > 0 && <div style={{ marginBottom: 14 }}><Banner tone="warning" icon={Ic.Info} title="Standard grade — below premium" desc={`At least one sample is above the premium threshold (≤ ${ffa.premium.toFixed(1)}%) but within accept (≤ ${ffa.accept.toFixed(1)}%).`}/></div>}
        {breachN === 0 && stdN === 0 && <div style={{ marginBottom: 14 }}><Banner tone="success" icon={Ic.Star} title="Premium grade — all FFA samples ≤ premium threshold" desc={`Premium ≤ ${ffa.premium.toFixed(1)}% · accept ≤ ${ffa.accept.toFixed(1)}%`}/></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 18, alignItems: "start" }}>
          <div>
            {/* Threshold strip with tiers */}
            <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.Drop size={18} style={{ color: "var(--avocado-fg)" }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{E.variety} crude oil — Free Fatty Acid</div>
                <div className="op-muted" style={{ fontSize: 12 }}>Premium ≤ {ffa.premium.toFixed(1)}% · accept ≤ {ffa.accept.toFixed(1)}% · N {N} · MnEq {MEQ}</div>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <span className="badge badge-approved" style={{ fontSize: 10 }}>Premium</span>
                <span className="badge badge-pending" style={{ fontSize: 10 }}>Standard</span>
                <span className="badge badge-rejected" style={{ fontSize: 10 }}>Reject</span>
              </div>
            </div>

            <div className="op-card flush">
              <div style={{ display: "grid", gridTemplateColumns: "34px 104px 104px 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" }}>SAMPLE (g)</span>
                <span className="op-muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em" }}>TITRANT (mL)</span>
                <span className="op-muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".04em" }}>%FFA · ACID VALUE · GRADE</span>
              </div>
              {rows.map((r, i) => {
                const v = vals[i], e = evals[i];
                const bad = e.state === "out";
                return (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "34px 104px 104px 1fr", gap: 12, alignItems: "center", padding: "12px 16px", borderBottom: i < rows.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)" }}>{r.id}</span>
                    <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: 18, height: "100%" }} defaultValue={r.sampleWt.toFixed(2)} inputMode="decimal"/>
                    </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: 18, height: "100%" }} defaultValue={r.titrant.toFixed(2)} inputMode="decimal"/>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <div style={{ minWidth: 86 }}>
                        <span style={{ fontSize: 21, fontWeight: 700, fontVariantNumeric: "tabular-nums", color: bad ? "var(--destructive)" : "var(--foreground)" }}>{v.toFixed(2)}<small style={{ fontSize: 12, color: "var(--muted-foreground)", fontWeight: 600 }}>%</small></span>
                        <div className="op-muted" style={{ fontSize: 11 }}>AV {avs[i].toFixed(2)}</div>
                      </div>
                      <Chip e={e}/>
                    </div>
                  </div>
                );
              })}
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, fontSize: 12.5, color: "var(--muted-foreground)" }}>
              <Ic.Settings size={14}/> %FFA = (titrant × {N} × {MEQ}) ÷ sample wt · {ffa.method}. Last calibration: {E.calibration.ffa}.
            </div>
          </div>

          <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 %FFA", st.mean?.toFixed(2), "%"], ["Avg acid value", avStat.mean?.toFixed(2), ""], ["Min FFA", st.min?.toFixed(2), "%"], ["Max FFA", st.max?.toFixed(2), "%"]].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: 20, fontWeight: 700, fontVariantNumeric: "tabular-nums", marginTop: 3 }}>{v}<small style={{ fontSize: 12, 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">Resulting grade</span>
              <span className={`badge ${worstTier === "premium" ? "badge-approved" : worstTier === "standard" ? "badge-pending" : "badge-rejected"}`} style={{ fontWeight: 600 }}>
                {worstTier === "premium" ? "Premium" : worstTier === "standard" ? "Standard" : "Below limit"}
              </span>
            </div>
            <div className="op-muted" style={{ fontSize: 11.5, marginTop: 8, lineHeight: 1.5 }}>At Intake, FFA is informational. At Production it gates the grade output.</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="primary" icon={Ic.ArrowRight} onClick={() => go("decision")}>Continue to decision</Btn>
      </div>
    </div>
  );
};

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