// csr-prealerts.jsx — inbound Next Flight freight, per station (destination airport).
const { useState: useStatePA, useMemo: useMemoPA } = React;

function PreAlertConsignment({ r, onOpen }) {
  const { b, info } = r;
  const oa = window.FX.AIRPORTS[info.originState];
  const statusCol = b.status === "In transit" ? "var(--brand)" : "var(--success)";
  return (
    <div onClick={() => onOpen && onOpen(b)} style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr 0.9fr 1fr 0.7fr", gap: 10, padding: "12px 18px", borderTop: "1px solid var(--border)", alignItems: "center", cursor: "pointer", transition: "background 120ms ease" }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--brand)" }}>{b.tracking}</span>
      <span style={{ minWidth: 0 }}>
        <span style={{ display: "block", fontSize: 13, fontWeight: 500, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.customerName}</span>
        <span style={{ display: "block", fontSize: 11, color: "var(--fg-mute)" }}>{b.dropoff.suburb} · {info.items} item{info.items === 1 ? "" : "s"} · {info.weightKg} kg</span>
      </span>
      <span style={{ display: "flex", alignItems: "center", gap: 7 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12.5, color: "var(--fg-strong)" }}>{oa ? oa.code : info.originState}</span>
        <Icon name="arrow-right" size={12} color="var(--fg-faint)" />
        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12.5, color: "var(--fg-strong)" }}>{window.FX.AIRPORTS[info.destState].code}</span>
      </span>
      <span style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
        <span style={{ width: 24, height: 24, borderRadius: "50%", flex: "none", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 10 }}>{info.deliveryDriver.initials}</span>
        <span style={{ fontSize: 12, color: "var(--fg-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{info.deliveryDriver.name}</span>
      </span>
      <span style={{ textAlign: "right" }}><Badge tone={b.status === "In transit" ? "brand" : "success"}><StatusDot color={statusCol} pulse={b.status === "In transit"} /> {b.status}</Badge></span>
    </div>
  );
}

