/* flights — live (generated) results with filters, sort, fare details, Book → checkout */

function FlightLogo({ f }) {
  const color = f.color || "#444";
  return (
    <div style={{ width: 46, height: 46, borderRadius: 12, background: color + "1A", color, display: "grid", placeItems: "center", fontWeight: 800, fontSize: 15, fontFamily: "var(--sans)", flexShrink: 0 }}>{f.code}</div>
  );
}

function FlightCard({ f }) {
  const { t, lang } = useLang();
  const { nav, setPendingBooking, searchCtx } = useStore();
  const [open, setOpen] = React.useState(false);
  const travelers = searchCtx.travelers || 1;
  const total = f.price * travelers;
  const airline = lang === "ar" ? f.airlineAr : f.airline;
  const book = () => {
    setPendingBooking({ type: "flight", item: f, amount: total, unit: f.price, travelers, title: `${f.from} → ${f.to} · ${airline} ${f.id}`, date: searchCtx.depart });
    nav("booking");
  };
  return (
    <div className="card hover-lift fcard-wrap" style={{ overflow: "hidden" }}>
      <div className="fcard" style={{ padding: "22px 26px", display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 26, alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <FlightLogo f={f} />
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{airline}</div>
            <div className="muted" style={{ fontSize: 12.5 }}>{f.id} · {f.aircraft}</div>
          </div>
        </div>

        <div className="fcard-route" style={{ display: "flex", alignItems: "center", gap: 20, justifyContent: "center" }}>
          <div style={{ textAlign: "end" }}>
            <div style={{ fontSize: 26, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{f.dep}</div>
            <div className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>{f.from}</div>
          </div>
          <div style={{ flex: 1, minWidth: 110, textAlign: "center" }}>
            <div className="muted" style={{ fontSize: 12 }}>{f.dur}</div>
            <div style={{ position: "relative", height: 2, background: "var(--line-2)", margin: "8px 0", borderRadius: 2 }}>
              <span style={{ position: "absolute", insetInline: 0, top: -5, display: "flex", justifyContent: f.stops ? "center" : "flex-end" }}>
                <Icon name="plane" size={15} color="var(--emerald)" className="plane-route" style={{ background: "var(--card)" }} />
              </span>
            </div>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: f.stops ? "var(--gold-d)" : "var(--ok)" }}>{f.stops ? (f.stops > 1 ? t("flights.stops", { n: f.stops }) : t("flights.stop", { n: f.stops })) + " · " + f.layover : t("flights.nonstop")}</div>
          </div>
          <div style={{ textAlign: "start" }}>
            <div style={{ fontSize: 26, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{f.arr}{f.nextDay ? <sup style={{ fontSize: 11, color: "var(--gold-d)" }}>+1</sup> : null}</div>
            <div className="muted" style={{ fontSize: 12.5, fontWeight: 600 }}>{f.to}</div>
          </div>
        </div>

        <div className="fcard-price" style={{ textAlign: "end", minWidth: 160 }}>
          <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", marginBottom: 6 }}>
            <span className={"chip " + (f.cabin === "Business" ? "chip-gold" : "chip-emerald")} style={{ padding: "3px 10px", fontSize: 11.5 }}>{f.cabin === "Business" ? t("cabin.business") : t("cabin.economy")}</span>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: "var(--ink)" }}><Money value={f.price} /></div>
          {travelers > 1 && <div className="muted" style={{ fontSize: 12 }}>{t("flights.perPerson")} · {t("flights.totalFor", { n: travelers })} <Money value={total} sar={false} /></div>}
          <button className="btn btn-primary btn-sm" style={{ marginTop: 10 }} onClick={book}>{t("book.now")} <Icon name="arrow" size={15} className="flip-rtl" /></button>
        </div>
      </div>
      <button onClick={() => setOpen(o => !o)} className="fcard-detail-toggle" style={{ width: "100%", border: "none", borderTop: "1px solid var(--line)", background: "var(--paper)", padding: "10px 26px", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 12.5, color: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Icon name="shield" size={14} color="var(--emerald)" /> {t("flights.onTime", { n: f.on })} · {t("flights.refundable")}</span>
        <span style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform .2s", display: "inline-grid" }}><Icon name="arrow" size={14} style={{ transform: "rotate(90deg)" }} /></span>
      </button>
      {open && (
        <div style={{ padding: "16px 26px 20px", background: "var(--paper)", borderTop: "1px solid var(--line)", display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(150px,1fr))", gap: 16 }}>
          {[["clock", t("flights.depTime"), f.dep + " → " + f.arr], ["plane", t("flights.aircraft"), f.aircraft], ["bag", t("flights.baggage"), f.cabin === "Business" ? t("flights.baggage.business") : t("flights.baggage.economy")], ["shield", t("flights.fareType"), f.cabin === "Business" ? t("flights.fare.flex") : t("flights.fare.saver")]].map(([ic, k, v]) => (
            <div key={k} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name={ic} size={16} color="var(--gold-d)" style={{ marginTop: 2, flexShrink: 0 }} />
              <div><div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".08em" }}>{k}</div><div style={{ fontSize: 13.5, fontWeight: 600 }}>{v}</div></div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ResultsHeader({ title, sub, onEdit }) {
  const { t } = useLang();
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16, marginBottom: 24 }}>
      <div>
        <h1 style={{ fontFamily: "var(--serif)", fontSize: 34, fontWeight: 600 }}>{title}</h1>
        <p className="muted" style={{ marginTop: 4 }}>{sub}</p>
      </div>
      <button className="btn btn-ghost btn-sm" onClick={onEdit}><Icon name="search" size={15} /> {t("flights.modify")}</button>
    </div>
  );
}

function FilterPanel({ children }) {
  return <aside className="card card-pad sticky-aside" style={{ position: "sticky", top: 92, alignSelf: "start" }}>{children}</aside>;
}

/* desktop: sticky sidebar. mobile: a "Filters" button + slide-up bottom sheet so
   results are visible immediately. */
function FilterShell({ children, count }) {
  const { isMobile } = useStore();
  const { t } = useLang();
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [open]);
  if (!isMobile) return <FilterPanel>{children}</FilterPanel>;
  return (
    <>
      <button className="btn btn-ghost" onClick={() => setOpen(true)} style={{ width: "100%", justifyContent: "center", marginBottom: 4 }}>
        <Icon name="search" size={16} /> {t("flights.refine")}
      </button>
      {open && (
        <div className="sheet-overlay" onClick={() => setOpen(false)} role="dialog" aria-modal="true" aria-label={t("flights.refine")}>
          <div className="sheet" onClick={(e) => e.stopPropagation()}>
            <div className="sheet-head">
              <strong style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{t("flights.refine")}</strong>
              <button onClick={() => setOpen(false)} aria-label={t("common.close")} style={{ background: "var(--paper-2)", border: "none", width: 34, height: 34, borderRadius: "50%", display: "grid", placeItems: "center", cursor: "pointer" }}><Icon name="x" size={18} /></button>
            </div>
            <div className="sheet-body">{children}</div>
            <div className="sheet-foot">
              <button className="btn btn-primary btn-block btn-lg" onClick={() => setOpen(false)}>{typeof count === "number" ? t("filters.show", { n: count }) : t("common.close")}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* merge live/local flights with the local carrier catalog (Arabic name, brand colour, distance) */
function enrichFlight(f) {
  const c = (window.CARRIERS || []).find((x) => x.code === f.code);
  let dist = f.distance || 0;
  if (!dist && window.apByCode && window.haversine) { const a = apByCode(f.from), b = apByCode(f.to); if (a && b) dist = haversine(a, b); }
  return { ...f, airlineAr: f.airlineAr || (c ? c.ar : f.airline), color: f.color || (c ? c.color : "#6A5234"), distance: dist };
}

/* live Amadeus results when the GDS key is configured, else the local engine */
function useLiveFlights(ctx) {
  const localGen = () => (window.generateFlights ? generateFlights({ from: ctx.from, to: ctx.to, date: ctx.depart }) : []).map(enrichFlight);
  const [state, setState] = React.useState(() => ({ flights: localGen(), source: "local", loading: false }));
  React.useEffect(() => {
    let alive = true;
    if (!window.apiConfig) { setState({ flights: localGen(), source: "local", loading: false }); return; }
    setState((s) => ({ ...s, loading: true }));
    (async () => {
      const cfg = await apiConfig();
      if (!alive) return;
      if (!providerLive("gds")) { setState({ flights: localGen(), source: "local", loading: false }); return; }
      const r = await apiFlights({ from: ctx.from, to: ctx.to, date: ctx.depart, adults: ctx.travelers, cabin: ctx.cabin });
      if (!alive) return;
      if (r && r.flights && r.flights.length) setState({ flights: r.flights.map(enrichFlight), source: "amadeus", loading: false });
      else setState({ flights: localGen(), source: "local", loading: false });
    })();
    return () => { alive = false; };
    // eslint-disable-next-line
  }, [ctx.from, ctx.to, ctx.depart, ctx.travelers, ctx.cabin]);
  return state;
}

function FlightsPage() {
  const { t, lang } = useLang();
  const { searchCtx, airportByCode } = useStore();
  const { flights: all, source, loading } = useLiveFlights(searchCtx);
  const [sort, setSort] = React.useState("price");
  const [nonstop, setNonstop] = React.useState(false);
  const [cabins, setCabins] = React.useState({ Economy: searchCtx.cabin !== "Business", Business: searchCtx.cabin !== "Economy" });
  const [bands, setBands] = React.useState({ morning: true, afternoon: true, evening: true });
  const [airlineSel, setAirlineSel] = React.useState({});
  const [maxPrice, setMaxPrice] = React.useState(0);
  const [showSearch, setShowSearch] = React.useState(false);

  const airlines = React.useMemo(() => {
    const map = {}; all.forEach(f => { map[f.code] = lang === "ar" ? f.airlineAr : f.airline; }); return map;
  }, [all, lang]);
  const priceMax = React.useMemo(() => all.reduce((m, f) => Math.max(m, f.price), 0), [all]);
  React.useEffect(() => { setMaxPrice(priceMax); }, [priceMax]);
  React.useEffect(() => { setAirlineSel(Object.keys(airlines).reduce((o, c) => (o[c] = true, o), {})); }, [Object.keys(airlines).join(",")]);

  const bandOf = (m) => m < 720 ? "morning" : m < 1080 ? "afternoon" : "evening";
  let list = all.filter(f =>
    (!nonstop || f.stops === 0) && cabins[f.cabin] && bands[bandOf(f.depMin)] &&
    (airlineSel[f.code] !== false) && (!maxPrice || f.price <= maxPrice)
  );
  list = [...list].sort((a, b) => sort === "price" ? a.price - b.price : sort === "dur" ? a.durMin - b.durMin : a.depMin - b.depMin);
  const from = airportByCode(searchCtx.from), to = airportByCode(searchCtx.to);
  const cityName = (a) => lang === "ar" ? a.ar : a.city;

  return (
    <main style={{ paddingTop: 96, minHeight: "100vh", background: "var(--paper)" }}>
      <div className="wrap" style={{ paddingTop: 28, paddingBottom: 70 }}>
        {showSearch && <div style={{ marginBottom: 24 }}><SmartSearch compact /></div>}
        <ResultsHeader
          title={t("flights.results", { from: cityName(from), to: cityName(to) })}
          sub={t("flights.sub", { depart: searchCtx.depart, travelers: t("search.travelersN", { n: searchCtx.travelers }), count: list.length })}
          onEdit={() => setShowSearch(s => !s)} />
        {source === "amadeus" && <div style={{ marginTop: -12, marginBottom: 18 }}><span className="chip chip-emerald" style={{ fontSize: 12 }}><span className="badge-dot" style={{ background: "var(--ok)" }}></span> {lang === "ar" ? "أسعار مباشرة · أماديوس" : "Live fares · Amadeus"}</span></div>}

        <div className="split" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 28, alignItems: "start" }}>
          <FilterShell count={list.length}>
            <div className="hide-mobile" style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 600, marginBottom: 16 }}>{t("flights.refine")}</div>
            <div className="filt-h">{t("flights.sortBy")}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 18 }}>
              {[["price", t("flights.sort.price")], ["dep", t("flights.sort.dep")], ["dur", t("flights.sort.dur")]].map(([v, l]) => (
                <label key={v} className="filt-row"><input type="radio" name="sort" checked={sort === v} onChange={() => setSort(v)} style={{ accentColor: "var(--emerald)" }} /> {l}</label>
              ))}
            </div>
            <div className="hr" style={{ margin: "4px 0 16px" }}></div>
            <label className="filt-row" style={{ marginBottom: 14 }}><input type="checkbox" checked={nonstop} onChange={e => setNonstop(e.target.checked)} style={{ accentColor: "var(--emerald)" }} /> {t("flights.nonstopOnly")}</label>

            <div className="filt-h">{t("flights.cabin")}</div>
            {[["Economy", t("cabin.economy")], ["Business", t("cabin.business")]].map(([c, l]) => (
              <label key={c} className="filt-row" style={{ marginBottom: 8 }}><input type="checkbox" checked={cabins[c]} onChange={e => setCabins(p => ({ ...p, [c]: e.target.checked }))} style={{ accentColor: "var(--emerald)" }} /> {l}</label>
            ))}

            <div className="filt-h" style={{ marginTop: 16 }}>{t("flights.depTime")}</div>
            {[["morning", "06–12"], ["afternoon", "12–18"], ["evening", "18–24"]].map(([b, l]) => (
              <label key={b} className="filt-row" style={{ marginBottom: 8 }}><input type="checkbox" checked={bands[b]} onChange={e => setBands(p => ({ ...p, [b]: e.target.checked }))} style={{ accentColor: "var(--emerald)" }} /> {l}</label>
            ))}

            {Object.keys(airlines).length > 1 && <>
              <div className="filt-h" style={{ marginTop: 16 }}>{t("flights.airlines")}</div>
              {Object.keys(airlines).map(c => (
                <label key={c} className="filt-row" style={{ marginBottom: 8 }}><input type="checkbox" checked={airlineSel[c] !== false} onChange={e => setAirlineSel(p => ({ ...p, [c]: e.target.checked }))} style={{ accentColor: "var(--emerald)" }} /> {airlines[c]}</label>
              ))}
            </>}

            {priceMax > 0 && <>
              <div className="filt-h" style={{ marginTop: 16 }}>{t("flights.priceRange")}: <Money value={maxPrice || priceMax} sar={false} /></div>
              <input type="range" min={Math.min(...all.map(f => f.price)) || 0} max={priceMax} value={maxPrice || priceMax} onChange={e => setMaxPrice(+e.target.value)} style={{ width: "100%", accentColor: "var(--emerald)" }} />
            </>}

            <div className="hr" style={{ margin: "18px 0" }}></div>
            <div className="chip chip-emerald" style={{ width: "100%", justifyContent: "center" }}><Icon name="shield" size={14} /> {t("flights.corpRates")}</div>
          </FilterShell>

          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {loading && all.length === 0
              ? [0, 1, 2].map(i => <div key={i} className="card" style={{ height: 120, background: "linear-gradient(90deg,var(--paper-2),var(--card),var(--paper-2))", backgroundSize: "200% 100%", animation: "shimmer 1.3s linear infinite" }} />)
              : <>
                  {list.map(f => <FlightCard key={f.id} f={f} />)}
                  {list.length === 0 && <div className="card card-pad center muted">{t("flights.empty")}</div>}
                </>}
          </div>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { FlightsPage, FlightCard, ResultsHeader, FilterPanel, FilterShell, FlightLogo });
