// csr-flights.jsx — operator flight lookup: search by flight number or port. Data via AirLabs.
const { useState: useStateFl, useMemo: useMemoFl } = React;

function FlightStatusPill({ status }) {
  const m = (window.FX.FLIGHT_STATUS && window.FX.FLIGHT_STATUS[status]) || { label: status, tone: "neutral", dot: "var(--fg-mute)" };
  return <Badge tone={m.tone}><StatusDot color={m.dot} pulse={status === "en-route"} /> {m.label}</Badge>;
}

function FlightTime({ f, which }) {
  const sched = which === "dep" ? f.dep_hm : f.arr_hm;
  const est = which === "dep" ? f.dep_est_hm : f.arr_est_hm;
  const delayed = f.delay > 0;
  return (
    <span>
      <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: delayed ? "var(--fg-faint)" : "var(--fg-strong)", textDecoration: delayed ? "line-through" : "none" }}>{sched}</span>
      {delayed && <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700, color: "#a36a00" }}>{est}</span>}
    </span>
  );
}

function CsrFlights() {
  const [mode, setMode] = useStateFl("number");
  const [num, setNum] = useStateFl("");
  const [port, setPort] = useStateFl("SYD");
  const [dir, setDir] = useStateFl("all");
  const [statusF, setStatusF] = useStateFl("all");
  const [carrier, setCarrier] = useStateFl("qf");   // Qantas-only by default (contract); VA/JQ available

  const results = useMemoFl(() => {
    if (mode === "number") return num.trim() ? window.FX.searchFlights({ number: num.trim() }) : [];
    return window.FX.searchFlights({ port, dir });
  }, [mode, num, port, dir]);
  const byCarrier = carrier === "qf" ? results.filter(f => f.airline_iata === "QF") : results;
  const filtered = statusF === "all" ? byCarrier : byCarrier.filter(f => f.status === statusF);

  const ports = window.FX.AIRPORT_CODES;
  const GRID = "1.05fr 1.7fr 0.85fr 0.85fr 0.95fr 0.95fr";
  const selStyle = { width: "auto", minWidth: 0, paddingTop: 9, paddingBottom: 9, fontSize: 13.5 };

  return (
    <div className="fade-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
        <div>
          <Eyebrow>Customer service</Eyebrow>
          <h1 style={{ margin: "9px 0 0", fontSize: 25, fontWeight: 700, letterSpacing: "-0.6px", color: "var(--fg-strong)" }}>Flight search</h1>
          <p style={{ margin: "7px 0 0", fontSize: 14.5, color: "var(--fg-mute)" }}>Look up any domestic flight by number or port to confirm times, status and gate.</p>
        </div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 13px", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-pill)" }}>
          <StatusDot color="var(--success)" pulse />
          <span style={{ fontSize: 12, color: "var(--fg-mute)" }}>Live data ·</span>
          <span style={{ fontWeight: 700, fontSize: 12.5, color: "var(--fg-strong)", letterSpacing: "0.2px" }}>AirLabs</span>
        </div>
      </div>

      <Card pad={18} style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 8, marginBottom: 15 }}>
          {[["number", "By flight number", "navigation"], ["port", "By port", "plane"]].map(([k, lbl, ic]) => (
            <button key={k} onClick={() => setMode(k)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 16px", borderRadius: "var(--r-pill)", border: "1.5px solid " + (mode === k ? "var(--brand)" : "var(--border)"), background: mode === k ? "var(--brand-soft)" : "var(--surface)", color: mode === k ? "var(--brand)" : "var(--fg-body)", fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap" }}>
              <Icon name={ic} size={15} /> {lbl}
            </button>
          ))}
        </div>

        {mode === "number" ? (
          <div style={{ position: "relative", maxWidth: 360 }}>
            <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={16} /></span>
            <TextInput value={num} onChange={setNum} placeholder="e.g. QF423" mono style={{ paddingLeft: 38, textTransform: "uppercase" }} />
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600, color: "var(--fg-mute)", marginBottom: 8, fontFamily: "var(--font-mono)", letterSpacing: "0.6px", textTransform: "uppercase" }}>Port</div>
              <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
                {ports.map(p => (
                  <button key={p} onClick={() => setPort(p)} style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 1, padding: "8px 14px", borderRadius: "var(--r-md)", border: "1.5px solid " + (port === p ? "var(--accent)" : "var(--border)"), background: port === p ? "var(--accent-soft)" : "var(--surface)", color: port === p ? "var(--accent-700)" : "var(--fg-body)" }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13.5 }}>{p}</span>
                    <span style={{ fontSize: 10.5, color: port === p ? "var(--accent-700)" : "var(--fg-mute)" }}>{window.FX.AIRPORT_BY_CODE[p].city}</span>
                  </button>
                ))}
              </div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              {[["all", "All"], ["dep", "Departures"], ["arr", "Arrivals"]].map(([k, lbl]) => (
                <button key={k} onClick={() => setDir(k)} style={{ padding: "7px 14px", borderRadius: "var(--r-pill)", fontSize: 12.5, fontWeight: 500, border: "1px solid " + (dir === k ? "var(--brand)" : "var(--border)"), background: dir === k ? "var(--brand-soft)" : "var(--surface)", color: dir === k ? "var(--brand)" : "var(--fg-mute)" }}>{lbl}</button>
              ))}
            </div>
          </div>
        )}
      </Card>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 11, gap: 12, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <div style={{ fontSize: 13, color: "var(--fg-mute)" }}><strong style={{ color: "var(--fg-strong)" }}>{filtered.length}</strong> flight{filtered.length === 1 ? "" : "s"}{mode === "port" ? ` · ${port} ${window.FX.AIRPORT_BY_CODE[port].city}` : ""}</div>
          {mode === "port" && (window.FX.AIRPORT_BY_CODE[port].dgOutbound
            ? <Badge tone="success"><StatusDot color="#22b86e" /> DG-approved outbound</Badge>
            : <Badge tone="danger"><Icon name="alert-triangle" size={11} /> No DG freight outbound</Badge>)}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ display: "inline-flex", gap: 4, background: "var(--bg-mist)", padding: 3, borderRadius: "var(--r-pill)" }}>
            {[["qf", "Qantas only"], ["all", "All carriers"]].map(([k, l]) => (
              <button key={k} onClick={() => setCarrier(k)} style={{ padding: "5px 11px", borderRadius: "var(--r-pill)", border: "none", fontSize: 12, fontWeight: 600, background: carrier === k ? "var(--surface)" : "transparent", color: carrier === k ? "var(--brand)" : "var(--fg-mute)", boxShadow: carrier === k ? "var(--shadow-xs)" : "none" }}>{l}</button>
            ))}
          </div>
          <Select value={statusF} onChange={setStatusF} style={selStyle} options={[{ value: "all", label: "All statuses" }, { value: "scheduled", label: "Scheduled" }, { value: "boarding", label: "Boarding" }, { value: "en-route", label: "En route" }, { value: "landed", label: "Landed" }]} />
        </div>
      </div>

      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: GRID, gap: 10, padding: "12px 20px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
          <span>Flight</span><span>Route</span><span>Departs</span><span>Arrives</span><span>Status</span><span>Aircraft · gate</span>
        </div>
        {filtered.map((f, i) => (
          <div key={f.flight_iata + i} style={{ display: "grid", gridTemplateColumns: GRID, gap: 10, padding: "13px 20px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
            <span style={{ minWidth: 0 }}>
              <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 13.5, fontWeight: 700, color: "var(--brand)" }}>{f.flight_iata}</span>
              <span style={{ display: "block", fontSize: 11.5, color: "var(--fg-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.airline_name}</span>
            </span>
            <span style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13.5, color: "var(--fg-strong)" }}>{f.dep_iata}</span>
              <span style={{ flex: "none", display: "inline-flex", alignItems: "center" }}><Icon name="plane" size={14} color="var(--accent)" /></span>
              <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 13.5, color: "var(--fg-strong)" }}>{f.arr_iata}</span>
              <span style={{ fontSize: 11.5, color: "var(--fg-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.dep_city} → {f.arr_city}</span>
            </span>
            <FlightTime f={f} which="dep" />
            <FlightTime f={f} which="arr" />
            <span><FlightStatusPill status={f.status} /></span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-body)" }}>{f.aircraft}<span style={{ color: "var(--fg-faint)" }}> · {f.terminal}/{f.gate}</span></span>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 44, textAlign: "center" }}>
            <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--bg-mist)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px", color: "var(--fg-faint)" }}><Icon name="plane" size={24} /></div>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-strong)" }}>{mode === "number" && !num.trim() ? "Search for a flight" : "No flights found"}</div>
            <div style={{ fontSize: 13, color: "var(--fg-mute)", marginTop: 4 }}>{mode === "number" ? "Enter a flight number like QF423 or VA800." : "Try another port or direction."}</div>
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { CsrFlights, FlightStatusPill, FlightTime });
