// booking-page.jsx — standalone full booking detail (opened in a new tab from the queue)
const { useState: useStateBP, useEffect: useEffectBP } = React;

const CSR_LS_BP = "fedexCsr_v2";
function bpLoad() { try { return JSON.parse(localStorage.getItem(CSR_LS_BP)) || {}; } catch (e) { return {}; } }
function bpSaveBooking(updated) {
  try {
    const st = bpLoad();
    const bookings = (st.bookings || []).map(b => b.tracking === updated.tracking ? updated : b);
    localStorage.setItem(CSR_LS_BP, JSON.stringify({ ...st, bookings }));
  } catch (e) {}
}
function bpParam(k) {
  try {
    const h = (window.location.hash || "").replace(/^#/, "");
    return new URLSearchParams(h).get(k) || new URLSearchParams(window.location.search).get(k) || "";
  } catch (e) { return ""; }
}
function bpTrackUrl(code, driverName) {
  return "Fedex Track.html#t=" + encodeURIComponent(code || "") + (driverName ? "&driver=" + encodeURIComponent(driverName) : "");
}

function findBooking(code) {
  const c = (code || "").trim().toUpperCase();
  const st = bpLoad();
  const fromLs = (st.bookings || []).find(b => (b.tracking || "").toUpperCase() === c);
  if (fromLs) return fromLs;
  return null;
}

function BookingPage() {
  const code = bpParam("t");
  const [booking, setBooking] = useStateBP(() => findBooking(code));
  const [editing, setEditing] = useStateBP(false);

  function describePatch(patch) {
    if (patch.status === "Cancelled") return "Booking cancelled";
    if (patch.awb !== undefined) return "Airway bill updated";
    if (patch.serviceAgentId) return "Service agent allocated";
    if (patch.serviceAgentId === null) return "Service agent unassigned";
    if (patch.agentStatus === "received") return "Agent confirmed booking information";
    if (patch.agentStatus === "delivered") return "Agent marked booking delivered";
    if (patch.status) return "Status changed to " + patch.status;
    if (patch.notes !== undefined || patch.callLog !== undefined) return "Notes / call log updated";
    return "Booking updated";
  }
  function update(patch) {
    setBooking(prev => {
      const detail = describePatch(patch);
      let audit = [...(prev.audit || [])];
      const last = audit[audit.length - 1];
      const now = new Date().toISOString();
      if (last && last.detail === detail && (new Date(now) - new Date(last.at)) < 120000) {
        audit[audit.length - 1] = { ...last, at: now };                 // collapse rapid repeats (e.g. typing an AWB)
      } else {
        audit.push({ at: now, by: "CE console", action: patch.status === "Cancelled" ? "cancelled" : "edited", detail });
      }
      const next = { ...prev, ...patch, audit };
      bpSaveBooking(next);
      return next;
    });
  }

  if (!booking) {
    return (
      <div style={{ minHeight: "100vh", background: "var(--bg-page)" }}>
        <TopBar />
        <div style={{ maxWidth: 600, margin: "12vh auto 0", textAlign: "center", padding: 24 }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--bg-mist)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 14px", color: "var(--fg-faint)" }}><Icon name="package" size={26} /></div>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: "var(--fg-strong)", margin: 0 }}>Booking not found</h1>
          <p style={{ fontSize: 14.5, color: "var(--fg-mute)", marginTop: 8 }}>We couldn't find booking <span className="mono">{code || "—"}</span>. Open it again from the bookings queue.</p>
          <div style={{ marginTop: 18 }}><a href="Fedex CSR Console.html" style={{ textDecoration: "none" }}><Button variant="primary" icon="arrow-left">Back to console</Button></a></div>
        </div>
      </div>
    );
  }

  const b = booking;
  const type = window.FX.BOOKING_TYPES.find(x => x.id === b.typeId);
  const size = window.FX.VEHICLES.find(x => x.id === b.vehicleId);
  const svc = window.FX.SERVICES.find(x => x.id === b.serviceId);
  const driver = b.driver || window.FX.DRIVERS.find(d => d.id === b.driverId);
  const cancelled = b.status === "Cancelled";
  const inTransit = b.status === "In transit";
  const isNF = window.FX.isNextFlight(b);
  const nfInfo = isNF ? window.FX.nextFlightInfo(b) : null;
  const chargesTotal = (b.charges || []).reduce((s, c) => s + c.amount * (c.qty || 1), 0);
  const statusTone = cancelled ? "danger" : inTransit ? "brand" : b.status === "Delivered" ? "neutral" : "success";
  const statusCol = cancelled ? "var(--danger)" : inTransit ? "var(--brand)" : b.status === "Delivered" ? "var(--fg-mute)" : "var(--success)";

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg-page)" }}>
      <TopBar tracking={b.tracking} />
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "26px 28px 80px" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22, flexWrap: "wrap" }}>
          <a href="Fedex CSR Console.html" style={{ textDecoration: "none", color: "var(--fg-mute)", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 13 }}><Icon name="arrow-left" size={15} /> Queue</a>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 20, fontWeight: 700, color: "var(--brand)" }}>{b.tracking}</span>
          {type && <Badge tone={type.tone}>{type.name}</Badge>}
          <Badge tone={statusTone}><StatusDot color={statusCol} pulse={inTransit} /> {b.status}</Badge>
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 14 }}>
            {!cancelled && <Button variant="secondary" size="sm" icon="pen-tool" onClick={() => setEditing(true)}>Edit booking</Button>}
            <span style={{ fontSize: 24, fontWeight: 900, letterSpacing: "-0.6px", color: "var(--fg-strong)" }}>{window.FX.money(b.total, b.currency || "AUD")}</span>
          </div>
        </div>

        {isNF && <div style={{ marginBottom: 22 }}><NextFlightPanel booking={b} onUpdate={update} cancelled={cancelled} /></div>}

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1fr)", gap: 22, alignItems: "start" }}>
          {/* LEFT */}
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            {isNF && nfInfo && (() => {
              const legs = b.legs || {};
              const setLeg = (which, patch) => {
                const next = { ...legs, [which]: { ...(legs[which] || {}), ...patch } };
                const upd = { legs: next };
                if (which === "delivery" && patch.status === "done") { upd.status = "Delivered"; upd.progress = 1; }
                update(upd);
              };
              return (
                <React.Fragment>
                  <Card pad={20}>
                    <CardTitle icon="package" title="Pickup" hint={nfInfo.dep.code + " · " + nfInfo.dep.city} />
                    <StopBP accent="var(--brand)" label="Pickup from" addr={b.pickup} time={`${window.FX.fmtDate(b.date)} · ${b.time || "—"}`} />
                    <div style={{ borderTop: "1px solid var(--border)", margin: "14px 0" }} />
                    <LegAllocation booking={b} which="pickup" port={nfInfo.dep} place={b.pickup} recommendState={nfInfo.originState} driver={nfInfo.pickupDriver} nf={nfInfo} leg={legs.pickup || {}} onSetLeg={setLeg} cancelled={cancelled} />
                  </Card>
                  <Card pad={20}>
                    <CardTitle icon="map-pin" title="Delivery" hint={nfInfo.arr.code + " · " + nfInfo.arr.city} />
                    <StopBP accent="var(--accent)" label="Deliver to" addr={b.dropoff} />
                    <div style={{ borderTop: "1px solid var(--border)", margin: "14px 0" }} />
                    <LegAllocation booking={b} which="delivery" port={nfInfo.arr} place={b.dropoff} recommendState={nfInfo.destState} driver={nfInfo.deliveryDriver} nf={nfInfo} leg={legs.delivery || {}} onSetLeg={setLeg} cancelled={cancelled} />
                  </Card>
                </React.Fragment>
              );
            })()}
            {!isNF && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", background: "var(--brand-soft)", borderRadius: "var(--r-md)" }}>
              <Icon name="link" size={16} color="var(--brand)" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Tracking link</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--brand)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>track.fedex.com.au/t/{b.tracking.replace(/^FX-/, "")}</div>
              </div>
              {!cancelled && <a href={bpTrackUrl(b.tracking, driver ? driver.name : "")} target="_blank" rel="noopener" style={{ textDecoration: "none" }}><Button variant="primary" size="sm" icon="navigation">Open tracking</Button></a>}
            </div>
            )}

            {/* route */}
            {!isNF && (
            <Card pad={20}>
              <CardTitle icon="map-pin" title="Route" />
              <StopBP accent="var(--brand)" label="Pickup" addr={b.pickup} time={`${window.FX.fmtDate(b.date)} · ${b.time || "—"}`} />
              <div style={{ width: 2, height: 16, background: "var(--border-strong)", margin: "2px 0 2px 13px" }} />
              <StopBP accent="var(--accent)" label="Deliver to" addr={b.dropoff} />
            </Card>
            )}

            {/* call history & notes */}
            <Card pad={20}>
              <CardTitle icon="message-square" title="Call history & notes" />
              <NotesPanel booking={b} onUpdate={update} />
            </Card>

            {/* audit history */}
            <Card pad={20}>
              <CardTitle icon="history" title="Audit history" />
              <AuditHistory booking={b} />
            </Card>
          </div>

          {/* RIGHT */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {/* customer */}
            <Card pad={18}>
              <CardTitle icon="user" title="Customer" />
              <div style={{ fontSize: 15, fontWeight: 700, color: "var(--fg-strong)" }}>{b.customerName}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)", marginTop: 2 }}>{b.customerRef}{b.ref1 ? " · Ref " + b.ref1 : ""}</div>
            </Card>

            {/* driver */}
            {!isNF && (
            <Card pad={18}>
              <CardTitle icon="navigation" title="Driver" />
              {driver ? (
                <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                  <span style={{ width: 40, height: 40, borderRadius: "50%", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 14, flex: "none" }}>{driver.initials}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-strong)" }}>{driver.name}</div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)" }}>{driver.vehicle} · {driver.rego}</div>
                  </div>
                  <a href={"tel:" + driver.phone} style={{ width: 34, height: 34, borderRadius: "50%", background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="phone" size={16} /></a>
                </div>
              ) : <div style={{ fontSize: 13, color: "var(--fg-mute)", fontStyle: "italic" }}>Not yet assigned.</div>}
            </Card>
            )}

            {/* details + charges */}
            <Card pad={18}>
              <CardTitle icon="package" title="Booking details" />
              <DetailRow label="Size" value={size ? size.name : "—"} top />
              <DetailRow label="Service" value={svc ? svc.name + (size ? " · " + window.FX.serviceCode(svc.id, size.id) : "") : "—"} />
              <DetailRow label="Distance" value={b.km != null ? b.km + " km" : "—"} />
              <DetailRow label="Return trip" value={b.isReturn ? "Yes" : "No"} />
              {b.notes && typeof b.notes === "string" && <DetailRow label="Booking note" value={b.notes} />}
            </Card>

            {/* charges */}
            <ChargesPanel booking={b} onUpdate={update} />

            {/* type instructions */}
            {type && (
              <Card pad={0} style={{ overflow: "hidden" }}>
                <div style={{ background: "var(--brand)", color: "#fff", padding: "13px 16px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Icon name="info" size={15} /><span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "1px", textTransform: "uppercase", opacity: 0.85 }}>Instructions · {type.short}</span>
                  </div>
                </div>
                <ul style={{ margin: 0, padding: "12px 16px 12px 32px", display: "flex", flexDirection: "column", gap: 6 }}>
                  {type.instructions.map((ins, i) => <li key={i} style={{ fontSize: 12.5, lineHeight: 1.4, color: "var(--fg-body)" }}>{ins}</li>)}
                </ul>
              </Card>
            )}
          </div>
        </div>
      </div>
      {editing && <EditBookingModal booking={b} onClose={() => setEditing(false)} onSave={(patch) => { update(patch); setEditing(false); }} />}
    </div>
  );
}

