/* ============================================================
   HQ — Airport board (pre-scheduled flight trips)
   Arrivals (inbound pickups) + Departures (hotel→airport),
   with capacity batching: assign several flights to one van.
   ============================================================ */

const BATCH_WINDOW_MIN = 45;   // trips within this gap form a batch window
const DEP_AIRPORT_BUFFER = 120; // be at airport this many min before departure
const DEP_TRAVEL_MIN = 45;      // hotel → airport travel estimate

function hotelsOf(state) { return state.locations.filter((l) => l.kind === "hotel" || l.kind === "venue"); }

function groupWindows(list) {
  const out = [];
  let cur = null;
  list.forEach((r) => {
    if (!cur || r.time - cur.end > BATCH_WINDOW_MIN * 60000) {
      cur = { start: r.time, end: r.time, items: [r] };
      out.push(cur);
    } else { cur.items.push(r); cur.end = r.time; }
  });
  return out;
}

function FlightCard({ state, ride, dir, selected, selectable, onToggle }) {
  const driver = state.drivers.find((d) => d.id === ride.driverId);
  const vehicle = driver && state.vehicles.find((v) => v.id === driver.vehicleId);
  const mins = Math.round((ride.time - Date.now()) / 60000);
  const urgent = dir === "dep" && ride.status === "requested" && mins <= 30;
  const veryUrgent = dir === "dep" && ride.status === "requested" && mins <= 10;

  return (
    <div className={"fcard" + (selected ? " sel" : "") + (selectable ? " selectable" : "")}
      onClick={() => selectable && onToggle(ride.id)}>
      {selectable && <span className={"fc-check" + (selected ? " on" : "")}>{selected ? <Icon name="check" style={{ width: 13, height: 13 }} /> : null}</span>}
      <div className="fc-main">
        <div className="fc-top">
          <span className="flight-badge"><Icon name="plane" style={{ width: 12, height: 12 }} />{ride.flight || "Flight"}</span>
          <span className="fc-party"><Icon name="user" style={{ width: 12, height: 12 }} />{ride.party}</span>
          {ride.batchId && <span className="fc-batch">shared van</span>}
        </div>
        <div className="fc-guest">{ride.guestName || (state.guests.find((g) => g.id === ride.guestId) || {}).name || "Guest"}</div>
        <div className="fc-route">{locName(Store, ride.from)} <span className="ar">→</span> {locName(Store, ride.to)}</div>

        {dir === "arr" ? (
          <div className="fc-time"><Icon name="plane" style={{ width: 13, height: 13 }} /> Lands {fmtTime(ride.flightTime || ride.time)}</div>
        ) : (
          <div className={"fc-time" + (veryUrgent ? " rose" : urgent ? " amber" : "")}>
            <Icon name="clock" style={{ width: 13, height: 13 }} /> Leave by <b>{fmtTime(ride.time)}</b>
            <span className="fc-sub">· wheels up {fmtTime(ride.flightTime)}</span>
          </div>
        )}
      </div>
      <div className="fc-status">
        {ride.status === "requested"
          ? <Pill tone="amber">Unassigned</Pill>
          : <span className="fc-driver"><Avatar initials={driver ? driver.initials : "?"} tone="sky" size={24} /><span className="mono">{vehicle ? vehicle.name : ""}</span></span>}
      </div>
    </div>
  );
}

