// OPT-GATE-03 · Scan result — matched
const ScanMatchScreen = ({ t, go }) => {
  const { Btn, Strip, Banner, OrderCard, Pill, Modal } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.scanMatch; // ontime | early | late | grace | already
  const order = FD.ORDER;
  const [reject, setReject] = useState(false);
  const [override, setOverride] = useState(false);
  const [unlocked, setUnlocked] = useState(false);

  const grace = state === "grace";
  const strip = grace
    ? { tone: "warning", icon: Ic.Warning, title: "Outside grace window", sub: "Arriving 2h 10m after slot · supervisor override required" }
    : { tone: "success", icon: Ic.CheckCircle, title: "Arrived", sub: "Scanned just now · linked to " + order.id };

  const slot = state === "early" ? ["pending", "Early · 40m before slot"]
    : state === "late" ? ["pending", "Late · 35m after slot"]
    : grace ? ["rejected", "2h 10m after slot"]
    : ["approved", "On time"];

  const canContinue = !grace || unlocked;

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <Strip {...strip}/>
      <div className="op-pad" style={{ flex: 1 }}>
        {state === "early" && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.Clock} title="Arriving 40 minutes before slot start" desc="Within the ±60 min grace window. You can continue — a note is added to the entry."/></div>}
        {state === "late" && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.Clock} title="Arriving 35 minutes after slot start" desc="Within the ±60 min grace window. You can continue — a note is added to the entry."/></div>}
        {state === "already" && <div style={{ marginBottom: 16 }}><Banner tone="info" icon={Ic.Info} title="This pass was already used at 08:18" desc="Re-scanning the same GPN. Mark as an accidental re-scan, or escalate as a possible duplicate."><div style={{ display: "flex", gap: 8, marginTop: 10 }}><Btn variant="outline" size="sm">Accidental re-scan</Btn><Btn variant="ghost" size="sm">Escalate</Btn></div></Banner></div>}
        {grace && <div style={{ marginBottom: 16 }}><Banner tone="danger" icon={Ic.Warning} title="Beyond the configured grace period" desc="A gate supervisor must authorize this entry with a PIN. Both the override and the late arrival are logged.">{!unlocked && <div style={{ marginTop: 10 }}><Btn variant="destructive" size="sm" icon={Ic.Lock || Ic.HelpCircle} onClick={() => setOverride(true)}>Request supervisor override</Btn></div>}{unlocked && <div style={{ marginTop: 8, color: "var(--success)", fontSize: 12.5, fontWeight: 600, display: "flex", alignItems: "center", gap: 6 }}><Ic.CheckCircle size={15}/> Override authorized — you can continue</div>}</Banner></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, alignItems: "start" }}>
          <div>
            <div className="op-sec"><span className="op-sec-title">Linked delivery order</span><Pill tone={slot[0]} dot>{slot[1]}</Pill></div>
            <OrderCard order={order}/>
          </div>
          <div>
            <div className="op-sec"><span className="op-sec-title">Next: capture & verify</span></div>
            <div className="op-card op-card-pad" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {[["Driver & ID photos", Ic.User], ["Truck front photo", Ic.Truck], ["3-point verification", Ic.CheckCircle]].map(([label, I2], i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--muted-foreground)" }}>
                  <span className="op-row-thumb" style={{ width: 38, height: 38, background: "var(--muted)", color: "var(--muted-foreground)" }}>{React.createElement(I2, { size: 18 })}</span>
                  <span style={{ fontSize: 13.5, fontWeight: 500 }}>{label}</span>
                  <span style={{ marginLeft: "auto", fontSize: 11.5 }}>Pending</span>
                </div>
              ))}
              <div className="op-divider" style={{ margin: "4px 0" }}/>
              <div className="op-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>Tier A farmer · 18 prior deliveries · 0 disputes. Informational only.</div>
              <div style={{ display: "flex", gap: 9, padding: "10px 12px", borderRadius: "var(--radius-md)", background: "var(--info-soft)", marginTop: 4 }}>
                <Ic.ClipboardList size={16} style={{ color: "var(--info-fg)", flexShrink: 0, marginTop: 1 }}/>
                <span style={{ fontSize: 12.5, lineHeight: 1.45, color: "var(--info-fg)" }}>After verification this truck routes to <b>incoming QC</b> — not the weighbridge. The weighbridge only follows if procurement accepts.</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="op-actionbar">
        <Btn variant="destructive" icon={Ic.X} onClick={() => setReject(true)}>Reject (mismatch)</Btn>
        <div className="op-ab-grow"/>
        <Btn variant="outline" icon={Ic.Refresh} onClick={() => go("scan")}>Re-scan</Btn>
        <Btn variant="primary" iconRight={Ic.ChevronRight} disabled={!canContinue} onClick={() => go("captureDriver")}>Continue to verification</Btn>
      </div>

      <Modal open={reject} onClose={() => setReject(false)} title="Reject this truck?" desc="Select a reason. This is logged to the audit trail and the truck is turned away."
        actions={<><Btn variant="ghost" block onClick={() => setReject(false)}>Cancel</Btn><Btn variant="destructive" block onClick={() => { setReject(false); go("dashboard"); }}>Confirm reject</Btn></>}>
        <div className="op-field"><div className="op-label">Reason <span className="req">*</span></div>
          <div className="op-select-wrap"><select className="op-select"><option>Wrong document</option><option>Out of slot</option><option>No order linked</option><option>Driver / vehicle suspect</option><option>Other</option></select><span className="op-select-chev"><Ic.ChevronDown size={18}/></span></div>
        </div>
      </Modal>

      <window.Op.OverrideModal open={override} onClose={() => setOverride(false)} condition="Arrival is 2h 10m past the slot window — beyond the ±60 min grace period."
        onConfirm={() => { setOverride(false); setUnlocked(true); }}/>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  scanMatch: { chrome: "flow", title: "Scan result", sub: "Verify the linked order", back: "scan", render: (ctx) => <ScanMatchScreen {...ctx}/> },
});