/* ---------- Audit history: created / edited / cancelled trail ---------- */
function AuditHistory({ booking }) {
  const entries = (booking.audit && booking.audit.length)
    ? booking.audit
    : [{ at: booking.placedAt || new Date().toISOString(), by: booking.caller && booking.caller.name ? "CE console · caller: " + booking.caller.name : "System", action: "created", detail: "Booking created" }];
  const iconFor = a => a === "created" ? "plus" : a === "cancelled" ? "x" : "pencil";
  const colFor = a => a === "created" ? "var(--brand)" : a === "cancelled" ? "var(--danger)" : "var(--accent-700)";
  const fmt = iso => { try { const d = new Date(iso); return d.toLocaleDateString("en-AU", { day: "numeric", month: "short" }) + " · " + d.toLocaleTimeString("en-AU", { hour: "2-digit", minute: "2-digit" }); } catch (e) { return iso; } };
  return (
    <div style={{ position: "relative" }}>
      {entries.slice().reverse().map((e, i, arr) => (
        <div key={i} style={{ display: "flex", gap: 12, paddingBottom: i < arr.length - 1 ? 14 : 0, position: "relative" }}>
          {i < arr.length - 1 && <span style={{ position: "absolute", left: 11, top: 24, bottom: 0, width: 2, background: "var(--border)" }} />}
          <span style={{ width: 23, height: 23, borderRadius: "50%", flex: "none", zIndex: 1, background: "var(--bg-mist)", color: colFor(e.action), display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name={iconFor(e.action)} size={12} /></span>
          <div style={{ flex: 1, minWidth: 0, paddingTop: 1 }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-strong)" }}>{e.detail}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)" }}>{fmt(e.at)}</span>
            </div>
            <div style={{ fontSize: 12, color: "var(--fg-mute)", marginTop: 1 }}>{e.by}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Next Flight allocation: per-leg (pickup / delivery); driver via Locate2u or a service provider ---------- */
const legChoiceStyle = { display: "flex", alignItems: "center", gap: 10, textAlign: "left", padding: "12px 13px", borderRadius: "var(--r-md)", border: "1.5px solid var(--border)", background: "var(--surface)", cursor: "pointer" };
const legLinkBtn = { flex: "none", background: "none", border: "1px solid var(--border)", borderRadius: 8, padding: "6px 11px", fontSize: 12, fontWeight: 600, color: "var(--fg-body)", cursor: "pointer" };
const legChip = { display: "inline-flex", alignItems: "center", gap: 6, background: "var(--brand-soft)", color: "var(--brand)", borderRadius: 999, padding: "4px 10px", fontSize: 11.5, fontWeight: 500 };

function LegAllocation({ booking, which, port, place, recommendState, driver, nf, leg, onSetLeg, cancelled }) {
  const store = bpLoad();
  const allAgents = store.serviceAgents || window.FX.SERVICE_AGENTS;
  const activeAgents = allAgents.filter(a => a.active);
  const [pick, setPick] = useStateBP("");
  const mode = leg.mode || null;
  const agent = leg.agentId ? allAgents.find(a => a.id === leg.agentId) : null;
  const isDelivery = which === "delivery";
  const accent = isDelivery ? "var(--accent)" : "var(--brand)";
  const stamp = () => new Date().toLocaleString("en-AU", { hour: "2-digit", minute: "2-digit", day: "numeric", month: "short" });

  const roadFrom = isDelivery ? port.code : (place.suburb || "Pickup");
  const roadTo = isDelivery ? (place.suburb || "Delivery") : port.code;
  const legSub = isDelivery ? (port.city + " Airport → final delivery") : ("Pickup → " + port.city + " Airport");

  const inArea = a => (a.serviceAreas || (a.state ? [a.state] : [])).includes(recommendState);
  const opts = [...activeAgents].sort((a, b) => (inArea(b) ? 1 : 0) - (inArea(a) ? 1 : 0))
    .map(a => ({ value: a.id, label: `${a.name} — ${a.city} (${(a.serviceAreas || [a.state]).join("/")})${inArea(a) ? " · recommended" : ""}` }));

  const setLeg = patch => onSetLeg(which, patch);
  const chooseDriver = () => setLeg({ mode: "driver", dispatchedAt: stamp(), agentId: null, status: null });
  const chooseAgent = () => setLeg({ mode: "agent" });
  const reset = () => setLeg({ mode: null, agentId: null, status: null, notifiedAt: null, acceptedAt: null, pickedUpAt: null, deliveredAt: null, dispatchedAt: null });
  const allocate = () => { const a = activeAgents.find(x => x.id === pick); if (!a) return; setLeg({ mode: "agent", agentId: a.id, status: "notified", notifiedAt: stamp() }); setPick(""); };

  const ORDER = ["notified", "accepted", "pickedup", "done"];
  const stepIdx = leg.status ? ORDER.indexOf(leg.status) + 1 : 0;
  const stepLabels = ["Notified", "Accepted", "Collected", isDelivery ? "Delivered" : "At airport"];
  const stepTimes = [leg.notifiedAt, leg.acceptedAt, leg.pickedUpAt, leg.deliveredAt];
  const l2uLink = "locate2u.com/dispatch/" + booking.tracking.replace(/^FX-/, "");
  const trackUrl = "Fedex Track.html#t=" + encodeURIComponent(booking.tracking) + "&nf=1&leg=" + which + (driver ? "&driver=" + encodeURIComponent(driver.name) : "");

  const statusBadge = () => {
    if (mode === "driver") return <Badge tone="brand"><StatusDot color="var(--brand)" /> Locate2u driver</Badge>;
    if (mode === "agent" && agent) { const lbl = { notified: "Notified", accepted: "Accepted", pickedup: "Collected", done: stepLabels[3] }[leg.status] || "Notified"; return <Badge tone={leg.status === "done" ? "success" : "brand"}><StatusDot color={leg.status === "done" ? "#22b86e" : "var(--brand)"} pulse={leg.status !== "done"} /> {lbl}</Badge>; }
    return <Badge tone="neutral">Unallocated</Badge>;
  };

  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)" }}>
        <span style={{ width: 28, height: 28, borderRadius: 8, flex: "none", background: accent, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name={isDelivery ? "map-pin" : "package"} size={15} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>{isDelivery ? "Delivery leg" : "Pickup leg"} <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-mute)", fontSize: 12 }}>· {roadFrom} → {roadTo}</span></div>
          <div style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{legSub}</div>
        </div>
        {statusBadge()}
      </div>
      <div style={{ padding: 13 }}>
        {!mode && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <button onClick={chooseDriver} disabled={cancelled} style={legChoiceStyle}>
              <span style={{ width: 34, height: 34, borderRadius: 9, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="truck" size={17} /></span>
              <span style={{ minWidth: 0 }}><span style={{ display: "block", fontSize: 13, fontWeight: 700, color: "var(--fg-strong)" }}>Driver</span><span style={{ display: "block", fontSize: 11, color: "var(--fg-mute)" }}>Dispatch in Locate2u</span></span>
            </button>
            <button onClick={chooseAgent} disabled={cancelled} style={legChoiceStyle}>
              <span style={{ width: 34, height: 34, borderRadius: 9, background: "var(--accent-soft)", color: "var(--accent-700)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="shield" size={17} /></span>
              <span style={{ minWidth: 0 }}><span style={{ display: "block", fontSize: 13, fontWeight: 700, color: "var(--fg-strong)" }}>Service provider</span><span style={{ display: "block", fontSize: 11, color: "var(--fg-mute)" }}>Notify a partner agent</span></span>
            </button>
          </div>
        )}

        {mode === "driver" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span style={{ width: 36, height: 36, borderRadius: "50%", flex: "none", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12 }}>{driver ? driver.initials : "L2U"}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>{driver ? driver.name : "Awaiting Locate2u driver"}</div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-mute)" }}>{driver ? driver.rego : "—"}</div>
              </div>
              {!cancelled && <button onClick={reset} style={legLinkBtn}>Change</button>}
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "flex-start", padding: "9px 11px", background: "var(--brand-soft)", borderRadius: "var(--r-sm)" }}>
              <Icon name="info" size={14} color="var(--brand)" style={{ flex: "none", marginTop: 1 }} />
              <span style={{ fontSize: 12, color: "var(--fg-body)", lineHeight: 1.4 }}>Driver allocation &amp; dispatch is handled in <strong>Locate2u</strong>. Dispatched {leg.dispatchedAt || "now"}.</span>
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <a href={trackUrl} target="_blank" rel="noopener" style={{ textDecoration: "none" }}><Button variant="secondary" size="sm" icon="navigation">Track driver</Button></a>
              <a href={"https://" + l2uLink} target="_blank" rel="noopener" style={{ textDecoration: "none" }}><Button variant="secondary" size="sm" iconRight="arrow-right">Open in Locate2u</Button></a>
            </div>
          </div>
        )}

        {mode === "agent" && !agent && (
          <div style={{ display: "flex", gap: 10, alignItems: "flex-end", flexWrap: "wrap" }}>
            <div style={{ flex: "1 1 260px", minWidth: 0 }}>
              <div style={{ fontSize: 11.5, color: "var(--fg-mute)", marginBottom: 6 }}>Service provider{recommendState ? " · recommended in " + recommendState : ""}</div>
              <Select value={pick} onChange={setPick} placeholder="Choose a service provider…" options={opts} />
            </div>
            <Button variant="primary" icon="send" disabled={!pick || cancelled} onClick={allocate}>Allocate &amp; notify</Button>
            <button onClick={reset} style={legLinkBtn}>Cancel</button>
          </div>
        )}

        {mode === "agent" && agent && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span style={{ width: 36, height: 36, borderRadius: 9, flex: "none", background: "var(--accent-soft)", color: "var(--accent-700)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="shield" size={17} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{agent.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{agent.contact} · {agent.city} ({agent.state})</div>
              </div>
              {!cancelled && <button onClick={reset} style={legLinkBtn}>Reassign</button>}
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
              <span style={legChip}><Icon name="mail" size={12} /> Email sent</span>
              {agent.phone ? <span style={legChip}><Icon name="message-square" size={12} /> SMS · {agent.phone}</span> : <span style={{ ...legChip, background: "var(--bg-mist)", color: "var(--fg-mute)" }}><Icon name="mail" size={12} /> Email only</span>}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
              {stepLabels.map((lbl, i) => (
                <div key={lbl} style={{ display: "flex", alignItems: "center", flex: i < stepLabels.length - 1 ? 1 : "none" }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 3 }}>
                    <span style={{ width: 20, height: 20, borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center", background: i < stepIdx ? accent : "var(--bg-mist-2)", color: i < stepIdx ? "#fff" : "var(--fg-mute)" }}>{i < stepIdx ? <Icon name="check" size={11} /> : <span style={{ width: 5, height: 5, borderRadius: "50%", background: "var(--fg-faint)" }} />}</span>
                    <span style={{ fontSize: 10, fontWeight: 600, color: i < stepIdx ? "var(--fg-strong)" : "var(--fg-mute)", whiteSpace: "nowrap" }}>{lbl}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 9, color: "var(--fg-faint)", minHeight: 11 }}>{stepTimes[i] || ""}</span>
                  </div>
                  {i < stepLabels.length - 1 && <span style={{ flex: 1, height: 2, background: i < stepIdx ? accent : "var(--border)", margin: "0 5px", marginBottom: 20 }} />}
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <Button variant="secondary" size="sm" icon="check" disabled={cancelled || stepIdx >= 2} onClick={() => setLeg({ status: "accepted", acceptedAt: stamp() })}>Accept</Button>
              <Button variant="secondary" size="sm" icon="package" disabled={cancelled || stepIdx < 2 || stepIdx >= 3} onClick={() => setLeg({ status: "pickedup", pickedUpAt: stamp() })}>Collected</Button>
              <Button variant="primary" size="sm" icon="check-circle" disabled={cancelled || stepIdx < 3 || stepIdx >= 4} onClick={() => setLeg({ status: "done", deliveredAt: stamp() })}>{isDelivery ? "Delivered" : "At airport"}</Button>
            </div>
            <div style={{ fontSize: 10.5, color: "var(--fg-faint)" }}>Links in the provider's email &amp; SMS — they Accept, then confirm Collected and {isDelivery ? "Delivered" : "At airport"}.</div>
          </div>
        )}
      </div>
    </div>
  );
}

function NextFlightAllocation({ booking, onUpdate, cancelled, nf }) {
  const legs = booking.legs || {};
  const setLeg = (which, patch) => {
    const next = { ...legs, [which]: { ...(legs[which] || {}), ...patch } };
    const upd = { legs: next };
    if (which === "delivery" && patch.status === "done") { upd.status = "Delivered"; upd.progress = 1; }
    onUpdate(upd);
  };
  return (
    <div style={{ marginTop: 16, borderTop: "1px solid var(--border)", paddingTop: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
        <Icon name="navigation" size={15} color="var(--brand)" />
        <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>Allocation</span>
      </div>
      <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginBottom: 12 }}>Allocate each leg to a Locate2u <strong>driver</strong> or a <strong>service provider</strong> — either end can go either way.</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <LegAllocation booking={booking} which="pickup" port={nf.dep} place={booking.pickup} recommendState={nf.originState} driver={nf.pickupDriver} nf={nf} leg={legs.pickup || {}} onSetLeg={setLeg} cancelled={cancelled} />
        <LegAllocation booking={booking} which="delivery" port={nf.arr} place={booking.dropoff} recommendState={nf.destState} driver={nf.deliveryDriver} nf={nf} leg={legs.delivery || {}} onSetLeg={setLeg} cancelled={cancelled} />
      </div>
    </div>
  );
}

/* ---------- Middle-mile legs: chain of flight / truck / train segments ---------- */
function midLegDefaults(nf) {
  return [{ id: "leg1", mode: nf.mode || "flight", carrier: nf.flight.airline_name || "", ref: nf.flightIata || "", from: nf.dep.code, to: nf.arr.code, depHm: nf.flight.dep_hm || "", arrHm: nf.flight.arr_est_hm || nf.flight.arr_hm || "" }];
}
const MID_MODE = { flight: { icon: "plane", label: "Flight", refLabel: "Flight no." }, truck: { icon: "truck", label: "Truck", refLabel: "Rego" }, train: { icon: "train", label: "Train", refLabel: "Service no." } };
function MidLegsEditor({ booking, onUpdate, cancelled, nf }) {
  const legs = (booking.midLegs && booking.midLegs.length) ? booking.midLegs : midLegDefaults(nf);
  const commit = (next) => onUpdate({ midLegs: next });
  const patch = (i, p) => commit(legs.map((l, idx) => idx === i ? { ...l, ...p } : l));
  const add = () => { const last = legs[legs.length - 1]; commit([...legs, { id: "leg" + Date.now(), mode: "truck", carrier: "", ref: "", from: last ? last.to : nf.arr.code, to: "", depHm: "", arrHm: "" }]); };
  const remove = (i) => commit(legs.length > 1 ? legs.filter((_, idx) => idx !== i) : legs);
  return (
    <div style={{ marginTop: 16, border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "11px 14px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)" }}>
        <Icon name="navigation" size={15} color="var(--brand)" />
        <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)", flex: 1 }}>Middle-mile legs</span>
        <span style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{legs.length} leg{legs.length === 1 ? "" : "s"}</span>
      </div>
      {/* chain summary */}
      <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap", padding: "11px 14px", borderBottom: "1px solid var(--border)" }}>
        <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12.5, color: "var(--fg-strong)" }}>{legs[0] ? legs[0].from : nf.dep.code}</span>
        {legs.map((l, i) => (
          <React.Fragment key={l.id || i}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--accent-700)" }}><Icon name={(MID_MODE[l.mode] || MID_MODE.flight).icon} size={13} />{l.ref ? <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5 }}>{l.ref}</span> : null}<Icon name="arrow-right" size={12} color="var(--fg-faint)" /></span>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12.5, color: "var(--fg-strong)" }}>{l.to || "?"}</span>
          </React.Fragment>
        ))}
      </div>
      {/* editable legs */}
      <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 10 }}>
        {legs.map((l, i) => {
          const mm = MID_MODE[l.mode] || MID_MODE.flight;
          return (
            <div key={l.id || i} style={{ border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: 11 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: "var(--fg-mute)" }}>LEG {i + 1}</span>
                <div style={{ display: "inline-flex", gap: 4, background: "var(--bg-mist)", padding: 3, borderRadius: "var(--r-pill)" }}>
                  {Object.keys(MID_MODE).map(k => (
                    <button key={k} onClick={() => !cancelled && patch(i, { mode: k })} style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 11px", borderRadius: "var(--r-pill)", border: "none", fontSize: 12, fontWeight: 600, background: l.mode === k ? "var(--surface)" : "transparent", color: l.mode === k ? "var(--brand)" : "var(--fg-mute)", boxShadow: l.mode === k ? "var(--shadow-xs)" : "none", cursor: "pointer" }}><Icon name={MID_MODE[k].icon} size={13} /> {MID_MODE[k].label}</button>
                  ))}
                </div>
                {!cancelled && legs.length > 1 && <button onClick={() => remove(i)} title="Remove leg" style={{ marginLeft: "auto", width: 28, height: 28, borderRadius: 7, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--fg-mute)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="x" size={14} /></button>}
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr 0.7fr 0.7fr 0.7fr 0.7fr", gap: 8 }}>
                <Field label="Carrier"><TextInput value={l.carrier || ""} onChange={v => patch(i, { carrier: v })} placeholder={l.mode === "flight" ? "e.g. Qantas" : l.mode === "train" ? "e.g. Pacific National" : "e.g. Linfox"} /></Field>
                <Field label={mm.refLabel}><TextInput value={l.ref || ""} onChange={v => patch(i, { ref: v.toUpperCase() })} placeholder={l.mode === "flight" ? "QF445" : l.mode === "train" ? "SP23" : "XV-44-KD"} mono /></Field>
                <Field label="From"><TextInput value={l.from || ""} onChange={v => patch(i, { from: v.toUpperCase() })} placeholder="SYD" mono /></Field>
                <Field label="To"><TextInput value={l.to || ""} onChange={v => patch(i, { to: v.toUpperCase() })} placeholder="MEL" mono /></Field>
                <Field label="Dep"><TextInput type="time" value={l.depHm || ""} onChange={v => patch(i, { depHm: v })} mono /></Field>
                <Field label="Arr"><TextInput type="time" value={l.arrHm || ""} onChange={v => patch(i, { arrHm: v })} mono /></Field>
              </div>
            </div>
          );
        })}
        {!cancelled && <button onClick={add} style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "10px", background: "var(--surface)", border: "1px dashed var(--border-strong)", borderRadius: "var(--r-md)", color: "var(--brand)", fontSize: 13, fontWeight: 600, cursor: "pointer" }}><Icon name="plus" size={15} /> Add a leg (connecting flight, truck or train)</button>}
      </div>
    </div>
  );
}

