// OPT-GATE-07 · Truck verification checklist
const VerifyScreen = ({ t, go }) => {
  const { Btn, Banner, Stepper, Modal, OverrideModal, PhotoTile } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.verify; // pending | allMatch | mismatch
  const src = t.entrySrc || "app"; // app (farmer-app pass) | manual (gate-generated GNP)
  const order = FD.ORDER;

  const init = state === "allMatch" ? ["match", "match", "match"] : state === "mismatch" ? ["match", "fail", "match"] : [null, null, null];
  const [m, setM] = useState(init);
  useEffect(() => { setM(init); }, [state]);
  const set = (i, v) => setM(arr => arr.map((x, j) => j === i ? v : x));

  const [reject, setReject] = useState(false);
  const [override, setOverride] = useState(false);
  const [unlocked, setUnlocked] = useState(false);
  const [admitted, setAdmitted] = useState(false);

  const anyFail = m.includes("fail");
  const allMatch = m.every(x => x === "match");
  const ready = allMatch || unlocked;

  const cards = [
    { icon: Ic.User, title: "Driver match", detail: `Expected: ${order.driver}`, sub: "Face + ID photo vs. expected name" },
    { icon: Ic.Truck, title: "Vehicle match", detail: `Plate: ${order.truck}`, sub: "Truck photo vs. plate on file" },
    { icon: Ic.Leaf, title: "Supplier match", detail: `${order.who} · ${order.product}`, sub: `Expected ${FD.KG(order.qty)}` },
  ];

  return (
    <>
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "center", margin: "4px 0 18px" }}>
          <Stepper steps={["Capture", "Verify"]} current={1}/>
        </div>

        {src === "manual"
          ? <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.Edit} title="Manual entry — no app gate pass" desc="No farmer-app GNP was found for this truck. A GNP will be generated here (OPT-GATE-08) once the truck passes verification."/></div>
          : <div style={{ marginBottom: 16 }}><Banner tone="info" icon={Ic.QR} title="Gate pass from the farmer app" desc={`${order.gpn} was generated when the farmer confirmed the slot. Verify the truck against the pass and allow entry — the gate does not create a new pass.`}/></div>}

        {anyFail && !unlocked && <div style={{ marginBottom: 16 }}><Banner tone="danger" icon={Ic.Warning} title="Mismatch detected" desc="Provide anomaly details and reject, or request a supervisor override to continue. The mismatch is logged either way."/></div>}
        {unlocked && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.CheckCircle} title="Supervisor override authorized" desc="The override and the original mismatch are recorded against the GPN."/></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, alignItems: "start" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {cards.map((c, i) => (
              <div key={i} className={`op-check-card ${m[i] === "match" ? "match" : m[i] === "fail" ? "fail" : ""}`}>
                <span className="op-check-num">{i + 1}</span>
                <span className="op-check-thumb"><c.icon size={26}/></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 600 }}>{c.title}</div>
                  <div style={{ fontSize: 13, fontWeight: 500, marginTop: 2 }}>{c.detail}</div>
                  <div className="op-muted" style={{ fontSize: 12, marginTop: 1 }}>{c.sub}</div>
                </div>
                <div className="op-check-toggle">
                  <button className={`op-mbtn match ${m[i] === "match" ? "on" : ""}`} onClick={() => set(i, "match")}><Ic.Check size={17}/> Match</button>
                  <button className={`op-mbtn fail ${m[i] === "fail" ? "on" : ""}`} onClick={() => set(i, "fail")}><Ic.X size={17}/> No</button>
                </div>
              </div>
            ))}
          </div>

          <div>
            <div className="op-card op-card-pad">
              <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 4 }}>Anything unusual?</div>
              <div className="op-muted" style={{ fontSize: 12, marginBottom: 12, lineHeight: 1.45 }}>{anyFail ? "Required — describe the mismatch." : "Optional anomaly note + evidence."}</div>
              <textarea className="op-textarea" placeholder="e.g. plate differs from order by one digit…" style={{ marginBottom: 12 }}/>
              <PhotoTile label="Add evidence photo" hint="Optional" aspect="16 / 9" onTap={() => {}}/>
              <div className="op-divider"/>
              <div className="op-muted" style={{ fontSize: 11.5, lineHeight: 1.5 }}>This step is the audit anchor — every entry passes through here, whether QR-scanned or manual.</div>
            </div>
          </div>
        </div>
      </div>
      </div>

      <div className="op-actionbar">
        <Btn variant="destructive" icon={Ic.X} onClick={() => setReject(true)}>Reject entry</Btn>
        {anyFail && !unlocked && <Btn variant="ghost" icon={Ic.HelpCircle} onClick={() => setOverride(true)}>Supervisor override</Btn>}
        <div className="op-ab-grow"/>
        {src === "manual"
          ? <Btn variant="primary" icon={Ic.QR} disabled={!ready} onClick={() => go("generatePass")}>Generate gate pass</Btn>
          : <Btn variant="primary" icon={Ic.Truck} disabled={!ready} onClick={() => setAdmitted(true)}>Allow entry</Btn>}
      </div>

      <Modal open={admitted} onClose={() => setAdmitted(false)} title="Entry authorized"
        desc={`Truck admitted on ${order.gpn}. Direct the driver to QC for the dry matter test.`}
        actions={<><Btn variant="ghost" block onClick={() => setAdmitted(false)}>Back</Btn><Btn variant="primary" block icon={Ic.Check} onClick={() => go("dashboard")}>Done</Btn></>}>
        <div className="op-muted" style={{ fontSize: 12.5, lineHeight: 1.5 }}>Other trucks listed on this GNP are verified and admitted the same way.</div>
      </Modal>

      <Modal open={reject} onClose={() => setReject(false)} title="Reject entry?" desc="Provide a reason. Logged to audit; 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></>}/>
      <OverrideModal open={override} onClose={() => setOverride(false)} condition="One or more checks were marked as 'Doesn't match'."
        onConfirm={() => { setOverride(false); setUnlocked(true); }}/>
    </>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  verify: { chrome: "flow", title: "Verify before entry", sub: "Step 2 of 2", back: "captureDriver", render: (ctx) => <VerifyScreen {...ctx}/> },
});
