/* ============================================================
   RESERVATIONS — interactive 2-floor PINK PONY floor plan +
   mobile-first, app-style booking wizard.
   variant: "guided" (stepper, default) | "quick" (single screen)
   ============================================================ */
const PRICE = (tier, night) => window.PP.tablePrice(tier, night);
const ZACCENT = { regular: "#CBA35C", vip: "#FF6B5B", stage: "#FF2E88", mezz: "#9333EA", skybox: "#5FBFA8" };
const FLOORS = [
  { id: "main", label: { en: "Main Floor", es: "Planta Principal" }, icon: "store" },
  { id: "second", label: { en: "Second Floor", es: "Segundo Piso" }, icon: "layers" },
];

/* ---------- one interactive table node ---------- */
function TableNode({ tb, sel, onPick, night, idx }) {
  const accent = ZACCENT[tb.zone] || "#CBA35C";
  const booked = tb.status === "booked" || tb.status === "closed";
  const held = tb.status === "held";
  const isDiamond = tb.shape === "diamond";
  const big = tb.zone === "vip" || tb.zone === "skybox";
  const w = big ? 58 : tb.seats >= 6 ? 48 : 40;
  const h = isDiamond ? w : (tb.seats >= 6 ? 38 : 32);
  const price = PRICE(tb.zone, night);
  const bg = sel ? accent : booked ? "rgba(255,255,255,.035)" : accent + "26";
  const border = sel ? "#fff" : booked ? "rgba(255,255,255,.14)" : held ? "#E8A33C" : accent;

  return (
    <button disabled={booked} onClick={() => onPick(tb)} title={tb.id + (booked ? "" : " · $" + price + "++")}
      className={"tbl-pop absolute flex items-center justify-center group " + (!booked && !sel ? "tbl-avail" : "")}
      style={{
        left: tb.x + "%", top: tb.y + "%", width: w, height: h,
        transform: `translate(-50%,-50%) ${isDiamond ? "rotate(45deg)" : ""} scale(${sel ? 1.16 : 1})`,
        background: bg, border: (held && !sel ? "1.5px dashed " : "1.5px solid ") + border,
        borderRadius: isDiamond ? 9 : 8,
        color: sel ? "#0B0B0C" : booked ? "rgba(255,255,255,.4)" : accent,
        cursor: booked ? "not-allowed" : "pointer",
        boxShadow: sel ? `0 0 0 3px ${accent}55, 0 0 26px ${accent}` : "none",
        transition: "transform .25s cubic-bezier(.16,1,.3,1), background .2s, box-shadow .25s",
        zIndex: sel ? 6 : 2, animationDelay: (idx % 12) * 28 + "ms", WebkitTapHighlightColor: "transparent",
      }}>
      <span style={{ transform: isDiamond ? "rotate(-45deg)" : "none" }} className="flex flex-col items-center leading-none pointer-events-none">
        <span className="font-extrabold" style={{ fontSize: big ? 9 : 10, color: sel ? "#0B0B0C" : "#fff" }}>{tb.id}</span>
        {booked
          ? <Icon name="lock" className="w-2.5 h-2.5 mt-0.5" />
          : <span className="font-semibold" style={{ fontSize: 7, marginTop: 1, color: sel ? "#0B0B0C" : "rgba(255,255,255,.65)" }}>{tb.seats}p</span>}
      </span>
    </button>
  );
}

/* ---------- per-floor scenery ---------- */
function FloorScene({ floor }) {
  const t = useT();
  if (floor === "main") return (
    <React.Fragment>
      <div className="absolute flex items-center justify-center rounded-md" style={{ left: "4%", top: "5%", width: "30%", height: "8%", background: "linear-gradient(90deg,#7a2350,#b23a6e)", border: "1px solid #ff6bb0" }}><span className="label text-white text-[9px]">{t("MAIN BAR", "BARRA")}</span></div>
      <div className="absolute flex items-center justify-center rounded-md" style={{ right: "3%", top: "40%", width: "8%", height: "20%", background: "linear-gradient(180deg,#7a2350,#b23a6e)", border: "1px solid #ff6bb0" }}><span className="label text-white text-[8px] [writing-mode:vertical-rl] rotate-180">DJ</span></div>
      <div className="absolute" style={{ left: "52%", top: "52%", width: "26%", height: "26%", transform: "translate(-50%,-50%)" }}>
        <div className="w-full h-full rounded-full flex items-center justify-center" style={{ background: "repeating-linear-gradient(45deg,#ff2e88,#ff2e88 3px,#d61f6f 3px,#d61f6f 6px)", boxShadow: "0 0 34px rgba(255,46,136,.55)" }}><span className="font-black text-white text-[11px] tracking-widest drop-shadow">STAGE</span></div>
      </div>
    </React.Fragment>
  );
  return (
    <React.Fragment>
      <div className="absolute flex items-center justify-center rounded-md" style={{ right: "3%", top: "34%", width: "9%", height: "34%", background: "linear-gradient(180deg,#4a2a6e,#6b3a9e)", border: "1px solid #b07bff" }}><span className="label text-white text-[8px] [writing-mode:vertical-rl] rotate-180">{t("BAR #2", "BARRA #2")}</span></div>
      <div className="absolute flex items-center justify-center rounded-full" style={{ left: "40%", top: "66%", width: "16%", height: "22%", transform: "translate(-50%,-50%)", background: "radial-gradient(circle,#5FBFA855,#0d0d0f)", border: "1.5px dashed #5FBFA8" }}><span className="font-black text-[#5FBFA8] text-[9px] tracking-wider">VIEW</span></div>
      <div className="absolute label text-white/30 text-[8px]" style={{ left: "3%", top: "5%" }}>{t("MEZZANINE", "MEZZANINE")}</div>
    </React.Fragment>
  );
}