/* ---------- Next Flight air-freight panel (pickup courier · flight · delivery courier) ---------- */
function NextFlightPanel({ booking, onUpdate, cancelled }) {
  const nf = window.FX.nextFlightInfo(booking);
  const [awb, setAwb] = useStateBP(booking.awb || nf.awb);
  const [awbPicker, setAwbPicker] = useStateBP(false);
  useEffectBP(() => { setAwb(booking.awb || nf.awb); }, [booking.tracking]);
  const f = nf.flight;
  const nfLink = "track.fedex.com.au/nf/" + booking.tracking.replace(/^FX-/, "");
  const trackUrl = (leg, drv) => "Fedex Track.html#t=" + encodeURIComponent(booking.tracking) + "&nf=1" + (leg ? "&leg=" + leg : "") + (drv ? "&driver=" + encodeURIComponent(drv) : "");
  const fstatus = (window.FX.FLIGHT_STATUS && window.FX.FLIGHT_STATUS[f.status]) || null;
  const mode = nf.mode || "flight";
  const isFlight = mode === "flight";
  const lh = nf.linehaul || {};
  const modeIcon = mode === "truck" ? "truck" : mode === "train" ? "train" : "plane";
  const setLH = (k, v) => onUpdate({ linehaul: { ...(booking.linehaul || {}), [k]: v } });
  const switchMode = (m) => {
    if (m === mode) return;
    if (m === "flight") onUpdate({ transportMode: "flight" });
    else onUpdate({ transportMode: m, linehaul: booking.linehaul || { carrier: "", rego: "", ref: "", trackingNo: "", destination: nf.arr.city, pickupHm: "", deliveryHm: "" } });
  };

  const routeNode = (icon, eyebrow, main, sub, accent) => (
    <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, flex: "none", background: "var(--surface)", color: accent, display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name={icon} size={17} /></span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>{eyebrow}</div>
        <div style={{ fontSize: 13, fontWeight: 700, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 200 }}>{main}</div>
        {sub && <div style={{ fontSize: 11, color: "var(--fg-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 200 }}>{sub}</div>}
      </div>
    </div>
  );

  return (
    <Card pad={0} style={{ overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", background: "var(--brand)", color: "#fff" }}>
        <Icon name={modeIcon} size={17} />
        <span style={{ fontWeight: 700, fontSize: 14.5, flex: 1 }}>{isFlight ? "Next Flight air freight" : mode === "truck" ? "Interstate line haul — truck" : "Interstate line haul — train"}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, background: "rgba(255,255,255,0.15)", padding: "4px 10px", borderRadius: 999 }}>{nf.originState} → {nf.destState}</span>
      </div>
      <div style={{ padding: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", padding: "12px 14px", background: "var(--bg-mist)", borderRadius: "var(--r-md)" }}>
          {routeNode("package", "Pickup", booking.pickup.company || booking.pickup.suburb, booking.pickup.suburb, "var(--brand)")}
          <Icon name="arrow-right" size={15} color="var(--fg-faint)" />
          {routeNode(isFlight ? "plane" : modeIcon, nf.dep.code, nf.dep.city + (isFlight ? " Airport" : " hub"), null, "var(--brand)")}
          <div style={{ flex: 1, minWidth: 128, display: "flex", flexDirection: "column", alignItems: "center", gap: 4, padding: "0 4px" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 14, color: "var(--brand)" }}>{nf.flightIata}</span>
            <span style={{ fontSize: 10, color: "var(--fg-mute)" }}>{f.airline_name || ""}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 6, width: "100%", justifyContent: "center" }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, fontWeight: 600, color: "var(--fg-strong)" }}>{f.dep_hm || "—"}</span>
              <span style={{ flex: 1, height: 1, background: "var(--border-strong)", position: "relative", minWidth: 20 }}><span style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)", background: "var(--bg-mist)", padding: "0 1px", display: "inline-flex" }}><Icon name={modeIcon} size={11} color="var(--accent)" /></span></span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, fontWeight: 600, color: "var(--fg-strong)" }}>{f.arr_est_hm || f.arr_hm || "—"}</span>
            </div>
            {isFlight ? (fstatus && <Badge tone={fstatus.tone}><StatusDot color={fstatus.dot} pulse={f.status === "en-route"} /> {fstatus.label}</Badge>) : <Badge tone="brand"><Icon name={modeIcon} size={11} /> Line haul</Badge>}
          </div>
          {routeNode(isFlight ? "plane" : modeIcon, nf.arr.code, isFlight ? nf.arr.city + " Airport" : (lh.destination || nf.arr.city + " hub"), null, "var(--accent)")}
          <Icon name="arrow-right" size={15} color="var(--fg-faint)" />
          {routeNode("map-pin", "Delivery", booking.dropoff.company || booking.dropoff.suburb, booking.dropoff.suburb, "var(--accent)")}
        </div>

        {/* Middle-mile transport is chosen per-leg in the Middle-mile legs editor below */}

        <MidLegsEditor booking={booking} onUpdate={onUpdate} cancelled={cancelled} nf={nf} />

        <div style={{ display: "grid", gridTemplateColumns: isFlight ? "1fr 1fr" : "1fr", gap: 12, marginTop: 16 }}>
          {isFlight && <div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-strong)" }}>Airway bill number</span>
              {!cancelled && <button onClick={() => setAwbPicker(true)} title="Search existing airway bills" style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "3px 9px", color: "var(--brand)", fontSize: 11.5, fontWeight: 600, cursor: "pointer" }}><Icon name="search" size={12} /> Find / add</button>}
            </div>
            <TextInput value={awb} onChange={v => { setAwb(v); onUpdate({ awb: v }); }} placeholder="e.g. 081-12345675" mono />
          </div>}
          <div>
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-strong)", marginBottom: 6 }}>Next Flight tracking link</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 12px", background: "var(--brand-soft)", borderRadius: "var(--r-sm)" }}>
              <Icon name="link" size={14} color="var(--brand)" />
              <span style={{ flex: 1, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--brand)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{nfLink}</span>
              {!cancelled && <a href={trackUrl("", "")} target="_blank" rel="noopener" style={{ textDecoration: "none", flex: "none" }}><Button variant="primary" size="sm" icon="navigation">Open</Button></a>}
            </div>
          </div>
        </div>
      </div>
      <AwbPickerModal open={awbPicker} onClose={() => setAwbPicker(false)} booking={booking} currentAwb={awb}
        onPick={(rec) => { setAwb(rec.awb); onUpdate({ awb: rec.awb, flightIata: rec.flightIata }); setAwbPicker(false); }} />
    </Card>
  );
}

