// OPT-QC-16 · Incoming QC — flag rejected & route to exit  (Addendum Update B, NEW)
// Operator Tablet · QC Inspector · P0 · 1280×800
// After procurement rejects, QC confirms the rejection on the truck record and
// routes it to gate exit. Registered as window.OptPages.flagReject.
// Tweak flagReject: awaiting · confirmed · refused

const QcFlagReject = ({ t, go }) => {
  const { Btn, Pill, Banner, SRow } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.flagReject || "awaiting";
  const E = QD.EVENT;

  const [checks, setChecks] = useState(() => ({
    sample: state !== "awaiting",
    load: state !== "awaiting",
    ack: state === "confirmed",
  }));
  useEffect(() => {
    setChecks({ sample: state !== "awaiting", load: state !== "awaiting", ack: state === "confirmed" });
  }, [state]);
  const toggle = (k) => setChecks(c => ({ ...c, [k]: !c[k] }));
  const refused = state === "refused";
  const allChecked = checks.sample && checks.load && (refused || checks.ack);

  const Check = ({ on, onClick, title, sub }) => (
    <button className="op-toggle-row" onClick={onClick} style={{ width: "100%", textAlign: "left", cursor: "pointer", background: "none", border: "none", borderBottom: "1px solid var(--border)" }}>
      <span className={`op-check ${on ? "on" : ""}`} style={{ width: 24, height: 24, borderRadius: 7, flexShrink: 0, border: on ? "none" : "1.5px solid var(--input)", background: on ? "var(--success)" : "var(--card)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", marginRight: 12 }}>{on && <Ic.Check size={15}/>}</span>
      <div className="op-tr-body"><div className="op-tr-title">{title}</div><div className="op-tr-sub">{sub}</div></div>
    </button>
  );

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      {/* 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, background: "var(--status-rejected-soft)", color: "var(--status-rejected-fg)" }}><Ic.Truck size={20}/></span>
        <div><div style={{ fontSize: 15, fontWeight: 600 }}>{E.who} <span className="op-muted" style={{ fontWeight: 500, fontSize: 12.5 }}>· {E.gpn}</span></div><div className="op-gpn" style={{ color: "var(--muted-foreground)" }}>Truck KCD 088X · {E.variety}</div></div>
        <div className="op-ab-spacer" style={{ flex: 1 }}/>
        <span className="badge badge-rejected" style={{ fontSize: 13, padding: "5px 12px" }}><Ic.XCircle size={13}/> Rejected</span>
      </div>

      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ marginBottom: 16 }}>
          <Banner tone="danger" icon={Ic.XCircle} title="Procurement rejected this load"
            desc="Confirm the physical return checklist below, then route the truck to gate exit. A rejected truck must exit without a weighbridge stop."/>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, alignItems: "start" }}>
          {/* Left — read-only context */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="op-card flush">
              <div className="op-card-head" style={{ paddingBottom: 8 }}><div className="op-card-title" style={{ fontSize: 14 }}>QC result</div></div>
              <SRow k="Mean DM" v="19.4% (below 25% min)"/>
              <SRow k="Mean FFA" v="0.90%"/>
              <SRow k="Visual" v="Anthracnose on ~15% of sample"/>
              <SRow k="Inspector" v={QD.INSPECTOR.name}/>
            </div>
            <div className="op-card op-card-pad">
              <div className="op-card-title" style={{ fontSize: 14, marginBottom: 8 }}>Procurement rejection</div>
              <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, marginBottom: 4 }}>REASON</div>
              <div style={{ fontSize: 13, lineHeight: 1.5, marginBottom: 10 }}>Quality below threshold — dry matter far below minimum; contamination visible. Notes: wrong maturity, not usable for intake.</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 11px", borderRadius: "var(--radius-md)", background: "var(--success-soft)" }}>
                <Ic.Phone size={15} style={{ color: "var(--success)" }}/>
                <span style={{ fontSize: 12.5 }}>SMS sent to {E.who} at 09:41 with the reason.</span>
              </div>
            </div>
          </div>

          {/* Right — return checklist + signature */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="op-card flush">
              <div className="op-card-head" style={{ paddingBottom: 6 }}><div className="op-card-title" style={{ fontSize: 14 }}>Return checklist</div></div>
              <Check on={checks.sample} onClick={() => toggle("sample")} title="Sample returned to farmer" sub="The sample taken at QC goes back with the load."/>
              <Check on={checks.load} onClick={() => toggle("load")} title="Truck load intact" sub="Full load leaving — nothing offloaded."/>
              {!refused && <Check on={checks.ack} onClick={() => toggle("ack")} title="Farmer acknowledged rejection" sub="Optional signature captured below."/>}
            </div>

            {refused ? (
              <div className="op-card op-card-pad">
                <div className="op-card-title" style={{ fontSize: 14, marginBottom: 8 }}>Circumstances</div>
                <textarea className="op-textarea" placeholder="Farmer refused to acknowledge — record what happened…" defaultValue="Farmer disputes the reading and declined to sign. Advised to contact procurement."/>
              </div>
            ) : (
              <div className="op-card op-card-pad">
                <div className="op-card-title" style={{ fontSize: 14, marginBottom: 8 }}>Farmer signature <span className="op-muted" style={{ fontWeight: 500 }}>· optional</span></div>
                <div style={{ height: 110, borderRadius: "var(--radius-lg)", border: "1.5px dashed var(--border)", background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted-foreground)", fontSize: 13, gap: 8 }}>
                  {checks.ack ? <span style={{ fontFamily: "cursive", fontSize: 24, color: "var(--foreground)" }}>G. Wambui</span> : <><Ic.Edit size={16}/>Sign here</>}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="op-actionbar" style={{ gap: 12 }}>
        <Btn variant="ghost" icon={Ic.Phone} onClick={() => go("flagReject")}>Call farmer</Btn>
        <Btn variant="outline" icon={Ic.Warning} onClick={() => go("queue")}>Escalate to procurement</Btn>
        <div className="op-ab-grow"/>
        <Btn variant="primary" icon={Ic.Truck} disabled={!allChecked} onClick={() => go("queue")}>Route to gate exit</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  flagReject: { chrome: "flow", title: "Incoming QC — flag rejected", sub: "Route rejected truck to gate exit", back: "queue", render: (ctx) => <QcFlagReject {...ctx}/> },
});
