// OPT-QC-09 · QC approve / reject decision
const QcDecision = ({ t, go }) => {
  const { Btn, Pill, Stepper, Banner, Modal, OverrideModal, SRow } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.decision; // approve | reject | call
  const E = QD.EVENT, m = QD.matrixFor(E.variety, E.stage), dm = m.dm;

  // value set drives the recommendation
  const dmVals = state === "reject" ? [22.4, 21.8, 22.9] : state === "call" ? [25.3, 24.7, 25.6] : E.samples.map(s => s.dm);
  const ffaVals = E.samples.map(s => s.ffa);
  const dmStat = QD.stats(dmVals), ffaStat = QD.stats(ffaVals);
  const dmEvals = dmVals.map(v => QD.evalDM(v, dm));
  const dmBreach = dmEvals.filter(e => e.state === "out").length;

  const rec = state === "approve" ? "Approve" : state === "reject" ? "Reject" : "Inspector's call";
  const recTone = state === "approve" ? "approved" : state === "reject" ? "rejected" : "pending";

  const [reject, setReject] = useState(false);
  const [hold, setHold] = useState(false);
  const [override, setOverride] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const submit = (route) => { setSubmitting(true); setTimeout(() => go(route), 650); };

  const StatCard = ({ icon: Icon, title, stat, unit, breach, decimals = 2 }) => (
    <div className="op-card op-card-pad" style={{ padding: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13.5, fontWeight: 600 }}><Icon size={15} style={{ color: "var(--avocado-fg)" }}/>{title}</div>
        {breach > 0 ? <span className="badge badge-rejected">{breach} breach</span> : <span className="badge badge-approved"><Ic.Check size={11}/> In range</span>}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        {[["Mean", stat.mean], ["Min", stat.min], ["Max", stat.max]].map(([k, v]) => (
          <div key={k} style={{ textAlign: "center", flex: 1 }}>
            <div className="op-muted" style={{ fontSize: 11 }}>{k}</div>
            <div style={{ fontSize: 17, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{v?.toFixed(decimals)}<small style={{ fontSize: 11, color: "var(--muted-foreground)" }}>{unit}</small></div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      {/* Top summary strip */}
      <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "12px 24px", borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
        <span className="op-row-thumb" style={{ width: 42, height: 42 }}><Ic.Leaf size={20}/></span>
        <div><div style={{ fontSize: 15, fontWeight: 600 }}>{E.who} <span className="op-muted" style={{ fontWeight: 500, fontSize: 12.5 }}>· Tier {E.tier}</span></div><div className="op-gpn" style={{ color: "var(--muted-foreground)" }}>{E.gpn}</div></div>
        <div className="op-ab-spacer" style={{ flex: 1 }}/>
        <div style={{ textAlign: "right" }}><div className="op-muted" style={{ fontSize: 11.5 }}>{E.variety} · {E.stage}</div><div style={{ fontSize: 15, fontWeight: 700 }}>{QD.KG(E.net)}</div></div>
      </div>

      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "center", margin: "0 0 16px" }}>
          <Stepper steps={["Start", "Sampling & parameters", "Submit for decision"]} current={2}/>
        </div>

        <div style={{ marginBottom: 16 }}>
          <Banner tone="info" icon={Ic.Info} title="QC records the result — procurement decides"
            desc="Submitting sends this QC result to procurement for the buying decision (Accept / Reject / Accept-with-adjustment). QC no longer approves or rejects loads directly."/>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.25fr 0.95fr 0.95fr", gap: 16, alignItems: "start" }}>
          {/* Evidence summary */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div className="op-sec" style={{ margin: 0 }}><span className="op-sec-title">Evidence</span><button className="op-sec-link" onClick={() => go("sampling")}>Re-enter</button></div>
            <StatCard icon={Ic.Thermometer} title="Dry Matter" stat={dmStat} unit="%" breach={dmBreach} decimals={2}/>
            <StatCard icon={Ic.Drop} title="Free Fatty Acid" stat={ffaStat} unit="%" breach={0} decimals={3}/>
            <div className="op-card op-card-pad" style={{ padding: 14, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontSize: 13, display: "flex", alignItems: "center", gap: 7 }}><Ic.ClipboardList size={15} style={{ color: "var(--muted-foreground)" }}/> Samples inspected</span>
              <span style={{ fontSize: 14, fontWeight: 700 }}>3 of 3</span>
            </div>
          </div>

          {/* Remarks */}
          <div>
            <div className="op-sec" style={{ margin: 0 }}><span className="op-sec-title">Inspector remarks</span><button className="op-sec-link" onClick={() => go("remarks")}>Edit</button></div>
            <div className="op-card op-card-pad" style={{ marginTop: 12 }}>
              {dmBreach > 0
                ? <div style={{ fontSize: 13, lineHeight: 1.55, color: "var(--foreground)" }}>Load partially shaded on arrival; one section appears harvested early. S2 read 19.2% — re-sampled, second reading consistent. Recommend supervisor review before approval.</div>
                : <div style={{ fontSize: 13, lineHeight: 1.55, color: "var(--muted-foreground)" }}>No anomalies noted. Load sound and consistent across all three samples. No additional remarks recorded.</div>}
              <div className="op-divider"/>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span className="op-pt-img" style={{ position: "static", width: 38, height: 38, borderRadius: 8, display: "inline-block", background: "repeating-linear-gradient(135deg, var(--muted) 0 8px, var(--surface) 8px 16px)" }}/>
                <span className="op-pt-img" style={{ position: "static", width: 38, height: 38, borderRadius: 8, display: "inline-block", background: "repeating-linear-gradient(135deg, var(--muted) 0 8px, var(--surface) 8px 16px)" }}/>
                <span className="op-muted" style={{ fontSize: 12 }}>2 evidence photos</span>
              </div>
            </div>
          </div>

          {/* Decision support */}
          <div>
            <div className="op-sec" style={{ margin: 0 }}><span className="op-sec-title">Recommendation for procurement</span></div>
            <div className="op-card op-card-pad" style={{ marginTop: 12, borderColor: state !== "call" ? `oklch(from var(--${recTone === "approved" ? "success" : "destructive"}) l c h / 0.4)` : undefined }}>
              <div className="op-muted" style={{ fontSize: 12 }}>Matrix recommendation</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "8px 0 4px" }}>
                <span className="op-row-thumb" style={{ width: 40, height: 40, background: recTone === "approved" ? "var(--success-soft)" : recTone === "rejected" ? "var(--status-rejected-soft)" : "var(--status-pending-soft)", color: recTone === "approved" ? "var(--success)" : recTone === "rejected" ? "var(--status-rejected-fg)" : "var(--status-pending-fg)" }}>
                  {recTone === "approved" ? <Ic.CheckCircle size={20}/> : recTone === "rejected" ? <Ic.XCircle size={20}/> : <Ic.HelpCircle size={20}/>}
                </span>
                <span style={{ fontSize: 19, fontWeight: 700 }}>{rec}</span>
              </div>
              <div className="op-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>{state === "approve" ? "All samples within range. Decision rule: majority pass." : state === "reject" ? "All DM samples below the minimum. Strong reject signal." : "Borderline readings near the boundary — equal treatment, your call."}</div>
            </div>
            <div className="op-card op-card-pad" style={{ marginTop: 12 }}>
              <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, marginBottom: 8 }}>LAST 5 APPROVALS · {E.variety} AT THIS DM RANGE</div>
              <div style={{ display: "flex", gap: 6 }}>
                {[25.4, 26.1, 25.2, 27.0, 25.8].map((v, i) => (
                  <div key={i} style={{ flex: 1, textAlign: "center", padding: "8px 0", borderRadius: 8, background: "var(--success-soft)" }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "var(--success)", fontVariantNumeric: "tabular-nums" }}>{v}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Incoming inspection checklist (IMTR) — read-only summary carried into the decision */}
      <div className="op-pad" style={{ paddingTop: 0 }}>
        <div className="op-sec" style={{ margin: "0 2px 10px" }}><span className="op-sec-title">Inspection checklist <span className="op-muted" style={{ fontWeight: 500 }}>· IMTR</span></span><span className="op-muted" style={{ fontSize: 12 }}>Captured at start · read-only</span></div>
        <div className="op-card flush">
          {E.checklist.map((c, i) => (
            <div key={c.id} style={{ display: "grid", gridTemplateColumns: "220px 1fr 150px 90px", gap: 14, alignItems: "center", padding: "11px 16px", borderBottom: i < E.checklist.length - 1 ? "1px solid var(--border)" : "none", background: !c.ok ? "oklch(from var(--destructive) l c h / 0.05)" : "transparent" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="op-check-num" style={{ background: c.ok ? "var(--foreground)" : "var(--destructive)" }}>{c.id}</span>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>{c.point}</span>
              </div>
              <span className="op-muted" style={{ fontSize: 12.5 }}>{c.standard}</span>
              <span style={{ fontSize: 13.5, fontWeight: 600 }}>{c.actual}</span>
              <span className={`badge ${c.ok ? "badge-approved" : "badge-rejected"}`} style={{ justifySelf: "start" }}>{c.ok ? <><Ic.Check size={12}/> OK</> : <><Ic.Warning size={12}/> NO</>}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Sticky action bar — QC submits the result; procurement decides */}
      <div className="op-actionbar" style={{ gap: 14 }}>
        <Btn variant="outline" icon={Ic.Warning} style={{ flex: 1, height: 60, color: "var(--destructive)" }} onClick={() => setReject(true)}>Flag reject concern</Btn>
        <Btn variant="outline" icon={Ic.Clock} style={{ flex: 1, height: 60 }} onClick={() => setHold(true)}>Hold for review</Btn>
        <Btn variant="primary" icon={Ic.ArrowRight} style={{ flex: 1.4, height: 60, background: "var(--success)" }} loading={submitting} onClick={() => submit("pass")}>Submit result to procurement</Btn>
      </div>

      {/* Flag reject concern modal — QC flags, procurement decides */}
      <Modal open={reject} onClose={() => setReject(false)} title="Flag a reject concern" desc="QC no longer rejects loads directly. Flagging records your concern and fast-tracks the load to procurement, who make the final buying decision.">
        <div className="op-field"><div className="op-label">Concern <span className="req">*</span></div><textarea className="op-textarea" placeholder="e.g. dry matter below minimum across all samples…" defaultValue={state === "reject" ? "All DM samples below the 25% minimum — immature fruit." : ""}/></div>
        <div className="op-modal-actions"><Btn variant="ghost" block onClick={() => setReject(false)}>Cancel</Btn><Btn variant="primary" block onClick={() => { setReject(false); go("flagReject"); }}>Flag &amp; send to procurement</Btn></div>
      </Modal>

      {/* Hold modal */}
      <Modal open={hold} onClose={() => setHold(false)} title="Hold for supervisor review" desc="The truck stays on-site at status 'QC hold'. Your task closes; the event stays open until the supervisor decides.">
        <div className="op-field"><div className="op-label">Reason <span className="req">*</span></div><textarea className="op-textarea" placeholder="Why does this need supervisor attention?"/></div>
        <div className="op-field" style={{ margin: 0 }}><div className="op-label">Assign supervisor <span className="req">*</span></div><div className="op-select-wrap"><select className="op-select"><option>{QD.SUPERVISOR.name} (QC Supervisor)</option><option>Grace Mwangi (QC Manager)</option></select><Ic.ChevronDown size={16} className="op-select-chev"/></div></div>
        <div className="op-modal-actions"><Btn variant="ghost" block onClick={() => setHold(false)}>Cancel</Btn><Btn variant="primary" block onClick={() => { setHold(false); submit("queue"); }}>Place on hold</Btn></div>
      </Modal>

      {/* Approve-with-breach override */}
      <OverrideModal open={override} onClose={() => setOverride(false)} condition="You are approving a load with one or more parameter breaches. The supervisor PIN, reason, and the original breach are logged permanently against the batch."
        onConfirm={() => { setOverride(false); submit("pass"); }}/>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  decision: { chrome: "flow", title: "Submit QC result for decision — GPN-…0041", sub: "Step 3 of 3 · Submit for decision", back: "sampling", render: (ctx) => <QcDecision {...ctx}/> },
});