function PreAlertFlight({ g, onOpen }) {
  const info = g.info;
  const f = info.flight;
  const totItems = g.items.reduce((sum, r) => sum + (r.info.items || 0), 0);
  const totKg = Math.round(g.items.reduce((sum, r) => sum + (r.info.weightKg || 0), 0) * 10) / 10;
  return (
    <Card pad={0} style={{ overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", background: "var(--brand)", color: "#fff" }}>
        <span style={{ width: 38, height: 38, borderRadius: 10, flex: "none", background: "rgba(255,255,255,0.15)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="plane" size={19} /></span>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15 }}>{info.flightIata}</span>
            <span style={{ fontSize: 12.5, opacity: 0.85 }}>{f.airline_name || ""}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, opacity: 0.9, marginTop: 2 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{info.dep.code}</span> {info.dep.city}
            <Icon name="arrow-right" size={11} color="rgba(255,255,255,0.7)" />
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{info.arr.code}</span> {info.arr.city}
          </div>
        </div>
        <div style={{ marginLeft: "auto", textAlign: "right" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "1px", opacity: 0.75, textTransform: "uppercase" }}>ETA</div>
          <div style={{ fontFamily: "var(--font-mono)", fontWeight: 800, fontSize: 20 }}>{info.eta}</div>
        </div>
        <div style={{ flex: "none", display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end" }}>
          <span style={{ background: "rgba(255,255,255,0.15)", borderRadius: "var(--r-pill)", padding: "5px 11px", fontSize: 12, fontWeight: 600, whiteSpace: "nowrap" }}>{g.items.length} consignment{g.items.length === 1 ? "" : "s"}</span>
          <span style={{ background: "rgba(255,255,255,0.15)", borderRadius: "var(--r-pill)", padding: "5px 11px", fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="package" size={12} /><span>{totItems} item{totItems === 1 ? "" : "s"} · {totKg} kg</span></span>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr 0.9fr 1fr 0.7fr", gap: 10, padding: "9px 18px", background: "var(--bg-mist)", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.7px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
        <span>Tracking</span><span>Customer</span><span>Route</span><span>Delivery courier</span><span style={{ textAlign: "right" }}>Status</span>
      </div>
      {g.items.map((r, i) => <PreAlertConsignment key={r.b.tracking + i} r={r} onOpen={onOpen} />)}
    </Card>
  );
}

function PreAlertEmail({ ap, flightGroups, byStationList }) {
  const items = byStationList.reduce((s, r) => s + (r.info.items || 0), 0);
  const kg = Math.round(byStationList.reduce((s, r) => s + (r.info.weightKg || 0), 0) * 10) / 10;
  const dateStr = new Date().toLocaleDateString("en-AU", { weekday: "short", day: "numeric", month: "short" });
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden", background: "#fff" }}>
      <div style={{ background: "var(--brand)", color: "#fff", padding: "16px 20px" }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "1.1px", opacity: 0.8, textTransform: "uppercase" }}>Fedex Next Flight · Pre-Alert</div>
        <div style={{ fontSize: 19, fontWeight: 800, marginTop: 4 }}>Inbound to {ap.city} <span style={{ fontFamily: "var(--font-mono)", opacity: 0.85 }}>({ap.code})</span></div>
        <div style={{ fontSize: 12.5, opacity: 0.85, marginTop: 3 }}>{dateStr} · {flightGroups.length} flight{flightGroups.length === 1 ? "" : "s"} · {byStationList.length} consignment{byStationList.length === 1 ? "" : "s"} · {items} items · {kg} kg</div>
      </div>
      <div style={{ padding: "14px 20px" }}>
        {flightGroups.map((g, i) => (
          <div key={i} style={{ marginBottom: i < flightGroups.length - 1 ? 18 : 0 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, paddingBottom: 6, borderBottom: "2px solid var(--brand)" }}>
              <span style={{ fontWeight: 700, fontSize: 13.5, color: "var(--fg-strong)" }}><span style={{ fontFamily: "var(--font-mono)" }}>{g.info.flightIata}</span> · {g.info.dep.code}→{g.info.arr.code}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 700, color: "var(--brand)" }}>ETA {g.info.eta}</span>
            </div>
            {g.items.map((r, j) => (
              <div key={j} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "7px 0", borderBottom: "1px solid var(--border)", fontSize: 12.5 }}>
                <span style={{ fontFamily: "var(--font-mono)", color: "var(--brand)", fontWeight: 600, flex: "none" }}>{r.b.tracking}</span>
                <span style={{ flex: 1, minWidth: 0, color: "var(--fg-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.b.customerName} · {r.b.dropoff.suburb}</span>
                <span style={{ color: "var(--fg-mute)", flex: "none", fontFamily: "var(--font-mono)" }}>{r.info.items}× · {r.info.weightKg}kg</span>
              </div>
            ))}
          </div>
        ))}
      </div>
      <div style={{ padding: "11px 20px", background: "var(--bg-mist)", fontSize: 11, color: "var(--fg-mute)", borderTop: "1px solid var(--border)" }}>Automated pre-alert from Fedex Next Flight operations. ETAs are estimates and subject to change.</div>
    </div>
  );
}

/* Full-screen station board — for the depot wall screen (item 47). Esc or × to close. */
function StationScreen({ ap, flightGroups, totalItems, totalKg, onClose }) {
  const [clock, setClock] = useStatePA(new Date());
  React.useEffect(() => {
    const t = setInterval(() => setClock(new Date()), 1000);
    const esc = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", esc);
    return () => { clearInterval(t); window.removeEventListener("keydown", esc); };
  }, []);
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 400, background: "#0B2240", color: "#fff", display: "flex", flexDirection: "column", padding: "34px 44px", overflowY: "auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 18, marginBottom: 26 }}>
        <span style={{ width: 52, height: 52, borderRadius: 14, background: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="plane" size={26} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "2px", textTransform: "uppercase", opacity: 0.6 }}>Pre-Alerts · Inbound Next Flight freight</div>
          <div style={{ fontSize: 30, fontWeight: 900, letterSpacing: "-0.8px" }}>{ap.city} <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, opacity: 0.75 }}>({ap.code})</span></div>
        </div>
        <div style={{ textAlign: "right", marginRight: 8 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 34, fontWeight: 800, letterSpacing: "1px" }}>{clock.toLocaleTimeString("en-AU", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false })}</div>
          <div style={{ fontSize: 12.5, opacity: 0.6 }}>{flightGroups.length} flight{flightGroups.length === 1 ? "" : "s"} · {totalItems} items · {totalKg} kg inbound</div>
        </div>
        <button onClick={onClose} title="Close (Esc)" style={{ width: 44, height: 44, borderRadius: "50%", border: "1px solid rgba(255,255,255,0.25)", background: "rgba(255,255,255,0.08)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flex: "none" }}><Icon name="x" size={20} /></button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {flightGroups.map(g => (
          <div key={g.info.flightIata} style={{ background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 16, overflow: "hidden" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "15px 22px", borderBottom: "1px solid rgba(255,255,255,0.1)" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 24, fontWeight: 800, color: "var(--accent)" }}>{g.info.flightIata}</span>
              <span style={{ fontSize: 15, opacity: 0.8 }}>{g.info.flight.airline_name || ""}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 17, fontWeight: 700 }}>{g.info.dep.code} → {g.info.arr.code}</span>
              <span style={{ marginLeft: "auto", textAlign: "right" }}>
                <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "1.5px", opacity: 0.55, textTransform: "uppercase" }}>ETA</span>
                <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 26, fontWeight: 800 }}>{g.info.eta}</span>
              </span>
            </div>
            {g.items.map((r, i) => (
              <div key={r.b.tracking} style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr 1fr 0.8fr", gap: 14, padding: "12px 22px", borderTop: i ? "1px solid rgba(255,255,255,0.06)" : "none", alignItems: "center", fontSize: 16 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--accent)", fontSize: 15 }}>{r.b.tracking}</span>
                <span style={{ opacity: 0.9, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.b.customerName} · {r.b.dropoff.suburb}</span>
                <span style={{ opacity: 0.75, fontSize: 14.5 }}>{r.info.deliveryDriver.name}</span>
                <span style={{ fontFamily: "var(--font-mono)", textAlign: "right", opacity: 0.9, fontSize: 14.5 }}>{r.info.items}× · {r.info.weightKg} kg</span>
              </div>
            ))}
          </div>
        ))}
        {flightGroups.length === 0 && <div style={{ padding: 60, textAlign: "center", opacity: 0.6, fontSize: 18 }}>No inbound freight for {ap.city} right now.</div>}
      </div>
    </div>
  );
}