/* ---------- interactive floor plan with switcher ---------- */
function FloorPlan({ tables, selected, onPick, night, floor, setFloor }) {
  const t = useT(); const { lang } = useLang();
  const list = tables.filter((x) => x.floor === floor);
  const avail = (fl) => tables.filter((x) => x.floor === fl && x.status !== "booked" && x.status !== "closed").length;
  const zonesHere = [...new Set(list.map((x) => x.zone))];

  return (
    <div>
      {/* floor switcher */}
      <div className="flex gap-2 mb-3.5 p-1 rounded-2xl bg-card border border-white/10">
        {FLOORS.map((fl) => {
          const on = floor === fl.id;
          return (
            <button key={fl.id} onClick={() => setFloor(fl.id)} className={"flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-[12px] font-bold uppercase tracking-[0.1em] transition-all " + (on ? "bg-coral text-white shadow-[0_6px_20px_-6px_rgba(255,107,91,.7)]" : "text-white/55 hover:text-white")}>
              <Icon name={fl.icon} className="w-4 h-4" />
              <span>{L(fl.label, lang)}</span>
              <span className={"text-[9px] px-1.5 py-0.5 rounded-full " + (on ? "bg-white/25" : "bg-white/8")}>{avail(fl.id)}</span>
            </button>
          );
        })}
      </div>

      {/* the map */}
      <div key={floor} className="floor-in relative w-full rounded-2xl overflow-hidden border-2 bg-[#101012]" style={{ aspectRatio: floor === "main" ? "1 / 0.9" : "1 / 0.78", borderColor: floor === "main" ? "var(--c-coral)" : "#9333EA" }}>
        <div className="absolute inset-0 opacity-[0.04]" style={{ backgroundImage: "linear-gradient(#fff 1px,transparent 0),linear-gradient(90deg,#fff 1px,transparent 0)", backgroundSize: "32px 32px" }}></div>
        <FloorScene floor={floor} />
        {list.map((tb, i) => <TableNode key={tb.id} tb={tb} sel={selected === tb.id} onPick={onPick} night={night} idx={i} />)}

        {/* legend */}
        <div className="absolute left-[3%] bottom-[3%] flex flex-col gap-1 bg-black/55 backdrop-blur rounded-lg p-2.5 border border-white/10">
          {zonesHere.map((z) => {
            const zn = window.PP.ZONES.find((x) => x.id === z);
            return <div key={z} className="flex items-center gap-2 text-[9px] text-white/75"><span className="w-2.5 h-2.5 rounded-sm" style={{ background: ZACCENT[z] + "33", border: `1px solid ${ZACCENT[z]}` }}></span>{zn ? L(zn.name, lang) : z}</div>;
          })}
          <div className="flex items-center gap-2 text-[9px] text-white/45 pt-1 mt-0.5 border-t border-white/10"><Icon name="lock" className="w-2.5 h-2.5" />{t("Booked", "Reservada")}</div>
        </div>
      </div>
      <p className="text-center text-white/35 text-[11px] mt-2.5">{t("Tap an available table to select it", "Toca una mesa disponible para elegirla")}</p>
    </div>
  );
}

/* ---------- selection detail (side card + mobile sheet) ---------- */
function SelectionDetail({ tb, price, guests, lang }) {
  const t = useT();
  const zn = window.PP.ZONES.find((z) => z.id === tb.zone);
  const accent = ZACCENT[tb.zone];
  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <div>
          <div className="label text-[10px]" style={{ color: accent }}>{zn ? L(zn.name, lang) : tb.zone}</div>
          <div className="text-2xl font-black uppercase leading-none mt-0.5">{t("Table", "Mesa")} {tb.id}</div>
        </div>
        <div className="text-right"><div className="serif text-3xl" style={{ color: accent }}>${price}</div><div className="label text-white/40 text-[9px]">{t("minimum", "mínimo")}</div></div>
      </div>
      <div className="flex items-center gap-4 text-sm text-white/70">
        <span className="flex items-center gap-1.5"><Icon name="users" className="w-4 h-4 text-gold" />{tb.seats} {t("seats", "asientos")}</span>
        <span className="flex items-center gap-1.5"><Icon name="check-circle" className="w-4 h-4 text-green-400" />{t("Available", "Disponible")}</span>
      </div>
      {guests > tb.seats && <p className="text-coral text-xs flex items-center gap-2 mt-3"><Icon name="triangle-alert" className="w-3.5 h-3.5 shrink-0" />{t("Your party is larger than this table — we may seat you elsewhere.", "Tu grupo supera esta mesa — podríamos reubicarte.")}</p>}
    </div>
  );
}

