/* EasyFly — Payment + confirmation (typed) */
;(() => {
const Ic = window.Ic;
const EF = window.EF;
const Stepper = window.Stepper;

function cityName(code: string): string {
  const a = EF.AIRPORTS.find((x: Airport) => x.code === code);
  return a ? a.city : code;
}
function seatSupp(seats: string[]): number {
  return seats.reduce((n, id) => {
    const row = parseInt(id, 10);
    return n + (row <= 4 ? 18 : (row === 10 || row === 11) ? 12 : 6);
  }, 0);
}

interface PayProps {
  search: SearchState;
  booking: BookingState;
  setBooking: SetState<BookingState>;
  go: (s: ScreenName) => void;
}

function Field({ label, ph, w, value, onChange, mono }:
  { label: string; ph: string; w?: string; value: string; onChange: (v: string) => void; mono?: boolean }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6, flex: w ? `0 0 ${w}` : "1 1 160px" }}>
      <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-500)" }}>{label}</span>
      <input value={value} placeholder={ph} onChange={e => onChange(e.target.value)}
        className={mono ? "mono" : ""}
        style={{ padding: "11px 13px", borderRadius: 10, border: "1.5px solid var(--line)", fontSize: 14.5,
          background: "var(--card)", outline: "none", transition: "border-color .15s", color: "var(--ink-900)" }}
        onFocus={e => e.currentTarget.style.borderColor = "var(--blue-400)"}
        onBlur={e => e.currentTarget.style.borderColor = "var(--line)"} />
    </label>
  );
}

function PaymentScreen({ search, booking, setBooking, go }: PayProps) {
  const [pax, setPax] = React.useState({ first: "", last: "", email: "", phone: "" });
  const [pay, setPay] = React.useState({ num: "", name: "", exp: "", cvc: "" });
  const upd = (set: any) => (k: string) => (v: string) => set((p: any) => ({ ...p, [k]: v }));

  const f = booking.flight as Flight;
  const fare = (booking.fare || EF.FARES[1]) as Fare;
  const n = search.pax;
  const base = f ? f.price * n : 0;
  const fareSup = fare.price * n;
  const seats = seatSupp(booking.seats);
  const taxes = Math.round(base * 0.18) + 12 * n;
  const total = base + fareSup + seats + taxes;

  const valid = pax.first && pax.last && pax.email && pay.num.length >= 12;

  return (
    <div className="screen-enter">
      <div style={{ background: "var(--navy-800)", color: "#fff" }}>
        <div className="wrap" style={{ padding: "16px 28px", display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
          <button className="btn" style={{ background: "rgba(255,255,255,.12)", color: "#fff", padding: "8px 14px" }} onClick={() => go("seats")}>
            <Ic.Chevron s={15} c="#fff" dir="left" /> Sièges
          </button>
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17 }}>Finalisez votre réservation</span>
          <div style={{ marginLeft: "auto" }}><Stepper step={3} /></div>
        </div>
      </div>

      <div className="wrap" style={{ padding: "30px 28px", display: "grid", gridTemplateColumns: "1fr 360px", gap: 30, alignItems: "start" }}>
        {/* forms */}
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <section className="card" style={{ padding: 24 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
              <span style={{ width: 28, height: 28, borderRadius: 999, background: "var(--sky-100)", color: "var(--blue-600)",
                display: "grid", placeItems: "center" }}><Ic.User s={16} /></span>
              <h3 style={{ fontSize: 17, fontWeight: 800 }}>Passager principal</h3>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 14 }}>
              <Field label="Prénom" ph="Camille" value={pax.first} onChange={upd(setPax)("first")} />
              <Field label="Nom" ph="Durand" value={pax.last} onChange={upd(setPax)("last")} />
              <Field label="E-mail" ph="camille@mail.fr" value={pax.email} onChange={upd(setPax)("email")} />
              <Field label="Téléphone" ph="06 12 34 56 78" value={pax.phone} onChange={upd(setPax)("phone")} />
            </div>
          </section>

          <section className="card" style={{ padding: 24 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
              <span style={{ width: 28, height: 28, borderRadius: 999, background: "var(--sky-100)", color: "var(--blue-600)",
                display: "grid", placeItems: "center" }}><Ic.Card s={16} /></span>
              <h3 style={{ fontSize: 17, fontWeight: 800 }}>Paiement</h3>
              <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--ink-400)" }}>
                <Ic.Lock s={14} /> Paiement chiffré
              </span>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 14 }}>
              <Field label="Numéro de carte" ph="4242 4242 4242 4242" w="100%" mono value={pay.num} onChange={upd(setPay)("num")} />
              <Field label="Titulaire" ph="CAMILLE DURAND" value={pay.name} onChange={upd(setPay)("name")} />
              <Field label="Expiration" ph="12/29" w="110px" mono value={pay.exp} onChange={upd(setPay)("exp")} />
              <Field label="CVC" ph="123" w="90px" mono value={pay.cvc} onChange={upd(setPay)("cvc")} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16 }}>
              {["Visa", "Mastercard", "Amex"].map(b => (
                <span key={b} className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-400)",
                  border: "1.5px solid var(--line)", borderRadius: 6, padding: "4px 9px" }}>{b}</span>
              ))}
            </div>
          </section>

          <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 12.5, color: "var(--ink-400)", padding: "0 4px" }}>
            <Ic.Shield s={15} c="var(--blue-500)" /> En réservant, vous acceptez les conditions de transport EasyFly. Démonstration — aucun paiement réel.
          </div>
        </div>

        {/* boarding-pass summary */}
        <aside style={{ position: "sticky", top: 84, display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ borderRadius: "var(--radius-lg)", overflow: "hidden", boxShadow: "var(--shadow-lg)" }}>
            <div style={{ background: "var(--navy-800)", color: "#fff", padding: "18px 20px", position: "relative" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 14, letterSpacing: ".04em" }}>CARTE D'EMBARQUEMENT</span>
                <Ic.PlaneDiag s={20} c="#fff" />
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 16 }}>
                <div>
                  <div className="mono" style={{ fontSize: 28, fontWeight: 700 }}>{search.from}</div>
                  <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.6)" }}>{cityName(search.from)}</div>
                </div>
                <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center" }}>
                  <Ic.PlaneDiag s={18} c="var(--accent)" />
                  <div style={{ width: "100%", height: 1, borderTop: "1.5px dashed rgba(255,255,255,.3)", marginTop: 4 }} />
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono" style={{ fontSize: 28, fontWeight: 700 }}>{search.to}</div>
                  <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.6)" }}>{cityName(search.to)}</div>
                </div>
              </div>
            </div>
            {/* perforation */}
            <div style={{ background: "var(--card)", position: "relative", height: 0 }}>
              <div style={{ position: "absolute", left: -8, top: -8, width: 16, height: 16, borderRadius: 999, background: "var(--bg)" }} />
              <div style={{ position: "absolute", right: -8, top: -8, width: 16, height: 16, borderRadius: 999, background: "var(--bg)" }} />
            </div>
            <div style={{ background: "var(--card)", padding: "20px", borderTop: "1.5px dashed var(--line)" }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
                {([["VOL", f ? f.id : "—"], ["DATE", search.dDate], ["DÉPART", f ? f.dep : "—"], ["SIÈGE", booking.seats.length ? booking.seats.join(", ") : "auto"], ["TARIF", fare.name], ["VOY.", `${n}`]] as [string,string][]).map(([k, v]) => (
                  <div key={k}>
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--ink-400)", letterSpacing: ".05em" }}>{k}</div>
                    <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-900)" }}>{v}</div>
                  </div>
                ))}
              </div>

              {/* price breakdown */}
              <div style={{ display: "flex", flexDirection: "column", gap: 7, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
                {([["Vol "+(f?f.cabin:"")+" × "+n, base], ["Tarif "+fare.name, fareSup], ["Sièges", seats], ["Taxes & frais", taxes]] as [string,number][])
                  .filter(([, v]) => v > 0 || true).map(([k, v]) => (
                  <div key={k} style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                    <span style={{ color: "var(--ink-500)" }}>{k}</span>
                    <span className="mono" style={{ fontWeight: 600 }}>{v} €</span>
                  </div>
                ))}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 14,
                paddingTop: 14, borderTop: "2px solid var(--navy-800)" }}>
                <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16 }}>Total</span>
                <span className="mono" style={{ fontWeight: 800, fontSize: 26, color: "var(--navy-800)", letterSpacing: "-.02em" }}>{total} €</span>
              </div>
            </div>
          </div>

          <button className="btn btn-primary btn-lg btn-block" disabled={!valid}
            style={{ opacity: valid ? 1 : .5, cursor: valid ? "pointer" : "not-allowed" }}
            onClick={() => { setBooking(b => ({ ...b, fare })); go("confirm"); }}>
            <Ic.Lock s={16} c="#fff" /> Payer {total} €
          </button>
          {!valid && <span style={{ fontSize: 12, color: "var(--ink-400)", textAlign: "center" }}>Complétez vos informations pour continuer</span>}
        </aside>
      </div>
    </div>
  );
}