function SendPreAlertModal({ open, onClose, ap, flightGroups, byStationList, recipients, selected, setSelected, onAddRecipient, onSend }) {
  const [newEmail, setNewEmail] = useStatePA("");
  const [pick, setPick] = useStatePA("");
  const validEmail = e => /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test((e || "").trim());
  const available = recipients.filter(r => !selected.includes(r));
  const addNew = () => {
    const e = newEmail.trim().toLowerCase();
    if (!validEmail(e)) return;
    onAddRecipient(e);
    if (!selected.includes(e)) setSelected([...selected, e]);
    setNewEmail("");
  };
  return (
    <Modal open={open} onClose={onClose} title="Send email notification" width={660}>
      {ap && (
        <div>
          <div style={{ fontSize: 13.5, color: "var(--fg-body)", lineHeight: 1.5, marginBottom: 18 }}>Email the current pre-alert for <strong style={{ color: "var(--fg-strong)" }}>{ap.city} ({ap.code})</strong> as an HTML summary. Pick recipients from your saved list or add a new address.</div>

          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.9px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 9 }}>Recipients ({selected.length})</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 14, minHeight: 20 }}>
            {selected.length === 0 && <span style={{ fontSize: 12.5, color: "var(--fg-mute)", fontStyle: "italic" }}>No recipients selected yet.</span>}
            {selected.map(e => (
              <span key={e} style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "var(--brand-soft)", color: "var(--brand)", borderRadius: "var(--r-pill)", padding: "5px 8px 5px 13px", fontSize: 12.5, fontWeight: 500 }}>
                {e}
                <button onClick={() => setSelected(selected.filter(x => x !== e))} style={{ background: "rgba(0,0,0,0.06)", border: "none", borderRadius: "50%", width: 18, height: 18, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--brand)", cursor: "pointer", padding: 0 }}><Icon name="x" size={11} /></button>
              </span>
            ))}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 12, color: "var(--fg-mute)", marginBottom: 6 }}>Add from saved list</div>
              <Select value={pick} onChange={v => { if (v) { setSelected([...selected, v]); setPick(""); } }} placeholder={available.length ? "Choose an address…" : "All added"} options={available.map(e => ({ value: e, label: e }))} />
            </div>
            <div>
              <div style={{ fontSize: 12, color: "var(--fg-mute)", marginBottom: 6 }}>Add a new address</div>
              <div style={{ display: "flex", gap: 8 }}>
                <div style={{ flex: 1, minWidth: 0 }}><TextInput value={newEmail} onChange={setNewEmail} placeholder="name@company.com" /></div>
                <Button variant="secondary" icon="plus" onClick={addNew} disabled={!validEmail(newEmail)}>Add</Button>
              </div>
            </div>
          </div>

          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.9px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 9 }}>Email preview</div>
          <PreAlertEmail ap={ap} flightGroups={flightGroups} byStationList={byStationList} />

          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 22 }}>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" icon="send" disabled={selected.length === 0} onClick={() => onSend(selected)}><span>Send to {selected.length} recipient{selected.length === 1 ? "" : "s"}</span></Button>
          </div>
        </div>
      )}
    </Modal>
  );
}

