/* EasyFly — Home screen with flight search (typed) */
;(() => {
const Ic = window.Ic;
const EF = window.EF;

interface AirportFieldProps { label: string; value: string; onChange: (v: string) => void; icon: JSX.Element; }

function AirportField({ label, value, onChange, icon }: AirportFieldProps) {
  const [open, setOpen] = React.useState<boolean>(false);
  const ap = EF.AIRPORTS.find((a: Airport) => a.code === value) as Airport;
  return (
    <div style={{ position: "relative", flex: 1, minWidth: 0 }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: "100%", textAlign: "left", padding: "12px 14px", borderRadius: "var(--radius-sm)",
        background: "var(--sky-50)", border: "1.5px solid transparent", display: "flex", alignItems: "center", gap: 11,
        transition: "border .15s",
      }} onMouseEnter={e=>e.currentTarget.style.borderColor="var(--sky-200)"}
         onMouseLeave={e=>e.currentTarget.style.borderColor="transparent"}>
        <span style={{ color: "var(--blue-500)", flex: "0 0 auto" }}>{icon}</span>
        <span style={{ minWidth: 0 }}>
          <span style={{ display: "block", fontSize: 11, fontWeight: 700, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: ".06em" }}>{label}</span>
          <span style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
            <span className="mono" style={{ fontWeight: 700, fontSize: 17, color: "var(--ink-900)" }}>{value}</span>
            <span style={{ fontSize: 13.5, color: "var(--ink-500)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ap.city}</span>
          </span>
        </span>
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }} />
          <div className="card" style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, zIndex: 31,
            boxShadow: "var(--shadow-lg)", maxHeight: 280, overflowY: "auto", padding: 6 }}>
            {EF.AIRPORTS.map((a: Airport) => (
              <button key={a.code} onClick={() => { onChange(a.code); setOpen(false); }} style={{
                width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 12, padding: "9px 11px",
                borderRadius: 9, background: a.code === value ? "var(--sky-100)" : "transparent",
              }} onMouseEnter={e=>e.currentTarget.style.background="var(--sky-50)"}
                 onMouseLeave={e=>e.currentTarget.style.background=a.code===value?"var(--sky-100)":"transparent"}>
                <span className="mono" style={{ fontWeight: 700, fontSize: 14, width: 38, color: "var(--navy-700)" }}>{a.code}</span>
                <span><span style={{ fontSize: 14, fontWeight: 600, color: "var(--ink-900)" }}>{a.city}</span>
                  <span style={{ fontSize: 12, color: "var(--ink-400)", marginLeft: 7 }}>{a.country}</span></span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

interface SearchFormProps { state: SearchState; set: SetState<SearchState>; onSearch: () => void; compact?: boolean; }

function SearchForm({ state, set, onSearch, compact }: SearchFormProps) {
  const tabs: [TripType, string][] = [["round", "Aller-retour"], ["oneway", "Aller simple"], ["multi", "Multi-destinations"]];
  const swap = () => set(s => ({ ...s, from: s.to, to: s.from }));
  return (
    <div className="card" style={{ padding: compact ? 16 : 22, boxShadow: "var(--shadow-lg)", borderRadius: "var(--radius-lg)" }}>
      {!compact && (
        <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
          {tabs.map(([id, label]) => (
            <button key={id} onClick={() => set(s => ({ ...s, trip: id }))} style={{
              padding: "8px 16px", borderRadius: 999, fontSize: 13.5, fontWeight: 700, letterSpacing: "-.01em", whiteSpace: "nowrap",
              background: state.trip === id ? "var(--navy-800)" : "transparent",
              color: state.trip === id ? "#fff" : "var(--ink-500)",
            }}>{label}</button>
          ))}
        </div>
      )}
      <div style={{ display: "flex", gap: 10, alignItems: "stretch", flexWrap: "wrap" }}>
        <div style={{ display: "flex", flex: "2 1 380px", gap: 0, position: "relative", alignItems: "center" }}>
          <AirportField label="Départ" value={state.from} icon={<Ic.Plane s={18} />}
            onChange={v => set(s => ({ ...s, from: v }))} />
          <button onClick={swap} title="Inverser" style={{
            flex: "0 0 auto", width: 38, height: 38, borderRadius: 999, background: "var(--card)",
            border: "1.5px solid var(--line)", display: "grid", placeItems: "center", color: "var(--blue-500)",
            margin: "0 -14px", zIndex: 5, boxShadow: "var(--shadow-sm)", transition: "transform .2s",
          }} onMouseEnter={e=>e.currentTarget.style.transform="rotate(180deg)"}
             onMouseLeave={e=>e.currentTarget.style.transform="none"}>
            <Ic.Swap s={16} />
          </button>
          <AirportField label="Arrivée" value={state.to} icon={<Ic.Pin s={18} />}
            onChange={v => set(s => ({ ...s, to: v }))} />
        </div>
        <DateField label="Aller" value={state.dDate} onChange={v=>set(s=>({...s,dDate:v}))} />
        {state.trip === "round" && <DateField label="Retour" value={state.rDate} onChange={v=>set(s=>({...s,rDate:v}))} />}
        <PaxField state={state} set={set} />
        <button className="btn btn-primary" style={{ flex: "0 0 auto", padding: "0 24px", minHeight: 62, borderRadius: "var(--radius)" }}
          onClick={onSearch}>
          <Ic.Search s={19} c="#fff" /> Rechercher
        </button>
      </div>
    </div>
  );
}

interface DateFieldProps { label: string; value: string; onChange: (v: string) => void; }
function DateField({ label, value }: DateFieldProps) {
  return (
    <label style={{ flex: "1 1 130px", minWidth: 120, padding: "12px 14px", borderRadius: "var(--radius-sm)",
      background: "var(--sky-50)", display: "flex", alignItems: "center", gap: 11, cursor: "pointer" }}>
      <span style={{ color: "var(--blue-500)" }}><Ic.Cal s={18} /></span>
      <span style={{ minWidth: 0 }}>
        <span style={{ display: "block", fontSize: 11, fontWeight: 700, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: ".06em" }}>{label}</span>
        <span style={{ fontSize: 15, fontWeight: 700, color: "var(--ink-900)" }}>{value}</span>
      </span>
    </label>
  );
}

function PaxField({ state, set }: { state: SearchState; set: SetState<SearchState> }) {
  const [open, setOpen] = React.useState<boolean>(false);
  return (
    <div style={{ position: "relative", flex: "1 1 140px", minWidth: 130 }}>
      <button onClick={() => setOpen(o => !o)} style={{ width: "100%", height: "100%", textAlign: "left",
        padding: "12px 14px", borderRadius: "var(--radius-sm)", background: "var(--sky-50)", display: "flex", alignItems: "center", gap: 11 }}>
        <span style={{ color: "var(--blue-500)" }}><Ic.User s={18} /></span>
        <span>
          <span style={{ display: "block", fontSize: 11, fontWeight: 700, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: ".06em" }}>Voyageurs</span>
          <span style={{ fontSize: 15, fontWeight: 700, color: "var(--ink-900)" }}>{state.pax} · {state.cabin}</span>
        </span>
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }} />
          <div className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, width: 260, zIndex: 31,
            boxShadow: "var(--shadow-lg)", padding: 16 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>Passagers</span>
              <PaxStepper v={state.pax} min={1} max={9} onCh={v => set(s => ({ ...s, pax: v }))} />
            </div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-400)", marginBottom: 8 }}>Cabine</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {["Économie", "Premium", "Affaires"].map(c => (
                <button key={c} onClick={() => set(s => ({ ...s, cabin: c }))} style={{
                  textAlign: "left", padding: "9px 12px", borderRadius: 9, fontSize: 14, fontWeight: 600,
                  background: state.cabin === c ? "var(--sky-100)" : "transparent",
                  color: state.cabin === c ? "var(--navy-700)" : "var(--ink-700)",
                  border: state.cabin === c ? "1.5px solid var(--sky-200)" : "1.5px solid transparent",
                }}>{c}</button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function PaxStepper({ v, min, max, onCh }: { v: number; min: number; max: number; onCh: (n: number) => void }) {
  const btn: React.CSSProperties = { width: 28, height: 28, borderRadius: 999, border: "1.5px solid var(--line)",
    display: "grid", placeItems: "center", fontSize: 18, color: "var(--navy-700)", lineHeight: 1 };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <button style={btn} onClick={() => onCh(Math.max(min, v - 1))}>–</button>
      <span className="mono" style={{ fontWeight: 700, width: 14, textAlign: "center" }}>{v}</span>
      <button style={btn} onClick={() => onCh(Math.min(max, v + 1))}>+</button>
    </div>
  );
}

function CityArt({ hue, code }: { hue: number; code: string }) {
  const id = `sky-${code}`;
  return (
    <svg viewBox="0 0 400 168" preserveAspectRatio="xMidYMid slice"
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={`hsl(${hue} 66% 56%)`} />
          <stop offset="1" stopColor={`hsl(${hue + 18} 72% 80%)`} />
        </linearGradient>
      </defs>
      <rect width="400" height="168" fill={`url(#${id})`} />
      <circle cx="316" cy="46" r="24" fill={`hsl(${hue} 92% 76%)`} opacity="0.9" />
      <ellipse cx="92" cy="38" rx="34" ry="8.5" fill="rgba(255,255,255,.5)" />
      <ellipse cx="148" cy="56" rx="22" ry="6.5" fill="rgba(255,255,255,.34)" />
      <path d="M0 168 V150 Q100 118 200 150 T400 146 V168 Z" fill={`hsl(${hue} 42% 46%)`} opacity="0.55" />
      <path d="M0 168 V122 H22 V98 H40 V130 H64 V106 H86 V142 H108 V90 H120 L128 72 L136 90 V134 H158 V112 H180 V152 H200 V94 H222 V126 H246 V102 H268 V140 H290 V114 H312 V148 H334 V100 H356 V128 H380 V110 H400 V168 Z"
        fill={`hsl(${hue} 56% 27%)`} />
    </svg>
  );
}

function DestCard({ d, onClick }: { d: Destination; onClick: () => void }) {
  const [img, setImg] = React.useState<string>("");
  const [ready, setReady] = React.useState<boolean>(false);
  React.useEffect(() => {
    let alive = true;
    const title = d.wiki || d.city;
    fetch(`https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&piprop=thumbnail&pithumbsize=900&titles=${encodeURIComponent(title)}&origin=*`)
      .then(r => r.json())
      .then((j: any) => {
        const pages = (j && j.query && j.query.pages) || {};
        const first: any = Object.values(pages)[0];
        const src: string | undefined = first && first.thumbnail && first.thumbnail.source;
        if (alive && src) setImg(src);
      })
      .catch(() => {});
    return () => { alive = false; };
  }, [d.code]);
  return (
    <button onClick={onClick} className="card" style={{ textAlign: "left", overflow: "hidden", padding: 0,
      transition: "transform .18s, box-shadow .18s", display: "block", width: "100%" }}
      onMouseEnter={e=>{e.currentTarget.style.transform="translateY(-4px)";e.currentTarget.style.boxShadow="var(--shadow-lg)";}}
      onMouseLeave={e=>{e.currentTarget.style.transform="none";e.currentTarget.style.boxShadow="none";}}>
      <div style={{ height: 168, position: "relative", overflow: "hidden", display: "flex", alignItems: "flex-end", padding: 14 }}>
        <CityArt hue={d.hue} code={d.code} />
        {img && (
          <img src={img} alt={d.city} referrerPolicy="no-referrer" loading="lazy"
            onLoad={() => setReady(true)} onError={() => setImg("")}
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover",
              opacity: ready ? 1 : 0, transition: "opacity .6s ease", display: "block" }} />
        )}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(8,18,35,0) 34%, rgba(8,18,35,.62))" }} />
        <span className="mono" style={{ position: "absolute", top: 12, right: 12, fontSize: 12, fontWeight: 700,
          color: "#fff", background: "rgba(8,18,35,.32)", padding: "3px 8px", borderRadius: 6, backdropFilter: "blur(2px)" }}>{d.code}</span>
        <div style={{ position: "relative", color: "#fff", textShadow: "0 1px 8px rgba(8,18,35,.45)" }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22, letterSpacing: "-.02em" }}>{d.city}</div>
          <div style={{ fontSize: 12.5, color: "rgba(255,255,255,.88)" }}>{d.country}</div>
        </div>
      </div>
      <div style={{ padding: "13px 16px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--ink-500)" }}>
          <Ic.Clock s={14} /> {d.dur} · direct
        </span>
        <span style={{ fontSize: 13, color: "var(--ink-500)" }}>dès <b className="mono" style={{ fontSize: 16, color: "var(--accent)" }}>{d.price} €</b></span>
      </div>
    </button>
  );
}