/* ---------- success + loyalty account prompt ---------- */
function SuccessScreen({ r, onReset }) {
  const t = useT(); const { lang } = useLang();
  const [acc, setAcc] = useState({ marketing: true, done: false });
  const createAccount = () => {
    window.PPDB.customers.add({ fullName: r.fullName, phone: r.phone, email: r.email, marketingConsent: acc.marketing, firstReservation: r.code });
    setAcc((a) => ({ ...a, done: true }));
    window.toast(t("Account created — welcome to the club!", "Cuenta creada — ¡bienvenido al club!"));
  };
  const rows = [[t("Name", "Nombre"), r.fullName], [t("Date", "Fecha"), r.date], [t("Time", "Hora"), r.time], [t("Guests", "Personas"), r.guests], [t("Experience", "Experiencia"), r.experienceType], [t("Table", "Mesa"), r.tableId || t("Host assigns", "El host asigna")]];
  return (
    <div className="min-h-screen flex items-center justify-center px-6 pt-28 pb-24">
      <div className="max-w-lg w-full text-center fade-view">
        <div className="w-20 h-20 rounded-full mx-auto mb-7 flex items-center justify-center bg-coral/15 border border-coral"><Icon name="check" className="w-9 h-9 text-coral" /></div>
        <div className="label text-gold mb-3">{t("Reservation Requested", "Reserva Solicitada")} · {r.code}</div>
        <h2 className="text-4xl md:text-5xl font-black uppercase mb-6">{t("You're on the list", "Estás en la lista")}</h2>
        <div className="rounded-2xl border border-white/12 bg-card p-6 text-left space-y-3 mb-6">
          {rows.map(([k, v], i) => (
            <div key={i} className="flex justify-between gap-4 text-sm border-b border-white/6 pb-2.5 last:border-0"><span className="text-white/45 uppercase tracking-wider text-[11px]">{k}</span><span className="text-white font-semibold text-right">{v}</span></div>
          ))}
        </div>
        <p className="text-white/50 text-sm mb-6">{t("A VIP host will contact you shortly to confirm your table and any minimum spend.", "Un host VIP te contactará pronto para confirmar tu mesa y consumo mínimo.")}</p>
        {!acc.done ? (
          <div className="rounded-2xl border border-gold/30 bg-gold/5 p-5 mb-6 text-left">
            <div className="flex items-center gap-2.5 mb-1.5"><Icon name="star" className="w-5 h-5 text-gold-soft" /><span className="font-black uppercase text-sm">{t("Earn points on this visit", "Gana puntos en esta visita")}</span></div>
            <p className="text-white/60 text-[13px] leading-relaxed mb-3">{t("Create your Pink Pony account to track reservations, earn points and unlock perks.", "Crea tu cuenta Pink Pony para seguir tus reservas, ganar puntos y desbloquear beneficios.")}</p>
            <label className="flex items-start gap-2.5 mb-3 cursor-pointer"><input type="checkbox" checked={acc.marketing} onChange={(e) => setAcc((a) => ({ ...a, marketing: e.target.checked }))} className="mt-0.5 accent-coral" /><span className="text-white/55 text-[12px]">{t("Send me offers and event invites.", "Envíame ofertas e invitaciones a eventos.")}</span></label>
            <button onClick={createAccount} className="gbtn w-full py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em]">{t("Create my account", "Crear mi cuenta")}</button>
          </div>
        ) : (
          <div className="rounded-2xl border border-green-500/40 bg-green-500/8 p-4 mb-6 text-green-300 text-sm flex items-center justify-center gap-2"><Icon name="check-circle" className="w-4 h-4" />{t("Account created — welcome to the club.", "Cuenta creada — bienvenido al club.")}</div>
        )}
        <PrimaryBtn onClick={onReset} icon="rotate-ccw">{t("New reservation", "Nueva reserva")}</PrimaryBtn>
      </div>
    </div>
  );
}