function PreAlerts({ bookings, onOpen, onNotify }) {
  const rows = useMemoPA(() => bookings
    .filter(b => window.FX.isNextFlight(b) && b.status !== "Cancelled" && b.status !== "Delivered")
    .map(b => ({ b, info: window.FX.nextFlightInfo(b) })), [bookings]);

  const byStation = useMemoPA(() => {
    const m = {};
    rows.forEach(r => { const st = r.info.destState; (m[st] = m[st] || []).push(r); });
    Object.keys(m).forEach(st => m[st].sort((a, b) => (a.info.eta || "").localeCompare(b.info.eta || "")));
    return m;
  }, [rows]);

  const stations = Object.keys(window.FX.AIRPORTS).filter(st => byStation[st] && byStation[st].length);
  const [sel, setSel] = useStatePA(null);
  const active = (sel && byStation[sel]) ? sel : (stations[0] || null);

  const flightGroups = useMemoPA(() => {
    if (!active) return [];
    const m = {};
    byStation[active].forEach(r => { const k = r.info.flightIata; (m[k] = m[k] || { info: r.info, items: [] }).items.push(r); });
    return Object.values(m).sort((a, b) => (a.info.eta || "").localeCompare(b.info.eta || ""));
  }, [active, byStation]);

  const RECIP_LS = "fedexPreAlertRecipients_v1";
  const DEFAULT_RECIPIENTS = ["dispatch@fedex.com.au", "nightsort@fedex.com.au", "linehaul.ops@fedex.com.au"];
  const [recipients, setRecipients] = useStatePA(() => { try { const s = JSON.parse(localStorage.getItem(RECIP_LS)); return Array.isArray(s) && s.length ? s : DEFAULT_RECIPIENTS; } catch (e) { return DEFAULT_RECIPIENTS; } });
  const persistRecipients = list => { setRecipients(list); try { localStorage.setItem(RECIP_LS, JSON.stringify(list)); } catch (e) {} };
  const [sendOpen, setSendOpen] = useStatePA(false);
  const [screenOpen, setScreenOpen] = useStatePA(false);
  const [selected, setSelected] = useStatePA([]);
  const openSend = () => { setSelected(recipients.slice()); setSendOpen(true); };
  const addRecipient = e => { if (!recipients.includes(e)) persistRecipients([...recipients, e]); };
  const handleSend = list => { setSendOpen(false); onNotify && onNotify(`Pre-alert for ${window.FX.AIRPORTS[active].city} emailed to ${list.length} recipient${list.length === 1 ? "" : "s"}`); };

  return (
    <div className="fade-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
        <div>
          <Eyebrow>Operations</Eyebrow>
          <h1 style={{ margin: "9px 0 0", fontSize: 25, fontWeight: 700, letterSpacing: "-0.6px", color: "var(--fg-strong)" }}>Pre-Alerts</h1>
          <p style={{ margin: "7px 0 0", fontSize: 14.5, color: "var(--fg-mute)" }}>Next Flight freight inbound to each station — confirm the flight, ETA and delivery courier before it lands.</p>
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <Button variant="secondary" icon="monitor" onClick={() => setScreenOpen(true)} disabled={!active}>Station screen</Button>
          <Button variant="primary" icon="mail" onClick={openSend} disabled={!active}>Send email notification</Button>
        </div>
      </div>

      {stations.length === 0 ? (
        <Card pad={48} style={{ textAlign: "center", borderStyle: "dashed", background: "var(--bg-mist)" }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 14px", color: "var(--fg-faint)" }}><Icon name="plane" size={26} /></div>
          <div style={{ fontSize: 15.5, fontWeight: 600, color: "var(--fg-strong)" }}>No inbound freight</div>
          <div style={{ fontSize: 13.5, color: "var(--fg-mute)", marginTop: 5 }}>Next Flight bookings will appear here, grouped by the station they're arriving into.</div>
        </Card>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "244px minmax(0,1fr)", gap: 20, alignItems: "start" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, position: "sticky", top: 16 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.9px", textTransform: "uppercase", color: "var(--fg-mute)", padding: "0 4px 2px" }}>Stations</div>
            {stations.map(st => {
              const list = byStation[st]; const ap = window.FX.AIRPORTS[st]; const on = st === active;
              return (
                <button key={st} onClick={() => setSel(st)} style={{ textAlign: "left", padding: "12px 14px", borderRadius: "var(--r-md)", border: "1.5px solid " + (on ? "var(--brand)" : "var(--border)"), background: on ? "var(--brand-soft)" : "var(--surface)", transition: "all 140ms ease" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15, color: on ? "var(--brand)" : "var(--fg-strong)" }}>{ap.code}</span>
                    <span style={{ fontSize: 13, color: "var(--fg-body)", flex: 1 }}>{ap.city}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, minWidth: 22, textAlign: "center", padding: "2px 7px", borderRadius: 999, background: on ? "var(--brand)" : "var(--bg-mist-2)", color: on ? "#fff" : "var(--fg-mute)" }}>{list.length}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--fg-mute)", marginTop: 4 }}>Next arrival <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-body)" }}>{list[0] ? list[0].info.eta : "—"}</span></div>
                </button>
              );
            })}
          </div>

          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <span style={{ width: 34, height: 34, borderRadius: 9, flex: "none", background: "var(--accent-soft)", color: "var(--accent-700)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="map-pin" size={17} /></span>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: "var(--fg-strong)" }}>Inbound to {window.FX.AIRPORTS[active].city} <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-mute)", fontWeight: 600 }}>({window.FX.AIRPORTS[active].code})</span></div>
                <div style={{ fontSize: 12.5, color: "var(--fg-mute)" }}>{flightGroups.length} inbound flight{flightGroups.length === 1 ? "" : "s"} · {byStation[active].length} consignment{byStation[active].length === 1 ? "" : "s"} · {byStation[active].reduce((sum, r) => sum + (r.info.items || 0), 0)} items · {Math.round(byStation[active].reduce((sum, r) => sum + (r.info.weightKg || 0), 0) * 10) / 10} kg</div>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {flightGroups.map(g => <PreAlertFlight key={g.info.flightIata} g={g} onOpen={onOpen} />)}
            </div>
          </div>
        </div>
      )}

      <SendPreAlertModal open={sendOpen} onClose={() => setSendOpen(false)} ap={active ? window.FX.AIRPORTS[active] : null} flightGroups={flightGroups} byStationList={active ? byStation[active] : []} recipients={recipients} selected={selected} setSelected={setSelected} onAddRecipient={addRecipient} onSend={handleSend} />
      {screenOpen && active && (
        <StationScreen ap={window.FX.AIRPORTS[active]} flightGroups={flightGroups}
          totalItems={byStation[active].reduce((s, r) => s + (r.info.items || 0), 0)}
          totalKg={Math.round(byStation[active].reduce((s, r) => s + (r.info.weightKg || 0), 0) * 10) / 10}
          onClose={() => setScreenOpen(false)} />
      )}
    </div>
  );
}

Object.assign(window, { PreAlerts });