interface HomeProps { search: SearchState; set: SetState<SearchState>; go: (s: ScreenName) => void; }

function HomeScreen({ search, set, go }: HomeProps) {
  return (
    <div className="screen-enter">
      <section style={{ background: "linear-gradient(150deg, var(--hero-from), var(--hero-to))", position: "relative", overflow: "hidden" }}>
        <DottedRoutes />
        <div className="wrap" style={{ padding: "62px 28px 132px", position: "relative" }}>
          <div className="pill" style={{ background: "rgba(255,255,255,.14)", color: "var(--hero-ink)", marginBottom: 18 }}>
            <Ic.Leaf s={14} c="currentColor" /> Compagnie nationale · 220 destinations
          </div>
          <h1 style={{ fontSize: 52, lineHeight: 1.04, color: "var(--hero-ink)", maxWidth: 720, fontWeight: 800 }}>
            L'Europe à portée d'aile,<br/>le monde à votre rythme.
          </h1>
          <p style={{ fontSize: 18, color: "var(--hero-sub)", maxWidth: 480, marginTop: 16, lineHeight: 1.55 }}>
            Réservez en quelques secondes, choisissez votre siège et embarquez l'esprit léger.
          </p>
        </div>
      </section>

      <div className="wrap" style={{ position: "relative", marginTop: -78, zIndex: 10 }}>
        <SearchForm state={search} set={set} onSearch={() => go("results")} />
      </div>

      <div className="wrap" style={{ marginTop: 26, display: "flex", gap: 30, flexWrap: "wrap", justifyContent: "center" }}>
        {([[<Ic.Shield s={18}/>,"Réservation sécurisée"],[<Ic.Bag s={18}/>,"Bagage cabine inclus"],
          [<Ic.Wifi s={16}/>,"Wi-Fi à bord"],[<Ic.Leaf s={16}/>,"Flotte renouvelée -18% CO₂"]] as [JSX.Element,string][]).map(([ic,t])=>(
          <span key={t} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 14, fontWeight: 600, color: "var(--ink-500)" }}>
            <span style={{ color: "var(--blue-500)" }}>{ic}</span>{t}
          </span>
        ))}
      </div>

      <section className="wrap" style={{ marginTop: 60 }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 22 }}>
          <div>
            <div className="pill" style={{ background: "var(--sky-100)", color: "var(--blue-600)", marginBottom: 10 }}>Au départ de Paris</div>
            <h2 style={{ fontSize: 30, fontWeight: 800 }}>Destinations populaires</h2>
          </div>
          <button className="btn btn-ghost">Toutes les destinations <Ic.Arrow s={15} /></button>
        </div>
        <div className="stagger" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18 }}>
          {EF.DESTINATIONS.map((d: Destination, i: number) => (
            <div key={d.code} style={{ animationDelay: `${i * 60}ms` }}>
              <DestCard d={d} onClick={() => { set(s => ({ ...s, to: d.code })); go("results"); }} />
            </div>
          ))}
        </div>
      </section>

      <section className="wrap" style={{ marginTop: 56 }}>
        <div style={{ borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--navy-800)",
          display: "grid", gridTemplateColumns: "1.3fr 1fr", color: "#fff", position: "relative" }}>
          <div style={{ padding: "44px 46px" }}>
            <div className="pill" style={{ background: "var(--accent)", color: "#fff", marginBottom: 16 }}>EasyFly Club</div>
            <h2 style={{ fontSize: 30, fontWeight: 800, lineHeight: 1.1, maxWidth: 380 }}>Cumulez des miles, voyagez plus loin.</h2>
            <p style={{ fontSize: 15.5, color: "rgba(255,255,255,.7)", maxWidth: 380, marginTop: 14, lineHeight: 1.55 }}>
              Embarquement prioritaire, bagage offert et 2 000 miles de bienvenue dès votre inscription.
            </p>
            <button className="btn btn-primary btn-lg" style={{ marginTop: 24 }}>Rejoindre le Club</button>
          </div>
          <div style={{ background: "linear-gradient(135deg, var(--blue-500), var(--navy-700))", position: "relative" }}>
            <Ic.PlaneDiag s={120} c="rgba(255,255,255,.16)" style={{ position: "absolute", right: 30, top: "50%", transform: "translateY(-50%) rotate(-18deg)" }} />
          </div>
        </div>
      </section>
    </div>
  );
}