/* ---------- the wizard ---------- */
function ReservePage({ variant = "guided", account }) {
  const t = useT(); const { lang } = useLang();
  const { ZONES, TABLES, NIGHTS } = window.PP;
  const tables = TABLES;
  const [step, setStep] = useState(0);
  const [floor, setFloor] = useState("main");
  const [f, setF] = useState({
    date: "", guests: 4, tableId: null, time: "10:00 PM",
    name: account ? account.name : "", phone: "", email: "", experience: (typeof window !== "undefined" && window.__resvExp) || "vip", requests: "", contactPref: "whatsapp",
  });
  const [done, setDone] = useState(null);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  // the night/program is derived automatically from the chosen calendar date
  const night = f.date ? (new Date(f.date + "T12:00:00").getDay() + 6) % 7 : 5;
  const nightObj = NIGHTS[night];
  const phoneDigits = f.phone.replace(/\D/g, "");
  const selTable = tables.find((x) => x.id === f.tableId);
  const price = selTable ? PRICE(selTable.zone, night) : 0;
  const pick = (tb) => { set("tableId", tb.id); };
  useEffect(() => { try { if (window.__resvExp) delete window.__resvExp; } catch (e) {} }, []);

  useReveal(step + variant);

  if (done) return <SuccessScreen r={done} onReset={() => { setDone(null); setStep(0); set("tableId", null); }} />;

  const STEPS = [
    { key: "date", label: t("Date", "Fecha"), icon: "calendar" },
    { key: "time", label: t("Time", "Hora"), icon: "clock" },
    { key: "experience", label: t("Experience", "Experiencia"), icon: "sparkles" },
    { key: "guests", label: t("Guests", "Personas"), icon: "users" },
    { key: "table", label: t("Table", "Mesa"), icon: "map-pin" },
    { key: "info", label: t("Details", "Datos"), icon: "user" },
    { key: "review", label: t("Review", "Revisar"), icon: "check" },
  ];
  const canNext = () => {
    if (step === 0) return !!f.date;
    if (step === 5) return f.name && phoneDigits.length >= 10 && /.+@.+\..+/.test(f.email);
    return true;
  };

  const TIMES = ["12:00 PM", "3:00 PM", "6:00 PM", "8:00 PM", "10:00 PM", "11:00 PM", "12:00 AM", "1:00 AM"];
  const RES_EXPERIENCES = [
    ["vip", t("VIP Table Experience", "Experiencia Mesa VIP")],
    ["night", t("Night Out", "Salida de Noche")],
    ["birthday", t("Birthday Celebration", "Cumpleaños")],
    ["bachelor", t("Bachelor Party", "Despedida de Soltero")],
    ["game", t("Game Day / Soccer", "Día de Partido / Soccer")],
    ["lunch", t("Free Lunch Dayshift", "Free Lunch Dayshift")],
    ["group", t("Private / Group Event", "Evento Privado / Grupo")],
    ["corporate", t("Corporate Event", "Evento Corporativo")],
  ];
  const expLabel = (id) => { const e = RES_EXPERIENCES.find((x) => x[0] === id); return e ? e[1] : id; };

  const submit = () => {
    // 1) save the reservation to Admin (PPDB.reservations) as PENDING
    const r = window.PPDB.reservations.add({
      fullName: f.name.trim(), phone: "+1" + phoneDigits.slice(-10), email: f.email.trim(),
      date: f.date, time: f.time, guests: f.guests,
      experienceId: f.experience, experienceType: expLabel(f.experience),
      night: night, nightName: nightObj.name, tableId: f.tableId || "",
      price: price, notes: f.requests.trim(), contactPref: f.contactPref,
    });
    // 2) send the summary straight to the club WhatsApp (also captured as a lead)
    window.PP.waOpen(
      t("New reservation request — Pink Pony Club", "Nueva solicitud de reserva — Pink Pony Club"),
      [
        [t("Ref", "Ref"), r.code],
        [t("Name", "Nombre"), f.name], [t("Phone", "Teléfono"), "+1" + phoneDigits.slice(-10)], [t("Email", "Correo"), f.email],
        [t("Date", "Fecha"), f.date + " (" + L(nightObj.day, lang) + ")"], [t("Time", "Hora"), f.time], [t("Guests", "Personas"), f.guests],
        [t("Experience", "Experiencia"), expLabel(f.experience)],
        [t("Table", "Mesa"), f.tableId || ""], [t("Minimum spend", "Consumo mínimo"), price ? "$" + price + "++" : ""],
        [t("Requests", "Peticiones"), f.requests],
      ],
      t("Status: PENDING · saved to Admin · clubpinkpony.com", "Estado: PENDIENTE · guardada en Admin · clubpinkpony.com"),
    );
    setDone(r);
  };

  /* ----- step bodies ----- */
  const localToday = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 10);
  // quick-pick chips for the next 14 days
  const dateChips = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(); d.setDate(d.getDate() + i);
    const iso = new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10);
    const nIdx = (d.getDay() + 6) % 7;
    return { iso, dow: d.toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "short" }), dom: d.getDate(), nIdx, label: i === 0 ? t("Today", "Hoy") : i === 1 ? t("Tomorrow", "Mañana") : null };
  });
  const stepDate = (
    <div>
      <h3 className="text-2xl font-black uppercase mb-1">{t("Pick your date", "Elige tu fecha")}</h3>
      <p className="text-white/50 text-sm mb-6">{t("Choose the day you'd like to come — we'll match the night's program automatically.", "Elige el día que quieres venir — ajustamos el programa de la noche automáticamente.")}</p>
      <div className="flex gap-2.5 overflow-x-auto pb-3 mb-5 -mx-1 px-1 snap-x">
        {dateChips.map((d) => {
          const sel = f.date === d.iso;
          return (
            <button key={d.iso} onClick={() => set("date", d.iso)} className={"snap-start shrink-0 w-[68px] rounded-2xl border p-2.5 text-center transition-all active:scale-95 " + (sel ? "border-coral bg-coral/12" : "border-white/12 hover:border-white/30")}>
              <div className="label text-[9px]" style={{ color: sel ? "var(--c-coral)" : "rgba(255,255,255,.45)" }}>{d.label || d.dow}</div>
              <div className="serif text-2xl leading-none mt-1" style={{ color: sel ? "#fff" : "rgba(255,255,255,.85)" }}>{d.dom}</div>
              <div className="text-[8px] mt-1 text-gold-soft truncate">{NIGHTS[d.nIdx].name}</div>
            </button>
          );
        })}
      </div>
      <label className="block max-w-xs mb-6">
        <span className="label text-white/45 text-[10px] block mb-2">{t("Or pick any date", "O elige cualquier fecha")}</span>
        <input type="date" min={localToday} value={f.date} onChange={(e) => set("date", e.target.value)} className="w-full bg-card border border-white/12 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-coral" style={{ colorScheme: "dark" }} />
      </label>
      {f.date && (
        <div className="rounded-2xl border border-coral/30 bg-coral/5 p-4 flex items-center gap-3 max-w-md fade-view">
          <div className="w-11 h-11 rounded-xl bg-coral/15 border border-coral/40 flex items-center justify-center shrink-0"><Icon name="calendar-check" className="w-5 h-5 text-coral" /></div>
          <div className="min-w-0">
            <div className="font-bold text-sm">{new Date(f.date + "T12:00:00").toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "long", month: "long", day: "numeric" })}</div>
            <div className="text-white/55 text-[12px] truncate">{L(nightObj.day, lang)} · {nightObj.name} · {t("from", "desde")} ${PRICE("regular", night)}++</div>
          </div>
        </div>
      )}
    </div>
  );

  const EXP_ICON = { vip: "gem", night: "moon", birthday: "cake", bachelor: "party-popper", game: "trophy", lunch: "utensils", group: "users", corporate: "briefcase" };
  const stepExperience = (
    <div>
      <h3 className="text-2xl font-black uppercase mb-1">{t("Pick your experience", "Elige tu experiencia")}</h3>
      <p className="text-white/50 text-sm mb-7">{t("Tell us what you're celebrating so we set the right vibe.", "Cuéntanos qué celebras para preparar el ambiente.")}</p>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {RES_EXPERIENCES.map(([id, lbl]) => {
          const sel = f.experience === id;
          return (
            <button key={id} onClick={() => set("experience", id)} className={"flex items-center gap-3.5 rounded-2xl border p-4 text-left transition-all active:scale-[0.98] " + (sel ? "border-coral bg-coral/10" : "border-white/12 hover:border-white/30")}>
              <div className={"w-11 h-11 rounded-xl flex items-center justify-center shrink-0 " + (sel ? "bg-coral text-white" : "bg-white/5 text-coral")}><Icon name={EXP_ICON[id] || "sparkles"} className="w-5 h-5" /></div>
              <div className="min-w-0"><div className="font-bold text-[14px] leading-tight">{lbl}</div></div>
              {sel && <Icon name="check-circle" className="w-5 h-5 text-coral ml-auto shrink-0" />}
            </button>
          );
        })}
      </div>
    </div>
  );

  const stepGuests = (
    <div>
      <h3 className="text-2xl font-black uppercase mb-1">{t("How many guests?", "¿Cuántas personas?")}</h3>
      <p className="text-white/50 text-sm mb-7">{t("We'll match you to the right table.", "Te ubicamos en la mesa adecuada.")}</p>
      <div className="flex items-center gap-5 mb-7">
        <button onClick={() => set("guests", Math.max(1, f.guests - 1))} className="w-14 h-14 rounded-2xl bg-card border border-white/15 hover:border-white/35 active:scale-90 transition-transform flex items-center justify-center"><Icon name="minus" className="w-6 h-6" /></button>
        <div className="text-center w-24"><div className="serif text-6xl text-white leading-none">{f.guests}</div><div className="label text-white/45 text-[10px] mt-1">{t("guests", "personas")}</div></div>
        <button onClick={() => set("guests", Math.min(30, f.guests + 1))} className="w-14 h-14 rounded-2xl bg-card border border-white/15 hover:border-white/35 active:scale-90 transition-transform flex items-center justify-center"><Icon name="plus" className="w-6 h-6" /></button>
      </div>
      <div className="flex flex-wrap gap-2">
        {[2, 4, 6, 8, 10, 12].map((n) => <button key={n} onClick={() => set("guests", n)} className={"px-5 py-2.5 rounded-full text-sm font-bold transition-all active:scale-95 " + (f.guests === n ? "bg-coral text-white" : "bg-white/5 border border-white/12 text-white/70 hover:text-white")}>{n}</button>)}
        <button onClick={() => set("guests", 15)} className={"px-5 py-2.5 rounded-full text-sm font-bold transition-all active:scale-95 " + (f.guests >= 13 ? "bg-coral text-white" : "bg-white/5 border border-white/12 text-white/70 hover:text-white")}>12+</button>
      </div>
    </div>
  );

  const stepTable = (
    <div>
      <h3 className="text-2xl font-black uppercase mb-1">{t("Choose your table", "Elige tu mesa")}</h3>
      <p className="text-white/50 text-sm mb-5">{t("Optional — pick a spot or let our host assign the best table for your party. VIP/Stage $500++ · Skybox $600++ · Mezzanine $250++.", "Opcional — elige un lugar o deja que el host asigne la mejor mesa para tu grupo. VIP/Tarima $500++ · Skybox $600++ · Mezzanine $250++.")}</p>
      <div className="grid lg:grid-cols-12 gap-6 items-start">
        <div className="lg:col-span-8">
          <FloorPlan tables={tables} selected={f.tableId} onPick={pick} night={night} floor={floor} setFloor={setFloor} />
        </div>
        {/* desktop side card */}
        <div className="hidden lg:block lg:col-span-4 lg:sticky lg:top-28">
          {selTable ? (
            <div className="fade-view rounded-2xl border p-6" style={{ borderColor: ZACCENT[selTable.zone] + "66", background: ZACCENT[selTable.zone] + "0d" }}>
              <SelectionDetail tb={selTable} price={price} guests={f.guests} lang={lang} />
            </div>
          ) : (
            <div className="rounded-2xl border border-dashed border-white/15 p-7 text-center"><Icon name="mouse-pointer-click" className="w-7 h-7 text-white/30 mx-auto mb-3" /><p className="text-white/50 text-sm">{t("Tap a table to select it.", "Toca una mesa para seleccionarla.")}</p></div>
          )}
        </div>
      </div>
      {/* mobile selection sheet */}
      {selTable && (
        <div className="lg:hidden sheet-up fixed bottom-0 inset-x-0 z-30 px-3 pb-3" style={{ paddingBottom: "calc(env(safe-area-inset-bottom) + 12px)" }}>
          <div className="rounded-2xl border bg-ink/95 backdrop-blur-xl p-4 shadow-[0_-12px_40px_rgba(0,0,0,.6)]" style={{ borderColor: ZACCENT[selTable.zone] + "66" }}>
            <SelectionDetail tb={selTable} price={price} guests={f.guests} lang={lang} />
            <button onClick={() => setStep(5)} className="gbtn w-full mt-3 py-3.5 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] flex items-center justify-center gap-2">{t("Continue", "Continuar")} · {t("Table", "Mesa")} {selTable.id}<Icon name="arrow-right" className="w-4 h-4" /></button>
          </div>
        </div>
      )}
    </div>
  );

  const stepTime = (
    <div>
      <h3 className="text-2xl font-black uppercase mb-1">{t("What time?", "¿A qué hora?")}</h3>
      <p className="text-white/50 text-sm mb-7">{t("Arrival time — doors open 12PM, close 5AM.", "Hora de llegada — abrimos 12PM, cerramos 5AM.")}</p>
      <div className="grid grid-cols-2 sm:flex sm:flex-wrap gap-3">
        {TIMES.map((tm) => <button key={tm} onClick={() => set("time", tm)} className={"px-6 py-4 rounded-2xl text-base font-bold transition-all active:scale-95 " + (f.time === tm ? "bg-coral text-white" : "bg-card border border-white/12 text-white/70 hover:border-white/30")}>{tm}</button>)}
      </div>
    </div>
  );

  const field = (k, icon, ph, type = "text") => (
    <div className="relative">
      <Icon name={icon} className="w-4 h-4 text-white/35 absolute left-4 top-1/2 -translate-y-1/2" />
      <input type={type} value={f[k]} onChange={(e) => set(k, e.target.value)} placeholder={ph} className="w-full bg-card border border-white/12 rounded-xl pl-11 pr-4 py-3.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35" />
    </div>
  );
  const stepInfo = (
    <div className="max-w-lg">
      <h3 className="text-2xl font-black uppercase mb-1">{t("Your details", "Tus datos")}</h3>
      <p className="text-white/50 text-sm mb-7">{t("So our host can confirm and greet you by name.", "Para que nuestro host confirme y te reciba por tu nombre.")}</p>
      <div className="space-y-4">
        {field("name", "user", t("Full name", "Nombre completo"))}
        {field("phone", "phone", t("Mobile number", "Número de móvil"), "tel")}
        {field("email", "mail", t("Email", "Correo"), "email")}
        <div>
          <span className="label text-white/45 text-[10px] block mb-2">{t("How should we confirm?", "¿Cómo te confirmamos?")}</span>
          <div className="flex flex-wrap gap-2">
            {[["whatsapp", "WhatsApp", "message-circle"], ["call", t("Call", "Llamada"), "phone"], ["email", "Email", "mail"]].map(([id, lbl, ic]) => (
              <button key={id} onClick={() => set("contactPref", id)} className={"inline-flex items-center gap-2 px-4 py-2 rounded-full text-[12px] font-bold transition-all active:scale-95 " + (f.contactPref === id ? "bg-coral text-white" : "bg-card border border-white/12 text-white/65 hover:text-white")}><Icon name={ic} className="w-3.5 h-3.5" />{lbl}</button>
            ))}
          </div>
        </div>
        <textarea value={f.requests} onChange={(e) => set("requests", e.target.value)} rows={3} placeholder={t("Special requests (bottles, cake, decorations, seating)…", "Peticiones especiales (botellas, pastel, decoración, ubicación)…")} className="w-full bg-card border border-white/12 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-coral placeholder:text-white/35 resize-none"></textarea>
      </div>
    </div>
  );

  const row = (k, v) => <div className="flex justify-between gap-4 py-2.5 border-b border-white/6 last:border-0"><span className="text-white/45 uppercase tracking-wider text-[11px]">{k}</span><span className="text-white font-semibold text-right text-sm">{v || "—"}</span></div>;
  const stepReview = (
    <div className="max-w-lg">
      <h3 className="text-2xl font-black uppercase mb-1">{t("Review & confirm", "Revisa y confirma")}</h3>
      <p className="text-white/50 text-sm mb-6">{t("No charge today — minimum spend applies on arrival.", "Sin cargo hoy — el mínimo aplica al llegar.")}</p>
      <div className="rounded-2xl border border-white/12 bg-card p-6 mb-6">
        {row(t("Name", "Nombre"), f.name)}
        {row(t("Mobile", "Móvil"), f.phone)}
        {row(t("Experience", "Experiencia"), expLabel(f.experience))}
        {row(t("Date", "Fecha"), f.date ? new Date(f.date + "T12:00:00").toLocaleDateString(lang === "es" ? "es" : "en", { weekday: "long", month: "long", day: "numeric" }) : "")}
        {row(t("Night", "Noche"), L(nightObj.day, lang) + " · " + nightObj.name)}
        {row(t("Time", "Hora"), f.time)}
        {row(t("Guests", "Personas"), f.guests)}
        {row(t("Table", "Mesa"), f.tableId || t("Host assigns best table", "El host asigna la mejor mesa"))}
        {row(t("Confirm by", "Confirmar por"), f.contactPref === "whatsapp" ? "WhatsApp" : f.contactPref === "call" ? t("Call", "Llamada") : "Email")}
        {f.tableId && row(t("Minimum spend", "Consumo mínimo"), "$" + price + "++")}
      </div>
      <PrimaryBtn className="w-full" icon="check" onClick={submit}>{t("Confirm reservation", "Confirmar reserva")}</PrimaryBtn>
    </div>
  );

  const bodies = [stepDate, stepTime, stepExperience, stepGuests, stepTable, stepInfo, stepReview];

  /* ----- QUICK single-screen variant ----- */
  if (variant === "quick") {
    const ok = f.date && f.name && f.phone.length >= 7 && /.+@.+\..+/.test(f.email);
    return (
      <div className="pt-28 md:pt-32 pb-24"><div className="container">
        <div className="reveal max-w-2xl mb-8"><Eyebrow num="">{t("Reservations", "Reservas")}</Eyebrow><h1 className="text-5xl md:text-7xl font-black uppercase leading-[0.9] mt-4">{t(<>Reserve a <span className="serif-it font-normal text-coral">table</span></>, <>Reserva una <span className="serif-it font-normal text-coral">mesa</span></>)}</h1></div>
        <div className="grid lg:grid-cols-12 gap-8 items-start">
          <div className="lg:col-span-7 reveal"><FloorPlan tables={tables} selected={f.tableId} onPick={pick} night={night} floor={floor} setFloor={setFloor} /></div>
          <div className="lg:col-span-5 reveal space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <label><span className="label text-white/45 text-[10px] block mb-1.5">{t("Date", "Fecha")}</span><input type="date" min={new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 10)} value={f.date} onChange={(e) => set("date", e.target.value)} className="w-full bg-card border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral" style={{ colorScheme: "dark" }} /></label>
              <label><span className="label text-white/45 text-[10px] block mb-1.5">{t("Experience", "Experiencia")}</span><select value={f.experience} onChange={(e) => set("experience", e.target.value)} className="w-full bg-card border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral">{RES_EXPERIENCES.map(([id, lbl]) => <option key={id} value={id} className="bg-card">{lbl}</option>)}</select></label>
              <label><span className="label text-white/45 text-[10px] block mb-1.5">{t("Guests", "Personas")}</span><input type="number" min="1" value={f.guests} onChange={(e) => set("guests", +e.target.value)} className="w-full bg-card border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral" /></label>
              <label><span className="label text-white/45 text-[10px] block mb-1.5">{t("Time", "Hora")}</span><select value={f.time} onChange={(e) => set("time", e.target.value)} className="w-full bg-card border border-white/12 rounded-xl px-3 py-3 text-sm text-white focus:outline-none focus:border-coral">{TIMES.map((tm) => <option key={tm} className="bg-card">{tm}</option>)}</select></label>
            </div>
            {field("name", "user", t("Full name", "Nombre completo"))}
            {field("phone", "phone", t("Mobile", "Móvil"), "tel")}
            {field("email", "mail", t("Email", "Correo"), "email")}
            <div className="rounded-xl border border-white/12 bg-card p-4 flex items-center justify-between">
              <span className="text-sm text-white/60">{f.tableId ? <>{t("Table", "Mesa")} <b className="text-white">{f.tableId}</b> · ${price}++</> : t("No table selected", "Sin mesa seleccionada")}</span>
            </div>
            <button disabled={!ok} onClick={submit} className={"gbtn w-full py-4 rounded-full text-[12px] font-bold uppercase tracking-[0.16em] transition-all " + (ok ? "bg-coral hover:bg-coral-deep text-white" : "bg-white/8 text-white/40 cursor-not-allowed")}>{t("Confirm reservation", "Confirmar reserva")}</button>
          </div>
        </div>
      </div></div>
    );
  }

  /* ----- GUIDED wizard (mobile-first) ----- */
  // on the table step the mobile sheet drives "continue" — but only once a
  // table is picked; with none selected the user can skip (host assigns).
  const onTableStep = step === 4 && !!f.tableId;
  return (
    <div className="pt-28 md:pt-32 pb-24"><div className="container max-w-4xl">
      <div className="reveal mb-7"><Eyebrow num="">{t("Reservations", "Reservas")}</Eyebrow><h1 className="text-4xl md:text-6xl font-black uppercase leading-[0.9] mt-3">{t(<>Reserve a <span className="serif-it font-normal text-coral">table</span></>, <>Reserva una <span className="serif-it font-normal text-coral">mesa</span></>)}</h1></div>

      {/* mobile progress bar */}
      <div className="sm:hidden mb-6">
        <div className="flex items-center justify-between mb-2"><span className="label text-coral text-[10px]">{STEPS[step].label}</span><span className="text-white/40 text-[11px]">{step + 1}/{STEPS.length}</span></div>
        <div className="h-1.5 rounded-full bg-white/10 overflow-hidden"><div className="h-full rounded-full bg-gradient-to-r from-coral to-coral-deep transition-all duration-500" style={{ width: ((step + 1) / STEPS.length) * 100 + "%" }}></div></div>
      </div>

      {/* desktop stepper */}
      <div className="hidden sm:flex items-center mb-10 overflow-x-auto pb-2">
        {STEPS.map((s, i) => (
          <React.Fragment key={s.key}>
            <button onClick={() => i < step && setStep(i)} className="flex items-center gap-2.5 shrink-0" style={{ cursor: i < step ? "pointer" : "default" }}>
              <span className="w-9 h-9 rounded-full flex items-center justify-center border transition-all" style={{ background: i < step ? "var(--c-coral)" : "transparent", borderColor: i <= step ? "var(--c-coral)" : "rgba(255,255,255,.18)", color: i < step ? "#fff" : i === step ? "var(--c-coral)" : "rgba(255,255,255,.4)" }}>
                {i < step ? <Icon name="check" className="w-4 h-4" /> : <Icon name={s.icon} className="w-4 h-4" />}
              </span>
              <span className={"text-[11px] font-bold uppercase tracking-[0.12em] " + (i === step ? "text-white" : "text-white/40")}>{s.label}</span>
            </button>
            {i < STEPS.length - 1 && <span className="flex-1 min-w-[14px] h-px mx-2" style={{ background: i < step ? "var(--c-coral)" : "rgba(255,255,255,.14)" }}></span>}
          </React.Fragment>
        ))}
      </div>

      {/* body */}
      <div key={step} className="fade-view min-h-[280px]">{bodies[step]}</div>

      {/* nav (sticky on mobile, hidden on the table step where the sheet drives it) */}
      <div className={"flex items-center justify-between mt-10 pt-6 border-t border-white/10 " + (onTableStep ? "max-lg:hidden" : "")}>
        <button onClick={() => setStep((s) => Math.max(0, s - 1))} disabled={step === 0} className={"inline-flex items-center gap-2 px-5 py-3 rounded-full text-[12px] font-bold uppercase tracking-[0.14em] transition-all " + (step === 0 ? "text-white/25 cursor-not-allowed" : "text-white/70 hover:text-white")}><Icon name="arrow-left" className="w-4 h-4" />{t("Back", "Atrás")}</button>
        <div className="text-white/40 text-xs hidden sm:block">{step + 1} / {STEPS.length}</div>
        {step < STEPS.length - 1 ? (
          <button onClick={() => canNext() && setStep((s) => s + 1)} disabled={!canNext()} className={"gbtn inline-flex items-center gap-2 px-7 py-3.5 rounded-full text-[12px] font-bold uppercase tracking-[0.16em] transition-all " + (canNext() ? "bg-coral hover:bg-coral-deep text-white" : "bg-white/8 text-white/40 cursor-not-allowed")}>{t("Continue", "Continuar")}<Icon name="arrow-right" className="w-4 h-4" /></button>
        ) : <div className="w-24"></div>}
      </div>
    </div></div>
  );
}

Object.assign(window, { ReservePage });
