// 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;

  let vals = E.samples.map(s => s.ffa);
  if (state === "tiered") vals = [0.42, 1.35, 0.48];
  if (state === "someBreach") vals = [0.42, 2.45, 0.48];
  if (state === "allBreach") vals = [2.30, 2.45, 2.18];

  const evals = vals.map(v => QD.evalFFA(v, ffa));
  const st = QD.stats(vals);
  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)}% · {ffa.method}</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">
              {vals.map((v, i) => {
                const e = evals[i];
                const bad = e.state === "out";
                return (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "46px 160px 1fr", gap: 14, alignItems: "center", padding: "14px 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: 50, 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: 22, height: "100%" }} defaultValue={v.toFixed(3)} inputMode="decimal"/>
                      <span style={{ fontSize: 13, color: "var(--muted-foreground)", padding: "0 12px", 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="Remark (optional)"/>
                    </div>
                  </div>
                );
              })}
            </div>

            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12, fontSize: 12.5, color: "var(--muted-foreground)" }}>
              <Ic.Settings size={14}/> Method: {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 }}>
              {[["Mean FFA", st.mean?.toFixed(3), "%"], ["Std dev", st.sd?.toFixed(3), ""], ["Minimum", st.min?.toFixed(3), "%"], ["Maximum", st.max?.toFixed(3), "%"]].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}/> },
});