function DottedRoutes() {
  const PLANE = "M2.5 13.5 21 4 13 19.5l-2.6-5.3-2.4 3.1-1.2-.4.5-3.6L2.5 13.5Z";
  const top = "M-20 300 Q 400 90 1220 240";
  const bot = "M-20 360 Q 600 140 1220 60";
  return (
    <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} preserveAspectRatio="none" viewBox="0 0 1200 360" fill="none">
      <path d={top} stroke="rgba(255,255,255,.20)" strokeWidth="1.5" strokeDasharray="3 7" />
      <path d={bot} stroke="rgba(255,255,255,.13)" strokeWidth="1.5" strokeDasharray="3 7" />
      <circle cx="980" cy="120" r="3" fill="rgba(255,255,255,.5)" />
      <circle cx="250" cy="220" r="3" fill="rgba(255,255,255,.4)" />
      {/* plane flying along the top route */}
      <g>
        <g transform="scale(1.5) rotate(27) translate(-12 -12)">
          <path d={PLANE} fill="rgba(255,255,255,.9)" />
        </g>
        <animateMotion dur="16s" repeatCount="indefinite" rotate="auto" path={top} keyPoints="0;1" keyTimes="0;1" calcMode="linear" />
      </g>
      {/* second, smaller plane on the lower route */}
      <g opacity="0.5">
        <g transform="scale(1.1) rotate(27) translate(-12 -12)">
          <path d={PLANE} fill="rgba(255,255,255,.85)" />
        </g>
        <animateMotion dur="22s" begin="-8s" repeatCount="indefinite" rotate="auto" path={bot} calcMode="linear" />
      </g>
    </svg>
  );
}

Object.assign(window, { HomeScreen, SearchForm });
})();
