/* EasyFly — Results screen (typed) */
;(() => {
const Ic = window.Ic;
const EF = window.EF;
const RouteArc = window.RouteArc;
const Stepper = window.Stepper;

function cityOf(code: string): string {
  const a = EF.AIRPORTS.find((x: Airport) => x.code === code);
  return a ? a.city : code;
}

interface ResultsProps {
  search: SearchState;
  set: SetState<SearchState>;
  go: (s: ScreenName) => void;
  selectFlight: (f: Flight) => void;
}

function FlightCard({ f, search, onSelect }: { f: Flight; search: SearchState; onSelect: () => void }) {
  const [open, setOpen] = React.useState<boolean>(false);
  return (
    <div className="card" style={{ padding: "var(--pad-card)", transition: "box-shadow .18s, border-color .18s" }}
      onMouseEnter={e=>{e.currentTarget.style.boxShadow="var(--shadow)";e.currentTarget.style.borderColor="var(--sky-200)";}}
      onMouseLeave={e=>{e.currentTarget.style.boxShadow="none";e.currentTarget.style.borderColor="var(--line)";}}>
      <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
        {/* airline + flight no */}
        <div style={{ display: "flex", flexDirection: "column", gap: 6, width: 96, flex: "0 0 auto" }}>
          <div className="logo-mark" style={{ width: 34, height: 34 }}><Ic.PlaneDiag s={18} c="#fff" /></div>
          <span className="mono" style={{ fontSize: 12, color: "var(--ink-400)", fontWeight: 600 }}>{f.id}</span>
        </div>
        {/* times */}
        <div style={{ display: "flex", alignItems: "center", gap: 18, flex: 1 }}>
          <div style={{ textAlign: "right" }}>
            <div className="mono" style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.02em" }}>{f.dep}</div>
            <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-400)", fontWeight: 600 }}>{search.from}</div>
          </div>
          <RouteArc dur={f.dur} stops={f.stops} w={180} />
          <div>
            <div className="mono" style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.02em" }}>{f.arr}</div>
            <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-400)", fontWeight: 600 }}>{search.to}</div>
          </div>
        </div>
        {/* meta */}
        <div style={{ display: "flex", flexDirection: "column", gap: 7, alignItems: "flex-start", width: 150, flex: "0 0 auto" }}>
          <span style={{ fontSize: 12.5, color: "var(--ink-500)" }}>{f.plane}</span>
          {f.via && <span className="pill" style={{ background: "var(--sky-100)", color: "var(--ink-500)", fontSize: 11.5 }}>via {f.via}</span>}
          {f.green && <span className="pill" style={{ background: "#e7f5ec", color: "#1f8a5b", fontSize: 11.5 }}><Ic.Leaf s={13} c="#1f8a5b"/> Éco-vol</span>}
        </div>
        {/* price + cta */}
        <div style={{ textAlign: "right", width: 150, flex: "0 0 auto" }}>
          <div style={{ fontSize: 12, color: "var(--ink-400)" }}>{f.cabin} · par pers.</div>
          <div className="mono" style={{ fontSize: 30, fontWeight: 700, color: "var(--navy-800)", letterSpacing: "-.02em" }}>{f.price} €</div>
          <button className="btn btn-primary" style={{ marginTop: 8, width: "100%" }} onClick={() => setOpen(o => !o)}>
            Sélectionner <Ic.Chevron s={15} c="#fff" dir={open ? "up" : "down"} />
          </button>
        </div>
      </div>
      {open && (
        <div style={{ marginTop: 18, paddingTop: 18, borderTop: "1px dashed var(--line)",
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
          {EF.FARES.map((fare: Fare) => (
            <button key={fare.id} onClick={onSelect} className="card" style={{ textAlign: "left", padding: 14,
              transition: "border-color .15s, background .15s" }}
              onMouseEnter={e=>{e.currentTarget.style.borderColor="var(--accent)";e.currentTarget.style.background="var(--sky-50)";}}
              onMouseLeave={e=>{e.currentTarget.style.borderColor="var(--line)";e.currentTarget.style.background="var(--card)";}}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>{fare.name}</span>
                <span className="mono" style={{ fontSize: 15, fontWeight: 700, color: "var(--accent)" }}>
                  {fare.price === 0 ? "inclus" : `+${fare.price} €`}</span>
              </div>
              {[fare.bag, fare.flex, fare.seat].map((line: string) => (
                <div key={line} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-500)", marginBottom: 4 }}>
                  <Ic.Check s={13} c="var(--blue-500)" /> {line}
                </div>
              ))}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function FilterGroup({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{ paddingBottom: 18, marginBottom: 18, borderBottom: "1px solid var(--line)" }}>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14.5, marginBottom: 12 }}>{title}</div>
      {children}
    </div>
  );
}

function Check({ label, count, on, set }: { label: string; count?: number; on: boolean; set: (b: boolean) => void }) {
  return (
    <button onClick={() => set(!on)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%",
      padding: "5px 0", textAlign: "left" }}>
      <span style={{ width: 19, height: 19, borderRadius: 6, border: on ? "none" : "1.6px solid var(--line)",
        background: on ? "var(--accent)" : "transparent", display: "grid", placeItems: "center", flex: "0 0 auto" }}>
        {on && <Ic.Check s={13} c="#fff" />}
      </span>
      <span style={{ fontSize: 13.5, color: "var(--ink-700)", flex: 1 }}>{label}</span>
      {count != null && <span className="mono" style={{ fontSize: 12, color: "var(--ink-400)" }}>{count}</span>}
    </button>
  );
}

function ResultsScreen({ search, set, go, selectFlight }: ResultsProps) {
  const [sort, setSort] = React.useState<"price" | "dep" | "dur">("price");
  const [directOnly, setDirectOnly] = React.useState<boolean>(false);
  const [maxPrice, setMaxPrice] = React.useState<number>(150);
  const [fEco, setFEco] = React.useState<boolean>(false);

  let list: Flight[] = EF.FLIGHTS.filter((f: Flight) =>
    (!directOnly || f.stops === 0) && f.price <= maxPrice && (!fEco || f.green));
  list = [...list].sort((a: Flight, b: Flight) =>
    sort === "price" ? a.price - b.price : sort === "dep" ? a.dep.localeCompare(b.dep) : a.dur.localeCompare(b.dur));

  const sorts: [typeof sort, string][] = [["price", "Moins cher"], ["dep", "Départ"], ["dur", "Plus rapide"]];

  return (
    <div className="screen-enter">
      {/* trip summary bar */}
      <div style={{ background: "var(--navy-800)", color: "#fff" }}>
        <div className="wrap" style={{ padding: "16px 28px", display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap" }}>
          <button className="btn" style={{ background: "rgba(255,255,255,.12)", color: "#fff", padding: "8px 14px" }} onClick={() => go("home")}>
            <Ic.Chevron s={15} c="#fff" dir="left" /> Modifier
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{search.from}</span>
            <Ic.Arrow s={16} c="rgba(255,255,255,.6)" />
            <span className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{search.to}</span>
            <span style={{ fontSize: 14, color: "rgba(255,255,255,.7)" }}>· {cityOf(search.from)} → {cityOf(search.to)}</span>
          </div>
          <span style={{ fontSize: 13.5, color: "rgba(255,255,255,.7)" }}>{search.dDate} · {search.pax} voy. · {search.cabin}</span>
          <div style={{ marginLeft: "auto" }}><Stepper step={1} /></div>
        </div>
      </div>

      <div className="wrap" style={{ padding: "28px 28px 0", display: "grid", gridTemplateColumns: "260px 1fr", gap: 26, alignItems: "start" }}>
        {/* filters */}
        <aside className="card" style={{ padding: 20, position: "sticky", top: 84 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 17 }}>Filtres</span>
            <button style={{ fontSize: 12.5, color: "var(--accent)", fontWeight: 700 }}
              onClick={() => { setDirectOnly(false); setMaxPrice(150); setFEco(false); }}>Réinitialiser</button>
          </div>
          <FilterGroup title="Escales">
            <Check label="Vol direct" count={EF.FLIGHTS.filter((f:Flight)=>f.stops===0).length} on={directOnly} set={setDirectOnly} />
            <Check label="1 escale" count={EF.FLIGHTS.filter((f:Flight)=>f.stops===1).length} on={!directOnly} set={()=>setDirectOnly(false)} />
          </FilterGroup>
          <FilterGroup title="Budget max">
            <input type="range" min={60} max={150} value={maxPrice} onChange={e => setMaxPrice(+e.target.value)}
              style={{ width: "100%", accentColor: "var(--accent)" }} />
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }}>
              <span style={{ fontSize: 12, color: "var(--ink-400)" }}>60 €</span>
              <span className="mono" style={{ fontSize: 14, fontWeight: 700, color: "var(--accent)" }}>≤ {maxPrice} €</span>
            </div>
          </FilterGroup>
          <FilterGroup title="Engagement">
            <Check label="Éco-vols uniquement" on={fEco} set={setFEco} />
          </FilterGroup>
          <div style={{ fontSize: 12.5, color: "var(--ink-400)", lineHeight: 1.5 }}>
            <Ic.Shield s={14} c="var(--blue-500)" style={{ verticalAlign: "-2px", marginRight: 6 }} />
            Annulation gratuite sous 24h sur tous les tarifs Flex.
          </div>
        </aside>

        {/* list */}
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <span style={{ fontSize: 14.5, color: "var(--ink-500)" }}>
              <b style={{ color: "var(--ink-900)" }}>{list.length} vols</b> trouvés · {search.dDate}
            </span>
            <div style={{ display: "flex", gap: 4, background: "var(--sky-100)", padding: 4, borderRadius: 999 }}>
              {sorts.map(([id, label]) => (
                <button key={id} onClick={() => setSort(id)} style={{ padding: "6px 14px", borderRadius: 999, fontSize: 13, fontWeight: 700,
                  background: sort === id ? "var(--card)" : "transparent", color: sort === id ? "var(--navy-800)" : "var(--ink-500)",
                  boxShadow: sort === id ? "var(--shadow-sm)" : "none" }}>{label}</button>
              ))}
            </div>
          </div>
          <div className="stagger" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {list.map((f: Flight, i: number) => (
              <div key={f.id} style={{ animationDelay: `${i * 50}ms` }}>
                <FlightCard f={f} search={search} onSelect={() => selectFlight(f)} />
              </div>
            ))}
            {list.length === 0 && (
              <div className="card" style={{ padding: 40, textAlign: "center", color: "var(--ink-400)" }}>
                Aucun vol ne correspond à vos filtres.
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ResultsScreen });
})();