/* Search existing (active) airway bills, or add a new one by typing its flight number. */
function AwbPickerModal({ open, onClose, booking, currentAwb, onPick }) {
  const [tab, setTab] = useStateBP("find");
  const [q, setQ] = useStateBP("");
  const [flightNo, setFlightNo] = useStateBP("");
  const [newAwb, setNewAwb] = useStateBP("");
  useEffectBP(() => { if (open) { setTab("find"); setQ(""); setFlightNo(""); setNewAwb(""); } }, [open]);

  const store = bpLoad();
  const allBookings = store.bookings || [];
  const registry = window.FX.airwayBillRegistry(allBookings, { activeOnly: true });
  const filtered = q.trim()
    ? registry.filter(r => (r.awb + " " + r.flightIata + " " + r.dep.code + " " + r.arr.code + " " + r.dep.city + " " + r.arr.city).toLowerCase().includes(q.trim().toLowerCase()))
    : registry;

  const resolved = window.FX.resolveFlight(flightNo);
  const fstatus = s => (window.FX.FLIGHT_STATUS && window.FX.FLIGHT_STATUS[s]) || null;

  const flightLine = (rec) => (
    <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", fontSize: 12, color: "var(--fg-mute)" }}>
      <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--brand)" }}>{rec.flightIata}</span>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-strong)" }}>{rec.dep.code}</span><Icon name="arrow-right" size={11} color="var(--fg-faint)" /><span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-strong)" }}>{rec.arr.code}</span></span>
      <span>· dep <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-strong)" }}>{rec.depHm}</span></span>
      <span>· arr <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--fg-strong)" }}>{rec.eta}</span></span>
      {fstatus(rec.status) && <Badge tone={fstatus(rec.status).tone}><StatusDot color={fstatus(rec.status).dot} pulse={rec.status === "en-route"} /> {fstatus(rec.status).label}</Badge>}
    </div>
  );

  function addNew() {
    if (!resolved || !newAwb.trim()) return;
    onPick({ awb: newAwb.trim(), flightIata: resolved.flightIata });
  }

  return (
    <Modal open={open} onClose={onClose} title="Airway bills" width={620}>
      <div style={{ display: "flex", gap: 6, background: "var(--bg-mist)", padding: 4, borderRadius: "var(--r-pill)", marginBottom: 16, width: "fit-content" }}>
        {[["find", "Find active AWB"], ["add", "Add new AWB"]].map(([k, l]) => (
          <button key={k} onClick={() => setTab(k)} style={{ padding: "7px 16px", borderRadius: "var(--r-pill)", border: "none", fontSize: 13, fontWeight: 600, background: tab === k ? "var(--surface)" : "transparent", color: tab === k ? "var(--brand)" : "var(--fg-mute)", boxShadow: tab === k ? "var(--shadow-xs)" : "none", cursor: "pointer" }}>{l}</button>
        ))}
      </div>

      {tab === "find" ? (
        <div>
          <div style={{ position: "relative", marginBottom: 14 }}>
            <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={15} /></span>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search AWB, flight or port…" style={{ ...window.inputStyle, paddingLeft: 36 }} />
          </div>
          <div style={{ fontSize: 11.5, color: "var(--fg-mute)", marginBottom: 10 }}>{filtered.length} active airway bill{filtered.length === 1 ? "" : "s"} — pick one to add this consignment to that flight.</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 9, maxHeight: 340, overflowY: "auto" }}>
            {filtered.map(rec => {
              const isCurrent = rec.awb === currentAwb;
              const sameRoute = rec.dep.code === window.FX.nextFlightInfo(booking).dep.code && rec.arr.code === window.FX.nextFlightInfo(booking).arr.code;
              return (
                <div key={rec.awb} style={{ border: "1px solid " + (isCurrent ? "var(--brand)" : "var(--border)"), borderRadius: "var(--r-md)", padding: 13, background: isCurrent ? "var(--brand-soft)" : "var(--surface)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 700, color: "var(--fg-strong)", flex: 1 }}>{rec.awb}</span>
                    {sameRoute ? <Badge tone="success"><Icon name="check" size={11} /> Same route</Badge> : <Badge tone="warn">Different route</Badge>}
                    {!isCurrent
                      ? <Button variant="primary" size="sm" icon="plus" onClick={() => onPick(rec)}>Use this</Button>
                      : <Badge tone="brand">Current</Badge>}
                  </div>
                  {flightLine(rec)}
                  <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid var(--border)" }}>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.5px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 6 }}>{rec.consignments.length} consignment{rec.consignments.length === 1 ? "" : "s"} on this flight</div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                      {rec.consignments.map(c => (
                        <div key={c.tracking} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--fg-body)" }}>
                          <span style={{ fontFamily: "var(--font-mono)", color: "var(--brand)", fontWeight: 600 }}>{c.tracking}</span>
                          <span style={{ flex: 1, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.customerName} · {c.from} → {c.to}</span>
                          <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-mute)", flex: "none" }}>{c.items}× · {c.weightKg}kg</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
            {filtered.length === 0 && <div style={{ padding: 28, textAlign: "center", fontSize: 13, color: "var(--fg-mute)" }}>No active airway bills{q.trim() ? " match your search" : ""}. Add a new one on the next tab.</div>}
          </div>
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", gap: 8, alignItems: "flex-start", background: "var(--brand-soft)", padding: "10px 12px", borderRadius: "var(--r-sm)" }}>
            <Icon name="info" size={15} color="var(--brand)" style={{ flex: "none", marginTop: 1 }} />
            <span style={{ fontSize: 12.5, color: "var(--fg-body)", lineHeight: 1.45 }}>Enter the flight number — we'll look it up in the schedule and confirm the route and departure time. The airway bill number comes from the airline's booking system and must be entered.</span>
          </div>
          <Field label="Flight number"><TextInput value={flightNo} onChange={v => setFlightNo(v.toUpperCase())} placeholder="e.g. QF445" mono /></Field>
          {flightNo.trim() && (resolved ? (
            <div style={{ border: "1px solid var(--success, #1f8a5b)", borderRadius: "var(--r-md)", padding: 13, background: "color-mix(in srgb, var(--success, #1f8a5b), white 92%)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <Icon name="check-circle" size={16} color="var(--success, #1f8a5b)" />
                <span style={{ fontSize: 13, fontWeight: 700, color: "var(--fg-strong)" }}>Flight found — {resolved.flight.airline_name}</span>
              </div>
              {flightLine(resolved)}
            </div>
          ) : (
            <div style={{ display: "flex", gap: 8, alignItems: "center", padding: "11px 13px", background: "color-mix(in srgb, var(--danger), white 93%)", border: "1px solid var(--danger)", borderRadius: "var(--r-md)" }}>
              <Icon name="alert-triangle" size={15} color="var(--danger)" style={{ flex: "none" }} />
              <span style={{ fontSize: 12.5, color: "var(--fg-body)" }}>No flight matches <strong>{flightNo}</strong> in the schedule. Check the number, or search Flights for the right one.</span>
            </div>
          ))}
          <Field label={<span>Airway bill number <span style={{ color: "var(--danger)" }}>*</span></span>} hint="The AWB issued by the airline's booking system for this flight."><TextInput value={newAwb} onChange={v => setNewAwb(v)} placeholder="e.g. 081-12345675" mono /></Field>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 10 }}>
            {resolved && !newAwb.trim() && <span style={{ fontSize: 11.5, color: "var(--fg-mute)", marginRight: "auto" }}>Enter the airline's airway bill number to continue.</span>}
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" icon="check" disabled={!resolved || !newAwb.trim()} onClick={addNew}>Add airway bill</Button>
          </div>
        </div>
      )}
    </Modal>
  );
}

/* ---------- edit booking ---------- */
function EditBookingModal({ booking, onClose, onSave }) {
  const isNF = window.FX.isNextFlight(booking);
  const nf = isNF ? window.FX.nextFlightInfo(booking) : null;
  const [typeId, setTypeId] = useStateBP(booking.typeId);
  const [vehicleId, setVehicleId] = useStateBP(booking.vehicleId);
  const [serviceId, setServiceId] = useStateBP(booking.serviceId);
  const [date, setDate] = useStateBP(booking.date || window.FX.todayISO());
  const [time, setTime] = useStateBP(booking.time || "");
  const [isReturn, setIsReturn] = useStateBP(!!booking.isReturn);
  const [notes, setNotes] = useStateBP(typeof booking.notes === "string" ? booking.notes : "");
  const [pickup, setPickup] = useStateBP(booking.pickup || window.FX.emptyAddr());
  const [dropoff, setDropoff] = useStateBP(booking.dropoff || window.FX.emptyAddr());
  const [originPort, setOriginPort] = useStateBP(booking.originPort || (nf ? nf.dep.code : ""));
  const [destPort, setDestPort] = useStateBP(booking.destPort || (nf ? nf.arr.code : ""));
  const portOpts = window.FX.AIRPORT_CODES.map(c => ({ value: c, label: c + " · " + window.FX.AIRPORT_BY_CODE[c].city + " (" + window.FX.AIRPORT_BY_CODE[c].state + ")" }));

  function save() {
    const patch = { typeId, vehicleId, serviceId, date, time, isReturn, notes, pickup, dropoff };
    const mid = (booking.stops && booking.stops.length > 2) ? booking.stops.slice(1, -1) : [];
    patch.stops = [pickup, ...mid, dropoff];
    if (isNF) { patch.originPort = originPort; patch.destPort = destPort; }
    onSave(patch);
  }
  return (
    <Modal open onClose={onClose} title={"Edit booking · " + booking.tracking} width={640}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        {/* Addresses & contacts */}
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 10 }}>Pickup — address & contact</div>
          <AddressField value={pickup} onChange={setPickup} addressBook={window.FX.ADDRESS_BOOK} role="Pickup from" accent="var(--brand)" index={0} />
        </div>
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 10 }}>Delivery — address & contact</div>
          <AddressField value={dropoff} onChange={setDropoff} addressBook={window.FX.ADDRESS_BOOK} role="Deliver to" accent="var(--accent)" index={1} />
        </div>

        {isNF && (
          <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", background: "var(--brand-soft)" }}>
              <Icon name="plane" size={15} color="var(--brand)" />
              <span style={{ fontSize: 13, fontWeight: 700, color: "var(--fg-strong)" }}>Flight routing</span>
              <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--brand)" }}>{originPort} → {destPort}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 12, alignItems: "end", padding: 14 }}>
              <Field label="Flying out of"><Select value={originPort} onChange={setOriginPort} options={portOpts} /></Field>
              <div style={{ paddingBottom: 10 }}><Icon name="arrow-right" size={16} color="var(--fg-faint)" /></div>
              <Field label="Flying into"><Select value={destPort} onChange={setDestPort} options={portOpts} /></Field>
            </div>
            <div style={{ padding: "0 14px 12px", fontSize: 11.5, color: "var(--fg-mute)", lineHeight: 1.45 }}>Overrides the port derived from the suburbs — the flight, ETA and recommended service agents update to match.</div>
          </div>
        )}

        {/* Service & timing */}
        <Field label="Delivery type">
          <Select value={typeId} onChange={setTypeId} options={window.FX.BOOKING_TYPES.map(t => ({ value: t.id, label: t.name }))} />
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Size"><Select value={vehicleId} onChange={setVehicleId} options={window.FX.VEHICLES.map(v => ({ value: v.id, label: v.name + " · " + v.weight }))} /></Field>
          <Field label="Service tier"><Select value={serviceId} onChange={setServiceId} options={window.FX.SERVICES.map(s => ({ value: s.id, label: s.name + " · " + s.eta }))} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Pickup date"><TextInput type="date" value={date} onChange={setDate} min={window.FX.todayISO()} /></Field>
          <Field label="Ready time"><TextInput type="time" value={time} onChange={setTime} mono /></Field>
        </div>
        {!isNF && (
          <button onClick={() => setIsReturn(v => !v)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: 0, textAlign: "left" }}>
            <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: isReturn ? "var(--brand)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
              <span style={{ position: "absolute", top: 2, left: isReturn ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
            </span>
            <span style={{ fontSize: 14, color: "var(--fg-strong)", fontWeight: 500 }}>Return trip</span>
          </button>
        )}
        <Field label="Booking note">
          <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder="Anything dispatch or the driver should know…" style={{ ...window.inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.45 }} />
        </Field>
        <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" full icon="check" onClick={save}>Save changes</Button>
        </div>
      </div>
    </Modal>
  );
}