function ConfirmScreen({ search, booking, go }: { search: SearchState; booking: BookingState; go: (s: ScreenName) => void }) {
  const f = booking.flight as Flight;
  const ref = "EF" + Math.random().toString(36).slice(2, 8).toUpperCase();
  return (
    <div className="screen-enter" style={{ minHeight: "70vh", display: "grid", placeItems: "center", padding: "60px 28px" }}>
      <div style={{ maxWidth: 540, textAlign: "center" }}>
        <div style={{ width: 76, height: 76, borderRadius: 999, background: "#e7f5ec", display: "grid", placeItems: "center",
          margin: "0 auto 22px", animation: "riseIn .6s both" }}>
          <Ic.Check s={40} c="#1f8a5b" />
        </div>
        <h1 style={{ fontSize: 34, fontWeight: 800, letterSpacing: "-.02em" }}>Réservation confirmée !</h1>
        <p style={{ fontSize: 16, color: "var(--ink-500)", marginTop: 12, lineHeight: 1.6 }}>
          Votre vol <b className="mono" style={{ color: "var(--navy-800)" }}>{f ? f.id : ""}</b> de {cityName(search.from)} à {cityName(search.to)} est réservé.
          Un e-mail de confirmation et vos cartes d'embarquement vous attendent.
        </p>
        <div className="card" style={{ display: "inline-flex", alignItems: "center", gap: 14, padding: "16px 24px", marginTop: 26 }}>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-400)" }}>RÉFÉRENCE</span>
          <span className="mono" style={{ fontSize: 24, fontWeight: 800, color: "var(--accent)", letterSpacing: ".06em" }}>{ref}</span>
        </div>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 30 }}>
          <button className="btn btn-navy btn-lg">Télécharger les billets</button>
          <button className="btn btn-ghost btn-lg" onClick={() => go("home")}>Retour à l'accueil</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PaymentScreen, ConfirmScreen });
})();
