// OPT-GATE-14 · Active trucks on site
const ActiveTrucksScreen = ({ t, go }) => {
  const { Btn, Banner, Pill, Modal, Toast } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.activeTrucks; // default | empty | noResults | longDwell
  const [sel, setSel] = useState([]);
  const [filter, setFilter] = useState(state === "longDwell" ? "dwell" : "all");
  const [exited, setExited] = useState(() => new Set());
  const [confirmList, setConfirmList] = useState(null); // trucks pending gate-out confirmation
  const [toast, setToast] = useState("");
  useEffect(() => { setFilter(state === "longDwell" ? "dwell" : "all"); setSel([]); }, [state]);

  // A truck can be gated out once its on-site process is complete.
  const readyToExit = (r) => r.stage === "Warehouse" || r.stage === "Loading bay";
  const doGateOut = () => {
    const ids = confirmList.map(r => r.id);
    setExited(prev => { const n = new Set(prev); ids.forEach(id => n.add(id)); return n; });
    setSel(s => s.filter(id => !ids.includes(id)));
    setToast(confirmList.length === 1 ? `Gate-out confirmed · ${confirmList[0].plate}` : `${confirmList.length} trucks gated out`);
    setConfirmList(null);
    setTimeout(() => setToast(""), 2200);
  };

  let rows = state === "empty" ? [] : FD.ACTIVE;
  if (state === "noResults") rows = [];
  else if (filter === "in") rows = rows.filter(r => r.dir === "in");
  else if (filter === "out") rows = rows.filter(r => r.dir === "out");
  else if (filter === "dwell") rows = rows.filter(r => r.elapsedMin >= 240);
  rows = rows.filter(r => !exited.has(r.id));

  const longCount = FD.ACTIVE.filter(r => r.elapsedMin >= 240 && !exited.has(r.id)).length;
  const toggle = (id) => setSel(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);

  const chips = [["all", "All", FD.ACTIVE.length], ["in", "Inbound", FD.ACTIVE.filter(r => r.dir === "in").length], ["out", "Outbound", FD.ACTIVE.filter(r => r.dir === "out").length], ["dwell", ">4h dwell", longCount]];

  return (
    <>
    <div className="op-body">
      <div className="op-pad">
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.02em" }}>Active trucks</div>
            <div className="op-muted" style={{ fontSize: 12.5 }}>{state === "empty" ? "None on site" : `${FD.ACTIVE.length} trucks inside the facility`}</div>
          </div>
          <div className="op-ab-grow"/>
          <div className="op-search sm" style={{ width: 280 }}><span className="op-search-ic"><Ic.Search size={16}/></span><input className="op-input" style={{ height: 44 }} placeholder="GPN, plate, farmer…"/></div>
          <Btn variant="outline" size="sm" icon={Ic.Download}>Export</Btn>
        </div>

        <div className="op-chips" style={{ marginBottom: 14 }}>
          {chips.map(([k, l, n]) => <button key={k} className={`op-chip ${filter === k ? "on" : ""}`} onClick={() => setFilter(k)}>{l} <span className="op-chip-count">{n}</span></button>)}
        </div>

        {longCount > 0 && state !== "empty" && <div style={{ marginBottom: 14 }}><Banner tone="warning" icon={Ic.Clock} title={`${longCount} trucks have been on site over 4 hours`} desc="Cross-shift handoff artifact — review before end of shift."><div style={{ marginTop: 8 }}><Btn variant="outline" size="sm" onClick={() => setFilter("dwell")}>Jump to long-dwell</Btn></div></Banner></div>}

        {rows.length === 0 ? (
          <div className="op-card"><div className="op-empty" style={{ padding: "56px 24px" }}>
            <div className="op-empty-art"><Ic.Truck size={42}/></div>
            <div className="op-empty-title">{state === "noResults" ? "No trucks match these filters" : "No trucks on site"}</div>
            <div className="op-empty-desc">{state === "noResults" ? "Try widening the filters." : "The facility is clear. Scanned arrivals will appear here."}</div>
            {state === "noResults" && <div style={{ marginTop: 16 }}><Btn variant="outline" onClick={() => setFilter("all")}>Clear filters</Btn></div>}
          </div></div>
        ) : (
          <div className="op-tbl-wrap">
            <table className="op-tbl">
              <thead><tr>
                <th style={{ width: 36 }}></th><th>GPN</th><th>Plate</th><th>Dir</th><th>Farmer / Buyer</th><th>Product</th><th className="num">Net qty</th><th>Stage</th><th>Entered</th><th>Dwell</th><th></th>
              </tr></thead>
              <tbody>
                {rows.map(r => {
                  const d = FD.dwell(r.elapsedMin);
                  return (
                    <tr key={r.id} className={sel.includes(r.id) ? "selected" : ""} onClick={() => go("movementLog")}>
                      <td onClick={(e) => { e.stopPropagation(); toggle(r.id); }}><span style={{ width: 20, height: 20, borderRadius: 6, border: "2px solid var(--input)", display: "inline-flex", alignItems: "center", justifyContent: "center", background: sel.includes(r.id) ? "var(--avocado)" : "var(--card)", borderColor: sel.includes(r.id) ? "var(--avocado)" : "var(--input)", color: "#fff" }}>{sel.includes(r.id) && <Ic.Check size={13}/>}</span></td>
                      <td><span className="op-gpn">{r.gpn.replace("GPN-2026", "…")}</span></td>
                      <td className="op-mono" style={{ fontWeight: 600 }}>{r.plate}</td>
                      <td><Pill tone={r.dir === "out" ? "soil" : "avocado"}>{r.dir === "out" ? "Out" : "In"}</Pill></td>
                      <td style={{ fontWeight: 600 }}>{r.who}</td>
                      <td className="op-muted">{r.product}</td>
                      <td className="num">{r.net ? FD.NUM(r.net) : "—"}</td>
                      <td><Pill tone={FD.stageTone(r.stage)}>{r.stage}</Pill></td>
                      <td className="num op-muted">{r.entered}</td>
                      <td><span className={`op-dwell ${d.tone}`}><Ic.Clock size={13}/> {d.txt}</span></td>
                      <td onClick={(e) => e.stopPropagation()} style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                        {readyToExit(r)
                          ? <Btn size="sm" variant="outline" icon={Ic.ArrowUp} onClick={() => setConfirmList([r])}>Gate-out</Btn>
                          : <span className="op-muted" style={{ fontSize: 12 }}>In process</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
      </div>

      {sel.length > 0 && (
        <div className="op-actionbar dock">
          <span style={{ fontSize: 13.5, fontWeight: 600 }}>{sel.length} selected</span>
          <div className="op-ab-grow"/>
          <Btn variant="ghost" onClick={() => setSel([])}>Clear</Btn>
          <Btn variant="primary" icon={Ic.Send} onClick={() => {
            const n = sel.length;
            setSel([]);
            setToast(n === 1 ? "1 truck sent to next checkpoint" : `${n} trucks sent to next checkpoint`);
            setTimeout(() => setToast(""), 2200);
          }}>Send to checkpoint</Btn>
        </div>
      )}

      {/* Gate-out confirmation (single row or bulk) */}
      <Modal open={!!confirmList} onClose={() => setConfirmList(null)} title={confirmList && confirmList.length === 1 ? "Confirm gate-out?" : "Confirm gate-out for selected trucks?"}
        desc="This records the exit and removes the truck from the on-site list. Logged to the movement log."
        actions={<><Btn variant="ghost" block onClick={() => setConfirmList(null)}>Cancel</Btn><Btn variant="primary" block icon={Ic.ArrowUp} onClick={doGateOut}>Confirm gate-out</Btn></>}>
        {confirmList && (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {confirmList.map(r => (
              <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: "var(--radius-lg)", background: "var(--surface)", border: "1px solid var(--border)" }}>
                <span className="op-row-thumb" style={{ width: 34, height: 34 }}><Ic.Truck size={17}/></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{r.plate} · <span className="op-muted" style={{ fontWeight: 500 }}>{r.who}</span></div>
                  <div className="op-muted" style={{ fontSize: 12 }}>{r.stage} · dwell {FD.dwell(r.elapsedMin).txt}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Modal>

      <Toast show={!!toast}>{toast}</Toast>
    </>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  activeTrucks: { chrome: "tabs", tab: "Active", render: (ctx) => <ActiveTrucksScreen {...ctx}/> },
});