/* ---------- charges with dropdown ---------- */
function ChargesPanel({ booking, onUpdate }) {
  const [sel, setSel] = useStateBP("");
  const charges = booking.charges || [];
  const cur = booking.currency || "AUD";
  function addCharge() {
    const sc = window.FX.SERVICE_CHARGES.find(x => x.id === sel);
    if (!sc) return;
    const existing = charges.find(c => c.id === sc.id);
    const next = existing
      ? charges.map(c => c.id === sc.id ? { ...c, qty: (c.qty || 1) + 1 } : c)
      : [...charges, { ...sc, qty: 1 }];
    onUpdate({ charges: next });
    setSel("");
  }
  function setQty(id, qty) { onUpdate({ charges: charges.map(c => c.id === id ? { ...c, qty: Math.max(1, qty) } : c) }); }
  function remove(id) { onUpdate({ charges: charges.filter(c => c.id !== id) }); }
  const total = charges.reduce((s, c) => s + c.amount * (c.qty || 1), 0);
  const grouped = {};
  window.FX.SERVICE_CHARGES.forEach(sc => { (grouped[sc.group] = grouped[sc.group] || []).push(sc); });

  return (
    <Card pad={18}>
      <CardTitle icon="wallet" title="Additional charges" hint={charges.length ? window.FX.money(total, cur) : null} />
      <div style={{ display: "flex", gap: 8, marginBottom: charges.length ? 14 : 0 }}>
        <div style={{ position: "relative", flex: 1 }}>
          <select value={sel} onChange={e => setSel(e.target.value)} style={{ width: "100%", padding: "10px 32px 10px 12px", fontSize: 13.5, color: sel ? "var(--fg-strong)" : "var(--fg-faint)", background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: "var(--r-sm)", appearance: "none", cursor: "pointer", outline: "none" }}>
            <option value="">Add a service charge…</option>
            {Object.keys(grouped).map(g => (
              <optgroup key={g} label={g}>
                {grouped[g].map(sc => <option key={sc.id} value={sc.id}>{sc.label} — {window.FX.money(sc.amount, cur)}</option>)}
              </optgroup>
            ))}
          </select>
          <span style={{ position: "absolute", right: 11, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--fg-mute)" }}><Icon name="chevron-down" size={15} /></span>
        </div>
        <Button variant="primary" size="sm" icon="plus" onClick={addCharge} disabled={!sel}>Add</Button>
      </div>
      {charges.length > 0 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
          {charges.map(c => (
            <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", background: "var(--bg-mist)", borderRadius: "var(--r-sm)" }}>
              <span style={{ flex: 1, minWidth: 0 }}>
                <span style={{ display: "block", fontSize: 13, fontWeight: 500, color: "var(--fg-strong)" }}>{c.label}</span>
                <span style={{ display: "block", fontSize: 11.5, color: "var(--fg-mute)", fontFamily: "var(--font-mono)" }}>{window.FX.money(c.amount, cur)} each</span>
              </span>
              <div style={{ display: "flex", alignItems: "center", gap: 4, flex: "none" }}>
                <button onClick={() => setQty(c.id, (c.qty || 1) - 1)} style={{ width: 22, height: 22, borderRadius: 6, border: "none", background: "var(--surface)", color: "var(--fg-body)", fontWeight: 700 }}>−</button>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, width: 16, textAlign: "center" }}>{c.qty || 1}</span>
                <button onClick={() => setQty(c.id, (c.qty || 1) + 1)} style={{ width: 22, height: 22, borderRadius: 6, border: "none", background: "var(--surface)", color: "var(--fg-body)", fontWeight: 700 }}>+</button>
              </div>
              <span style={{ fontSize: 13, fontWeight: 700, color: "var(--fg-strong)", width: 64, textAlign: "right" }}>{window.FX.money(c.amount * (c.qty || 1), cur)}</span>
              <button onClick={() => remove(c.id)} style={{ background: "transparent", border: "none", color: "var(--fg-faint)", display: "inline-flex" }}><Icon name="x" size={14} /></button>
            </div>
          ))}
          <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 8, borderTop: "1px dashed var(--border)", marginTop: 3 }}>
            <span style={{ fontSize: 13, color: "var(--fg-mute)" }}>Charges total</span>
            <span style={{ fontSize: 14, fontWeight: 700, color: "var(--fg-strong)" }}>{window.FX.money(total, cur)}</span>
          </div>
        </div>
      )}
    </Card>
  );
}

