// OPT-GATE-12 · Gate exit — verify
const ExitVerifyScreen = ({ t, go }) => {
  const { Btn, Banner, OrderCard, Modal, OverrideModal, Pill } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.exitVerify; // allClear | pending | exited | rejected
  const order = { ...FD.ORDER, net: 4200 };
  const [incident, setIncident] = useState(false);
  const [override, setOverride] = useState(false);
  const [unlocked, setUnlocked] = useState(false);
  const rejected = state === "rejected";

  const clearances = rejected ? [
    { label: "Procurement rejected", done: true, sub: "Quality below threshold · reason logged" },
    { label: "Sample returned to farmer", done: true, sub: "Confirmed by QC" },
    { label: "Truck load intact", done: true, sub: "Nothing offloaded — no weighbridge stop" },
    { label: "Farmer notified", done: true, sub: "SMS sent at 09:41" },
  ] : [
    { label: "Unload complete", done: true, sub: "Receiving bay C · 10:02" },
    { label: "Tare captured", done: true, sub: "12,220 kg · slip attached" },
    { label: "QC decision recorded", done: state === "allClear", sub: state === "allClear" ? "Passed · Grade 1" : "Awaiting QC result" },
    { label: "GRN linked", done: state === "allClear", sub: state === "allClear" ? "GRN-2026-0512" : "Pending warehouse acceptance" },
  ];
  const allClear = clearances.every(c => c.done);
  const exited = state === "exited";
  const canAuthorize = (allClear || unlocked) && !exited;

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        {exited && <div style={{ marginBottom: 16 }}><Banner tone="neutral" icon={Ic.Info} title="This truck already exited at 10:48" desc="A GPN can only exit once. Subsequent scans are blocked."/></div>}
        {rejected && <div style={{ marginBottom: 16 }}><Banner tone="danger" icon={Ic.XCircle} title="Rejected pre-weighbridge — return exit" desc="Procurement rejected this load after incoming QC. It leaves loaded, with no weight recorded and no payment. A rejected-delivery exit slip is issued."/></div>}
        {!allClear && !exited && !unlocked && !rejected && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.Clock} title="Pending clearances" desc="Exit is blocked until all upstream steps complete. Tap a failed row to jump to it, or request a supervisor override."/></div>}
        {unlocked && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.CheckCircle} title="Override authorized" desc="Proceeding with incomplete clearances — logged against the GPN."/></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 18, alignItems: "start" }}>
          <div>
            <div className="op-sec"><span className="op-sec-title">Truck</span><Pill tone="in-progress">{order.dir === "out" ? "Outbound" : "Inbound"}</Pill></div>
            <OrderCard order={order}/>
            <div className="op-card flush" style={{ marginTop: 14 }}>
              <window.Op.SRow k="GPN" v={<span className="op-gpn">{order.gpn}</span>}/>
              <window.Op.SRow k="Net received" v={FD.KG(order.net)}/>
              <window.Op.SRow k="Entered" v="08:18"/>
              <window.Op.SRow k="Dwell so far" v="2h 30m"/>
            </div>
          </div>

          <div>
            <div className="op-sec"><span className="op-sec-title">{rejected ? "Required checks · rejected return" : "Required clearances · inbound"}</span><span className="op-muted" style={{ fontSize: 12 }}>{clearances.filter(c => c.done).length}/{clearances.length} complete</span></div>
            <div className="op-card flush">
              {clearances.map((c, i) => (
                <div key={i} className="op-srow" style={{ alignItems: "center" }}>
                  <span className="k" style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <span style={{ width: 32, height: 32, borderRadius: 9, display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, background: c.done ? "var(--success-soft)" : "var(--status-rejected-soft)", color: c.done ? "var(--success)" : "var(--status-rejected-fg)" }}>
                      {c.done ? <Ic.Check size={17}/> : <Ic.X size={16}/>}
                    </span>
                    <span><span style={{ color: "var(--foreground)", fontWeight: 600, fontSize: 14 }}>{c.label}</span><br/><span style={{ fontSize: 12 }}>{c.sub}</span></span>
                  </span>
                  {!c.done && <button className="op-sec-link" style={{ color: "var(--destructive)" }}>View step ›</button>}
                </div>
              ))}
            </div>
            <div className="op-muted" style={{ fontSize: 12, marginTop: 12, lineHeight: 1.5 }}>Clearances are computed in real time from QC, warehouse & sales. If the truck is flagged in an incident, exit is blocked regardless.</div>
          </div>
        </div>
      </div>

      <div className="op-actionbar">
        <Btn variant="destructive" icon={Ic.Warning} onClick={() => setIncident(true)}>Cannot exit (incident)</Btn>
        {!allClear && !exited && !unlocked && <Btn variant="ghost" icon={Ic.HelpCircle} onClick={() => setOverride(true)}>Supervisor override</Btn>}
        <div className="op-ab-grow"/>
        <Btn variant="primary" icon={Ic.ArrowUp} disabled={!canAuthorize} onClick={() => go("exitLog")}>{rejected ? "Authorize rejected exit" : "Authorize exit"}</Btn>
      </div>

      <Modal open={incident} onClose={() => setIncident(false)} title="Create exit incident?" desc="The truck remains on site until the incident is resolved."
        actions={<><Btn variant="ghost" block onClick={() => setIncident(false)}>Cancel</Btn><Btn variant="destructive" block onClick={() => { setIncident(false); go("dashboard"); }}>Create incident</Btn></>}/>
      <OverrideModal open={override} onClose={() => setOverride(false)} condition="One or more exit clearances are still pending."
        onConfirm={() => { setOverride(false); setUnlocked(true); }}/>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  exitVerify: { chrome: "flow", title: "Verify exit", sub: "GPN-20260516-0042", back: "dashboard", render: (ctx) => <ExitVerifyScreen {...ctx}/> },
});
