// OPT-GATE-14 · Active trucks on site
const ActiveTrucksScreen = ({ t, go }) => {
  const { Btn, Banner, Pill } = 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");
  useEffect(() => { setFilter(state === "longDwell" ? "dwell" : "all"); setSel([]); }, [state]);

  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);

  const longCount = FD.ACTIVE.filter(r => r.elapsedMin >= 240).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>
              </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>{r.stage}</td>
                      <td className="num op-muted">{r.entered}</td>
                      <td><span className={`op-dwell ${d.tone}`}><Ic.Clock size={13}/> {d.txt}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {sel.length > 0 && (
        <div className="op-actionbar">
          <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}>Send to checkpoint</Btn>
        </div>
      )}
    </div>
  );
};

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