/* ---------- call history & notes ---------- */
function NotesPanel({ booking, onUpdate }) {
  const [text, setText] = useStateBP("");
  const [kind, setKind] = useStateBP("Caller note");
  const log = booking.callLog || [];
  const store = bpLoad();
  const cu = (store.users || window.FX.CONSOLE_USERS || []).find(u => u.id === store.currentUserId) || {};
  const byName = cu.name || "CE console";
  function add() {
    if (!text.trim()) return;
    const entry = { id: "n" + Date.now(), kind, text: text.trim(), by: byName, at: new Date().toISOString() };
    onUpdate({ callLog: [entry, ...log] });
    setText("");
  }
  const kindMeta = { "Caller note": { tone: "accent", icon: "headset" }, "Note": { tone: "neutral", icon: "message-square" }, "Inbound call": { tone: "brand", icon: "phone" }, "Outbound call": { tone: "accent", icon: "phone" } };
  return (
    <div>
      <div style={{ display: "flex", gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
        {["Caller note", "Inbound call", "Outbound call", "Note"].map(k => (
          <button key={k} onClick={() => setKind(k)} style={{ padding: "6px 12px", borderRadius: "var(--r-pill)", border: "1px solid " + (kind === k ? "var(--brand)" : "var(--border)"), background: kind === k ? "var(--brand-soft)" : "var(--surface)", color: kind === k ? "var(--brand)" : "var(--fg-body)", fontSize: 12.5, fontWeight: 500 }}>{k}</button>
        ))}
      </div>
      <textarea value={text} onChange={e => setText(e.target.value)} rows={3} placeholder="Log a caller note or call outcome for this booking…" style={{ ...window.inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.45 }} />
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8 }}>
        <span style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>Saving as <strong style={{ color: "var(--fg-body)" }}>{byName}</strong> · now</span>
        <Button variant="primary" size="sm" icon="plus" onClick={add} disabled={!text.trim()}>Add to log</Button>
      </div>
      <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10 }}>
        {log.length === 0 && <div style={{ textAlign: "center", color: "var(--fg-mute)", fontSize: 13, padding: "16px 0" }}>No call history or notes yet.</div>}
        {log.map(e => {
          const m = kindMeta[e.kind] || kindMeta["Note"];
          return (
            <div key={e.id} style={{ display: "flex", gap: 11 }}>
              <span style={{ width: 30, height: 30, borderRadius: "50%", flex: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", background: "var(--brand-soft)", color: "var(--brand)" }}><Icon name={m.icon} size={14} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Badge tone={m.tone}>{e.kind}</Badge>
                  <span style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>{e.by} · {fmtWhen(e.at)}</span>
                </div>
                <div style={{ fontSize: 13.5, color: "var(--fg-body)", marginTop: 5, lineHeight: 1.45 }}>{e.text}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- shared bits ---------- */
function TopBar({ tracking }) {
  return (
    <header style={{ height: 60, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 24px", background: "var(--brand)", color: "#fff" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <Wordmark size={22} onDark />
        <span style={{ width: 1, height: 24, background: "rgba(255,255,255,0.2)" }} />
        <span style={{ fontWeight: 600, fontSize: 14.5 }}>Booking detail{tracking ? " · " + tracking : ""}</span>
      </div>
      <a href="Fedex CSR Console.html" style={{ fontSize: 13, color: "rgba(255,255,255,0.85)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="headset" size={15} /> Console</a>
    </header>
  );
}
function CardTitle({ icon, title, hint }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 13 }}>
      <Icon name={icon} size={16} color="var(--brand)" />
      <span style={{ fontSize: 14.5, fontWeight: 700, color: "var(--fg-strong)", flex: 1 }}>{title}</span>
      {hint && <Badge tone="brand">{hint}</Badge>}
    </div>
  );
}
function DetailRow({ label, value, top }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 14, padding: "8px 0", borderTop: top ? "none" : "1px solid var(--border)" }}>
      <span style={{ fontSize: 12.5, color: "var(--fg-mute)", flex: "none" }}>{label}</span>
      <span style={{ fontSize: 13, color: "var(--fg-strong)", fontWeight: 500, textAlign: "right" }}>{value}</span>
    </div>
  );
}
function StopBP({ accent, label, addr, time }) {
  return (
    <div style={{ display: "flex", gap: 11 }}>
      <span style={{ width: 26, height: 26, borderRadius: 8, background: accent, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="map-pin" size={14} /></span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>{label}{time ? " · " + time : ""}</div>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-strong)", marginTop: 2 }}>{addr.company || addr.contact}</div>
        <div style={{ fontSize: 12.5, color: "var(--fg-body)" }}>{addr.unit ? addr.unit + ", " : ""}{addr.line ? addr.line + ", " : ""}{addr.suburb}{addr.postcode ? " " + addr.postcode : ""}</div>
        {addr.contact && <div style={{ fontSize: 12, color: "var(--fg-mute)", marginTop: 2 }}>{addr.contact}{addr.phone ? " · " + addr.phone : ""}</div>}
        {addr.instructions && <div style={{ fontSize: 12, color: "var(--fg-body)", marginTop: 4, fontStyle: "italic", borderLeft: "2px solid var(--accent)", paddingLeft: 7 }}>{addr.instructions}</div>}
      </div>
    </div>
  );
}
function fmtWhen(iso) {
  try { const d = new Date(iso); return d.toLocaleDateString("en-AU", { day: "numeric", month: "short" }) + " · " + d.toLocaleTimeString("en-AU", { hour: "2-digit", minute: "2-digit" }); }
  catch (e) { return ""; }
}

ReactDOM.createRoot(document.getElementById("root")).render(<BookingPage />);