function FlightColumn({ state, title, sub, dir, list, sel, onToggle }) {
  const wins = groupWindows(list);
  const maxCap = Math.max(0, ...state.vehicles.map((v) => v.cap));
  return (
    <div className="fcol">
      <div className="fcol-h">
        <div><h3>{title}</h3><div className="faint" style={{ fontSize: 11.5 }}>{sub}</div></div>
        <span className="count">{list.length}</span>
      </div>
      <div className="fcol-body">
        {list.length === 0 && <div className="empty">Nothing scheduled.</div>}
        {wins.map((w, i) => {
          const total = w.items.reduce((n, r) => n + r.party, 0);
          const openCount = w.items.filter((r) => r.status === "requested").length;
          return (
            <div className="fwin" key={i}>
              <div className="fwin-h">
                <span className="fwin-time mono">{fmtTime(w.start)}{w.end !== w.start ? "–" + fmtTime(w.end) : ""}</span>
                <span className="fwin-meta">{total} guest{total === 1 ? "" : "s"}{openCount > 1 ? ` · ${openCount} to assign` : ""}</span>
                {openCount > 1 && <span className={"fwin-fit" + (total <= maxCap ? "" : " over")}>{total <= maxCap ? "fits one van" : "needs 2+ vans"}</span>}
              </div>
              {w.items.map((r) => (
                <FlightCard key={r.id} state={state} ride={r} dir={dir}
                  selectable={r.status === "requested"} selected={sel.ids.has(r.id)} onToggle={onToggle} />
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function AssignBar({ state, sel, onClear }) {
  if (!sel.ids.size) return null;
  const ids = [...sel.ids];
  const total = ids.reduce((n, id) => { const r = state.rides.find((x) => x.id === id); return n + (r ? r.party : 0); }, 0);
  const fitting = state.vehicles
    .map((v) => ({ v, d: state.drivers.find((x) => x.vehicleId === v.id) }))
    .filter((x) => x.d && x.v.cap >= total)
    .sort((a, b) => a.v.cap - b.v.cap)
    .slice(0, 4);
  const assign = (driverId) => { Store.assignBatch(ids, driverId); onClear(); };
  return (
    <div className="assign-bar">
      <div className="ab-info">
        <span className="ab-n">{total}</span>
        <div><div className="ab-l">guest{total === 1 ? "" : "s"} selected</div><div className="faint" style={{ fontSize: 11 }}>{ids.length} trip{ids.length === 1 ? "" : "s"} · one van run</div></div>
      </div>
      <div className="ab-vans">
        {fitting.length === 0
          ? <span className="ab-none">No single van seats {total} — split the run.</span>
          : fitting.map(({ v, d }) => (
              <button key={v.id} className="ab-van" onClick={() => assign(d.id)}>
                <span className="ab-van-name mono">{v.name}</span>
                <span className="ab-van-cap">{v.cap} seats · {d.name.split(" ")[0]}</span>
              </button>
            ))}
      </div>
      <button className="ab-clear" onClick={onClear}>Clear</button>
    </div>
  );
}

function AirportBoard({ state }) {
  const [sel, setSel] = useState({ dir: null, ids: new Set() });
  const [adding, setAdding] = useState(false);

  const arrivals = state.rides.filter((r) => r.scheduled && r.type === "airport_pickup").sort((a, b) => a.time - b.time);
  const departures = state.rides.filter((r) => r.scheduled && r.type === "hotel_airport").sort((a, b) => a.time - b.time);

  const toggle = (dir) => (id) => setSel((s) => {
    const ids = new Set(s.dir === dir ? s.ids : []);
    if (ids.has(id)) ids.delete(id); else ids.add(id);
    return { dir, ids };
  });
  const clear = () => setSel({ dir: null, ids: new Set() });

  return (
    <>
      <div className="airport-head">
        <div className="faint" style={{ fontSize: 12.5, maxWidth: 560, lineHeight: 1.45 }}>
          Pre-arranged flight runs. Select several flights in a window and assign them to <b>one van</b> to max capacity when arrivals or departures are close together.
        </div>
        <div className="spacer" />
        <button className="btn btn-primary btn-sm" onClick={() => setAdding(true)}><Icon name="plus" style={{ width: 15, height: 15 }} /> Add flight</button>
      </div>

      <div className="airport-grid">
        <FlightColumn state={state} title="Arrivals" sub="Inbound — airport → hotel" dir="arr"
          list={arrivals} sel={sel.dir === "arr" ? sel : { ids: new Set() }} onToggle={toggle("arr")} />
        <FlightColumn state={state} title="Departures" sub="Hotel → airport, by leave-by time" dir="dep"
          list={departures} sel={sel.dir === "dep" ? sel : { ids: new Set() }} onToggle={toggle("dep")} />
      </div>

      <AssignBar state={state} sel={sel} onClear={clear} />
      {adding && <AddFlightModal state={state} onClose={() => setAdding(false)} />}
    </>
  );
}

function AddFlightModal({ state, onClose }) {
  const [kind, setKind] = useState("arr");
  const [flight, setFlight] = useState("");
  const [guestName, setGuestName] = useState("");
  const [party, setParty] = useState(1);
  const hotels = hotelsOf(state);
  const [hotel, setHotel] = useState(hotels[0] ? hotels[0].id : "");
  const [mins, setMins] = useState(kind === "arr" ? 90 : 240);

  const flightTime = Date.now() + Number(mins) * 60000;
  const leaveBy = flightTime - (DEP_AIRPORT_BUFFER + DEP_TRAVEL_MIN) * 60000;
  const airportBy = flightTime - DEP_AIRPORT_BUFFER * 60000;

  const save = () => {
    if (kind === "arr") {
      Store.addScheduledTrip({ type: "airport_pickup", guestId: null, guestName: guestName.trim(), from: "apt", to: hotel, party: Number(party), time: flightTime, flightTime, flight: flight.trim() });
    } else {
      Store.addScheduledTrip({ type: "hotel_airport", guestId: null, guestName: guestName.trim(), from: hotel, to: "apt", party: Number(party), time: leaveBy, flightTime, deadline: airportBy, flight: flight.trim() });
    }
    onClose();
  };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-h"><h3>Schedule a flight trip</h3><div className="x" onClick={onClose}>✕</div></div>
        <div className="modal-b" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="seg-mini">
            <button className={kind === "arr" ? "active" : ""} onClick={() => { setKind("arr"); setMins(90); }}>Arrival (pickup)</button>
            <button className={kind === "dep" ? "active" : ""} onClick={() => { setKind("dep"); setMins(240); }}>Departure (drop-off)</button>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><label className="lbl">Flight number</label><input className="field mono" value={flight} onChange={(e) => setFlight(e.target.value)} placeholder="e.g. DL 482" autoFocus /></div>
            <div><label className="lbl">Party size</label><input className="field" type="number" min="1" value={party} onChange={(e) => setParty(e.target.value)} /></div>
          </div>
          <div><label className="lbl">Guest / group name</label><input className="field" value={guestName} onChange={(e) => setGuestName(e.target.value)} placeholder="e.g. Pastor Cole Daniels" /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 12 }}>
            <div><label className="lbl">{kind === "arr" ? "Drop at hotel" : "Pick up from hotel"}</label>
              <select className="field" value={hotel} onChange={(e) => setHotel(e.target.value)}>
                {hotels.map((h) => <option key={h.id} value={h.id}>{h.name}</option>)}
              </select>
            </div>
            <div><label className="lbl">{kind === "arr" ? "Lands in (min)" : "Departs in (min)"}</label>
              <input className="field" type="number" min="0" value={mins} onChange={(e) => setMins(e.target.value)} /></div>
          </div>

          <div className="flight-calc">
            {kind === "arr" ? (
              <div className="fc-row"><Icon name="plane" style={{ width: 14, height: 14, color: "var(--violet)" }} /> Lands <b>{fmtTime(flightTime)}</b> · pick up at airport → {locName(Store, hotel)}</div>
            ) : (
              <>
                <div className="fc-row"><Icon name="plane" style={{ width: 14, height: 14, color: "var(--violet)" }} /> Departs <b>{fmtTime(flightTime)}</b></div>
                <div className="fc-row"><Icon name="clock" style={{ width: 14, height: 14, color: "var(--amber)" }} /> At airport by <b>{fmtTime(airportBy)}</b> · leave {locName(Store, hotel)} by <b>{fmtTime(leaveBy)}</b></div>
              </>
            )}
          </div>

          <div style={{ display: "flex", gap: 9, justifyContent: "flex-end" }}>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button className="btn btn-primary" onClick={save} disabled={!flight.trim()}><Icon name="plus" style={{ width: 16, height: 16 }} /> Add to schedule</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AirportBoard });
