/* EasyFly — Seat selection (typed) */
;(() => {
const Ic = window.Ic;
const EF = window.EF;
const Stepper = window.Stepper;

type SeatClass = "premium" | "legroom" | "standard";
interface SeatInfo { id: string; row: number; col: string; cls: SeatClass; price: number; taken: boolean; }

const COLS = ["A", "B", "C", "D", "E", "F"];
const ROWS = 26;
const TAKEN = new Set<string>([
  "1A","1F","2C","3D","4B","4E","6A","7F","8C","9D","11B","12E","12F",
  "14A","15C","16D","18B","19E","20A","21F","22C","23D","24E","25A","25B",
]);

function seatPrice(cls: SeatClass): number { return cls === "premium" ? 18 : cls === "legroom" ? 12 : 6; }
function seatClass(row: number): SeatClass { return row <= 4 ? "premium" : (row === 10 || row === 11) ? "legroom" : "standard"; }

const SEAT_FILL: Record<string, string> = {
  premium: "#dbe8fb", legroom: "#e7f5ec", standard: "var(--card)",
};
const SEAT_LINE: Record<string, string> = {
  premium: "#9cc0f5", legroom: "#9bd6b4", standard: "var(--line)",
};

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

function Seat({ s, selected, onClick }: { s: SeatInfo; selected: boolean; onClick: () => void }) {
  const base: React.CSSProperties = {
    width: 34, height: 34, borderRadius: "8px 8px 6px 6px", fontSize: 11, fontFamily: "var(--font-mono)",
    fontWeight: 700, display: "grid", placeItems: "center", transition: "transform .12s, background .12s",
    cursor: s.taken ? "not-allowed" : "pointer",
  };
  if (s.taken) return <div style={{ ...base, background: "#eef1f5", color: "#c4ccd6", cursor: "not-allowed",
    border: "1.5px solid #e4e8ee" }}>×</div>;
  if (selected) return <button style={{ ...base, background: "var(--accent)", color: "#fff",
    border: "1.5px solid var(--accent)", boxShadow: "0 4px 10px -3px var(--accent)" }} onClick={onClick}>{s.col}</button>;
  return (
    <button style={{ ...base, background: SEAT_FILL[s.cls], color: "var(--ink-700)", border: `1.5px solid ${SEAT_LINE[s.cls]}` }}
      onClick={onClick}
      onMouseEnter={e=>e.currentTarget.style.transform="translateY(-2px)"}
      onMouseLeave={e=>e.currentTarget.style.transform="none"}>{s.col}</button>
  );
}

function SeatsScreen({ search, booking, setBooking, go }: SeatsProps) {
  const need: number = search.pax;
  const selected: string[] = booking.seats;

  const toggle = (s: SeatInfo) => {
    setBooking((b: BookingState) => {
      const has = b.seats.includes(s.id);
      if (has) return { ...b, seats: b.seats.filter(x => x !== s.id) };
      if (b.seats.length >= need) return { ...b, seats: [...b.seats.slice(1), s.id] };
      return { ...b, seats: [...b.seats, s.id] };
    });
  };

  const seatObjs: SeatInfo[] = selected.map(id => {
    const row = parseInt(id, 10); const col = id.replace(/[0-9]/g, "");
    const cls = seatClass(row); return { id, row, col, cls, price: seatPrice(cls), taken: false };
  });
  const seatTotal: number = seatObjs.reduce((n, s) => n + s.price, 0);
  const f = booking.flight as Flight;

  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("results")}>
            <Ic.Chevron s={15} c="#fff" dir="left" /> Vols
          </button>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span className="mono" style={{ fontSize: 18, fontWeight: 700 }}>{search.from}</span>
            <Ic.Arrow s={15} c="rgba(255,255,255,.6)" />
            <span className="mono" style={{ fontSize: 18, fontWeight: 700 }}>{search.to}</span>
            <span className="mono" style={{ fontSize: 13, color: "rgba(255,255,255,.6)", marginLeft: 6 }}>{f ? f.id : ""} · {f ? f.plane : ""}</span>
          </div>
          <div style={{ marginLeft: "auto" }}><Stepper step={2} /></div>
        </div>
      </div>

      <div className="wrap" style={{ padding: "30px 28px", display: "grid", gridTemplateColumns: "1fr 320px", gap: 30, alignItems: "start" }}>
        {/* cabin */}
        <div>
          <div style={{ textAlign: "center", marginBottom: 8 }}>
            <h2 style={{ fontSize: 24, fontWeight: 800 }}>Choisissez vos sièges</h2>
            <p style={{ fontSize: 14, color: "var(--ink-500)", marginTop: 4 }}>
              {selected.length}/{need} sélectionné{selected.length > 1 ? "s" : ""} — touchez un siège pour le choisir
            </p>
          </div>

          {/* legend */}
          <div style={{ display: "flex", gap: 18, justifyContent: "center", marginBottom: 20, flexWrap: "wrap" }}>
            {([["premium","Premium +18 €"],["legroom","Espace +12 €"],["standard","Standard +6 €"]] as [SeatClass,string][]).map(([c,l]) => (
              <span key={c} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-500)" }}>
                <span style={{ width: 16, height: 16, borderRadius: 5, background: SEAT_FILL[c], border: `1.5px solid ${SEAT_LINE[c]}` }} />{l}
              </span>
            ))}
            <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-500)" }}>
              <span style={{ width: 16, height: 16, borderRadius: 5, background: "#eef1f5", border: "1.5px solid #e4e8ee" }} />Occupé
            </span>
          </div>

          {/* fuselage */}
          <div style={{ maxWidth: 420, margin: "0 auto", background: "var(--card)", border: "1px solid var(--line)",
            borderRadius: "60px 60px 18px 18px", padding: "44px 26px 26px", boxShadow: "var(--shadow)", position: "relative" }}>
            <div style={{ position: "absolute", top: 14, left: "50%", transform: "translateX(-50%)",
              display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "var(--ink-400)", fontWeight: 600 }}>
              <Ic.PlaneDiag s={15} c="var(--ink-400)" /> Avant de l'appareil
            </div>
            {/* column header */}
            <div style={{ display: "flex", justifyContent: "center", gap: 7, marginBottom: 10 }}>
              {COLS.map((c, i) => (
                <React.Fragment key={c}>
                  <span className="mono" style={{ width: 34, textAlign: "center", fontSize: 11, color: "var(--ink-400)", fontWeight: 700 }}>{c}</span>
                  {i === 2 && <span style={{ width: 22 }} />}
                </React.Fragment>
              ))}
            </div>
            {Array.from({ length: ROWS }, (_, r) => {
              const row = r + 1; const cls = seatClass(row);
              return (
                <div key={row} style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 7, marginBottom: 7 }}>
                  {COLS.map((col, i) => {
                    const id = `${row}${col}`;
                    const seat: SeatInfo = { id, row, col, cls, price: seatPrice(cls), taken: TAKEN.has(id) };
                    return (
                      <React.Fragment key={id}>
                        <Seat s={seat} selected={selected.includes(id)} onClick={() => toggle(seat)} />
                        {i === 2 && <span className="mono" style={{ width: 22, textAlign: "center", fontSize: 10.5, color: "var(--ink-400)" }}>{row}</span>}
                      </React.Fragment>
                    );
                  })}
                </div>
              );
            })}
          </div>
        </div>

        {/* summary */}
        <aside style={{ position: "sticky", top: 84, display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card" style={{ padding: 20 }}>
            <h3 style={{ fontSize: 17, fontWeight: 800, marginBottom: 14 }}>Vos sièges</h3>
            {seatObjs.length === 0 && (
              <p style={{ fontSize: 13.5, color: "var(--ink-400)", lineHeight: 1.5 }}>
                Aucun siège sélectionné. Vous pouvez aussi laisser EasyFly placer votre groupe automatiquement.
              </p>
            )}
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {seatObjs.map(s => (
                <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 11px",
                  background: "var(--sky-50)", borderRadius: 10 }}>
                  <span className="mono" style={{ width: 36, height: 36, borderRadius: 8, background: "var(--accent)", color: "#fff",
                    display: "grid", placeItems: "center", fontWeight: 700, fontSize: 13 }}>{s.id}</span>
                  <span style={{ flex: 1 }}>
                    <span style={{ display: "block", fontSize: 13.5, fontWeight: 700, textTransform: "capitalize" }}>
                      {s.cls === "premium" ? "Premium" : s.cls === "legroom" ? "Espace +" : "Standard"}</span>
                    <span style={{ fontSize: 11.5, color: "var(--ink-400)" }}>Rangée {s.row}</span>
                  </span>
                  <span className="mono" style={{ fontWeight: 700, fontSize: 14, color: "var(--navy-800)" }}>+{s.price} €</span>
                </div>
              ))}
            </div>
            {seatObjs.length > 0 && (
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, paddingTop: 14, borderTop: "1px dashed var(--line)" }}>
                <span style={{ fontWeight: 700, fontSize: 14 }}>Supplément sièges</span>
                <span className="mono" style={{ fontWeight: 700, fontSize: 16, color: "var(--accent)" }}>+{seatTotal} €</span>
              </div>
            )}
          </div>
          <button className="btn btn-primary btn-lg btn-block" onClick={() => go("payment")}>
            Continuer <Ic.Arrow s={16} c="#fff" />
          </button>
          <button className="btn btn-ghost btn-block" onClick={() => { setBooking(b => ({ ...b, seats: [] })); go("payment"); }}>
            Placement automatique
          </button>
        </aside>
      </div>
    </div>
  );
}

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