// ---- BRAISE — Booking flow --------------------------------------------

const STEPS = [
  { id: "search", label: "Date & couverts", icon: "calendar" },
  { id: "slots", label: "Créneau", icon: "clock" },
  { id: "details", label: "Coordonnées", icon: "users" },
  { id: "payment", label: "Acompte", icon: "lock" },
];

// ---- Progress stepper -------------------------------------------------
function Stepper({ current }) {
  const idx = STEPS.findIndex((s) => s.id === current);
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 0, marginBottom: 46, flexWrap: "wrap" }}>
      {STEPS.map((s, i) => {
        const done = i < idx, active = i === idx;
        return (
          <React.Fragment key={s.id}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <span style={{
                width: 34, height: 34, borderRadius: "50%", display: "grid", placeItems: "center", flexShrink: 0,
                border: `1px solid ${active || done ? "var(--ember)" : "var(--line)"}`,
                background: done ? "var(--ember)" : (active ? "var(--ember-soft)" : "var(--paper)"),
                color: done ? "var(--paper)" : (active ? "var(--ember-deep)" : "var(--ink-faint)"),
                transition: "all 0.3s var(--ease)",
              }}>
                {done ? <Icon name="check" size={16} /> : <Icon name={s.icon} size={15} />}
              </span>
              <span className="step-labels" style={{
                fontSize: 13, fontWeight: active ? 600 : 500,
                color: active ? "var(--ink)" : (done ? "var(--ink-soft)" : "var(--ink-faint)"),
              }}>{s.label}</span>
            </div>
            {i < STEPS.length - 1 && (
              <div style={{ width: 38, height: 1, margin: "0 14px", background: i < idx ? "var(--ember)" : "var(--line)", transition: "background 0.3s var(--ease)" }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ---- Aside summary ----------------------------------------------------
function AsideRow({ icon, label, value, onEdit }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 13, padding: "15px 0", borderBottom: "1px solid var(--line-soft)" }}>
      <span style={{ color: "var(--ember)", marginTop: 2 }}><Icon name={icon} size={17} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)" }}>{label}</div>
        <div style={{ fontSize: 15, fontWeight: 500, marginTop: 2, textTransform: label === "Date" ? "capitalize" : "none" }}>{value || "—"}</div>
      </div>
      {onEdit && value && <button onClick={onEdit} className="link-underline" style={{ fontSize: 12 }}>Modifier</button>}
    </div>
  );
}

function AsideSummary({ b, goStep }) {
  const svc = SERVICES.find((s) => s.id === b.service);
  const zone = ZONES.find((z) => z.id === b.zone);
  const total = b.party * DEPOSIT_PER_SEAT;
  return (
    <aside className="resa-aside" style={{ position: "sticky", top: 96 }}>
      <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)", padding: 26, overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
          <Ph tone="ember" style={{ width: 52, height: 52, borderRadius: 12, flexShrink: 0 }} />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 20, letterSpacing: "0.08em" }}>BRAISE</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>{RESTO.baseline}</div>
          </div>
        </div>
        <div style={{ marginTop: 8 }}>
          <AsideRow icon="calendar" label="Date" value={formatLong(b.date)} onEdit={() => goStep("search")} />
          <AsideRow icon={svc ? svc.icon : "sun"} label="Service" value={svc ? svc.name : ""} onEdit={() => goStep("search")} />
          <AsideRow icon="users" label="Couverts" value={partyLabel(b.party)} onEdit={() => goStep("search")} />
          <AsideRow icon="clock" label="Créneau" value={b.slot} onEdit={b.slot ? () => goStep("slots") : null} />
          {zone && <AsideRow icon="flame" label="Ambiance" value={zone.name} onEdit={() => goStep("search")} />}
        </div>
        <div style={{ marginTop: 18, padding: "16px 18px", background: "var(--bone-deep)", borderRadius: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10 }}>
            <span style={{ fontSize: 14, fontWeight: 500 }}>Acompte</span>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 22, whiteSpace: "nowrap" }}>{fmtEur(total)}</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-faint)", marginTop: 8, lineHeight: 1.5 }}>
            {fmtEur(DEPOSIT_PER_SEAT)} par couvert × {b.party}. Déduit de l'addition, remboursable jusqu'à 24 h avant.
          </div>
        </div>
      </div>
    </aside>
  );
}

// ---- Step 1 : search --------------------------------------------------
function StepSearch({ b, setB, next }) {
  return (
    <div className="page-fade">
      <SectionHead title="Quand venez-vous&nbsp;?" sub="Choisissez une date, le service et le nombre de couverts." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 0.9fr", gap: 40, marginTop: 36, alignItems: "start" }} className="home-split">
        <div>
          <label className="field-label">Date</label>
          <Calendar value={b.date} onChange={(d) => setB({ ...b, date: d, slot: "" })} />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 30 }}>
          <div>
            <label className="field-label">Service</label>
            <div style={{ display: "flex", gap: 10 }}>
              {SERVICES.map((s) => (
                <button key={s.id} onClick={() => setB({ ...b, service: s.id, slot: "" })} style={{
                  flex: 1, padding: "18px 12px", borderRadius: "var(--field-radius)", textAlign: "left",
                  border: `1px solid ${b.service === s.id ? "var(--ember)" : "var(--field-border)"}`,
                  background: b.service === s.id ? "var(--ember-soft)" : "var(--field-bg)",
                  transition: "all 0.2s var(--ease)",
                }}>
                  <Icon name={s.icon} size={20} style={{ color: b.service === s.id ? "var(--ember-deep)" : "var(--ink-soft)" }} />
                  <div style={{ fontWeight: 600, fontSize: 15.5, marginTop: 8, color: b.service === s.id ? "var(--ember-deep)" : "var(--ink)" }}>{s.name}</div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-faint)" }}>{s.note}</div>
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="field-label">Couverts</label>
            <div style={{ background: "var(--paper)", border: "1px solid var(--field-border)", borderRadius: "var(--field-radius)", padding: "18px 22px", display: "flex", justifyContent: "center" }}>
              <PartyStepper value={b.party} onChange={(v) => setB({ ...b, party: v, slot: "" })} />
            </div>
            {b.party >= 8 && (
              <p style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 12, display: "flex", gap: 8, alignItems: "flex-start" }}>
                <Icon name="spark" size={15} style={{ color: "var(--ember)", marginTop: 2, flexShrink: 0 }} />
                Pour les grandes tablées, le salon privé est idéal — vous pourrez le sélectionner à l'étape suivante.
              </p>
            )}
          </div>
          <div>
            <label className="field-label">Ambiance souhaitée</label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {ZONES.map((z) => (
                <button key={z.id} onClick={() => setB({ ...b, zone: z.id })} style={{
                  textAlign: "left", padding: "13px 15px", borderRadius: "var(--field-radius)",
                  border: `1px solid ${b.zone === z.id ? "var(--ember)" : "var(--field-border)"}`,
                  background: b.zone === z.id ? "var(--ember-soft)" : "var(--field-bg)",
                  transition: "all 0.2s var(--ease)",
                }}>
                  <div style={{ fontWeight: 600, fontSize: 14.5, color: b.zone === z.id ? "var(--ember-deep)" : "var(--ink)" }}>{z.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-faint)", lineHeight: 1.4, marginTop: 2 }}>{z.blurb}</div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 38, display: "flex", justifyContent: "flex-end" }}>
        <button className="btn btn--ember" disabled={!b.date} onClick={next}>
          Voir les créneaux <Icon name="arrow-right" size={16} />
        </button>
      </div>
    </div>
  );
}

// ---- Step 2 : slots ---------------------------------------------------
function StepSlots({ b, setB, next, back }) {
  const slots = slotsFor(b.date, b.service, b.party);
  const available = slots.filter((s) => !s.full);
  return (
    <div className="page-fade">
      <SectionHead title="Choisissez votre heure"
        sub={`${formatLong(b.date)} · ${SERVICES.find((s) => s.id === b.service).name} · ${partyLabel(b.party)}`} />
      {available.length === 0 ? (
        <div style={{ marginTop: 36, textAlign: "center", padding: "60px 20px", background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)" }}>
          <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--bone-deep)", display: "grid", placeItems: "center", margin: "0 auto 18px", color: "var(--ink-faint)" }}><Icon name="calendar" size={24} /></div>
          <h3 style={{ fontSize: 24 }}>Complet pour ce service</h3>
          <p style={{ color: "var(--ink-soft)", maxWidth: 360, margin: "12px auto 24px" }}>Essayez un autre jour ou l'autre service — il reste souvent des tables.</p>
          <button className="btn btn--ghost" onClick={back}><Icon name="arrow-left" size={16} /> Changer la date</button>
        </div>
      ) : (
        <>
          <div style={{ marginTop: 14, marginBottom: 24, display: "flex", gap: 18, fontSize: 12.5, color: "var(--ink-faint)", flexWrap: "wrap" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: "var(--paper)", border: "1px solid var(--line)" }} />Disponible</span>
            <span style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: "var(--gold-soft)", border: "1px solid var(--gold)" }} />Dernières places</span>
            <span style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: "var(--bone-deep)" }} />Complet</span>
          </div>
          <div className="slots-grid" style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 10 }}>
            {slots.map((s) => {
              const selected = b.slot === s.label;
              return (
                <button key={s.label} disabled={s.full} onClick={() => setB({ ...b, slot: s.label })} style={{
                  padding: "16px 6px", borderRadius: 12, fontSize: 15.5, fontWeight: 500, position: "relative",
                  border: `1px solid ${selected ? "var(--ember)" : (s.full ? "transparent" : (s.tight ? "var(--gold)" : "var(--line)"))}`,
                  background: selected ? "var(--ember)" : (s.full ? "var(--bone-deep)" : (s.tight ? "var(--gold-soft)" : "var(--paper)")),
                  color: selected ? "var(--paper)" : (s.full ? "var(--ink-faint)" : "var(--ink)"),
                  cursor: s.full ? "not-allowed" : "pointer", opacity: s.full ? 0.55 : 1,
                  textDecoration: s.full ? "line-through" : "none", transition: "all 0.18s var(--ease)",
                }}>{s.label}</button>
              );
            })}
          </div>
        </>
      )}
      <div style={{ marginTop: 38, display: "flex", justifyContent: "space-between", gap: 12 }}>
        <button className="btn btn--ghost" onClick={back}><Icon name="arrow-left" size={16} /> Retour</button>
        <button className="btn btn--ember" disabled={!b.slot} onClick={next}>Continuer <Icon name="arrow-right" size={16} /></button>
      </div>
    </div>
  );
}

// ---- Step 3 : details -------------------------------------------------
function Field({ label, value, onChange, type = "text", placeholder, error, ...rest }) {
  return (
    <div>
      <label className="field-label">{label}</label>
      <input className="field" type={type} value={value} placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)} style={error ? { borderColor: "var(--ember)" } : null} {...rest} />
      {error && <div style={{ fontSize: 12, color: "var(--ember-deep)", marginTop: 6 }}>{error}</div>}
    </div>
  );
}

function StepDetails({ b, setB, next, back }) {
  const [touched, setTouched] = useState(false);
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b.email);
  const phoneOk = b.phone.replace(/\D/g, "").length >= 9;
  const valid = b.firstName.trim() && b.lastName.trim() && emailOk && phoneOk;
  const submit = () => { setTouched(true); if (valid) next(); };
  return (
    <div className="page-fade">
      <SectionHead title="Vos coordonnées" sub="Pour vous envoyer la confirmation et vous joindre en cas de besoin." />
      <div style={{ marginTop: 34, display: "flex", flexDirection: "column", gap: 22, maxWidth: 620 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
          <Field label="Prénom" value={b.firstName} onChange={(v) => setB({ ...b, firstName: v })} placeholder="Camille"
            error={touched && !b.firstName.trim() ? "Champ requis" : ""} />
          <Field label="Nom" value={b.lastName} onChange={(v) => setB({ ...b, lastName: v })} placeholder="Rey"
            error={touched && !b.lastName.trim() ? "Champ requis" : ""} />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="home-split">
          <Field label="E-mail" type="email" value={b.email} onChange={(v) => setB({ ...b, email: v })} placeholder="camille@email.fr"
            error={touched && !emailOk ? "E-mail invalide" : ""} />
          <Field label="Téléphone" type="tel" value={b.phone} onChange={(v) => setB({ ...b, phone: v })} placeholder="06 12 34 56 78"
            error={touched && !phoneOk ? "Numéro invalide" : ""} />
        </div>
        <div>
          <label className="field-label">Occasion (facultatif)</label>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
            {OCCASIONS.map((o) => (
              <button key={o} onClick={() => setB({ ...b, occasion: o })} style={{
                padding: "9px 16px", borderRadius: 999, fontSize: 13.5,
                border: `1px solid ${b.occasion === o ? "var(--ember)" : "var(--line)"}`,
                background: b.occasion === o ? "var(--ember-soft)" : "var(--paper)",
                color: b.occasion === o ? "var(--ember-deep)" : "var(--ink-soft)",
                transition: "all 0.18s var(--ease)",
              }}>{o}</button>
            ))}
          </div>
        </div>
        <div>
          <label className="field-label">Une demande particulière&nbsp;? (facultatif)</label>
          <textarea className="field" value={b.notes} onChange={(e) => setB({ ...b, notes: e.target.value })}
            placeholder="Allergies, poussette, fauteuil, table près du feu…" />
        </div>
      </div>
      <div style={{ marginTop: 36, display: "flex", justifyContent: "space-between", gap: 12 }}>
        <button className="btn btn--ghost" onClick={back}><Icon name="arrow-left" size={16} /> Retour</button>
        <button className="btn btn--ember" onClick={submit} disabled={touched && !valid}>Vers l'acompte <Icon name="arrow-right" size={16} /></button>
      </div>
    </div>
  );
}

// ---- Step 4 : payment -------------------------------------------------
function StepPayment({ b, setB, confirm, back }) {
  const [card, setCard] = useState({ num: "", exp: "", cvc: "", name: "" });
  const [touched, setTouched] = useState(false);
  const [loading, setLoading] = useState(false);
  const total = b.party * DEPOSIT_PER_SEAT;

  const fmtNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const fmtExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length > 2 ? d.slice(0, 2) + "/" + d.slice(2) : d; };
  const numOk = card.num.replace(/\s/g, "").length === 16;
  const expOk = /^\d{2}\/\d{2}$/.test(card.exp);
  const cvcOk = card.cvc.length >= 3;
  const nameOk = card.name.trim().length > 2;
  const valid = numOk && expOk && cvcOk && nameOk;

  const pay = () => {
    setTouched(true);
    if (!valid) return;
    setLoading(true);
    setTimeout(() => confirm(), 1200);
  };

  return (
    <div className="page-fade">
      <SectionHead title="Confirmez avec un acompte" sub={`Un acompte de ${fmtEur(total)} valide votre table. Il est intégralement déduit de votre addition.`} />
      <div style={{ marginTop: 34, maxWidth: 620 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 20px", background: "var(--ember-soft)", borderRadius: 12, marginBottom: 26 }}>
          <Icon name="lock" size={18} style={{ color: "var(--ember-deep)" }} />
          <span style={{ fontSize: 13.5, color: "var(--ember-deep)", lineHeight: 1.5 }}>Paiement sécurisé. Remboursable jusqu'à 24 h avant le service. <strong>Prototype — aucune carte n'est débitée.</strong></span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <Field label="Numéro de carte" value={card.num} onChange={(v) => setCard({ ...card, num: fmtNum(v) })}
            placeholder="4242 4242 4242 4242" inputMode="numeric"
            error={touched && !numOk ? "16 chiffres attendus" : ""} />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
            <Field label="Expiration" value={card.exp} onChange={(v) => setCard({ ...card, exp: fmtExp(v) })}
              placeholder="MM/AA" inputMode="numeric" error={touched && !expOk ? "MM/AA" : ""} />
            <Field label="Cryptogramme" value={card.cvc} onChange={(v) => setCard({ ...card, cvc: v.replace(/\D/g, "").slice(0, 4) })}
              placeholder="123" inputMode="numeric" error={touched && !cvcOk ? "3 chiffres" : ""} />
          </div>
          <Field label="Titulaire de la carte" value={card.name} onChange={(v) => setCard({ ...card, name: v })}
            placeholder="CAMILLE REY" error={touched && !nameOk ? "Nom requis" : ""} />
        </div>
      </div>
      <div style={{ marginTop: 36, display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <button className="btn btn--ghost" onClick={back} disabled={loading}><Icon name="arrow-left" size={16} /> Retour</button>
        <button className="btn btn--ember" onClick={pay} disabled={loading || (touched && !valid)}>
          {loading ? "Validation…" : <>Payer {fmtEur(total)} & réserver <Icon name="arrow-right" size={16} /></>}
        </button>
      </div>
    </div>
  );
}

// ---- Confirmation -----------------------------------------------------
function Confirmation({ resa, go }) {
  const svc = SERVICES.find((s) => s.id === resa.service);
  const zone = ZONES.find((z) => z.id === resa.zone);
  return (
    <div className="container page-fade" style={{ padding: "70px 32px 90px", maxWidth: 720 }}>
      <div style={{ textAlign: "center" }}>
        <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--ember)", color: "var(--paper)", display: "grid", placeItems: "center", margin: "0 auto 26px", animation: "fadeUp 0.6s var(--ease) both" }}>
          <Icon name="check" size={34} stroke={2} />
        </div>
        <div className="eyebrow" style={{ marginBottom: 14 }}>Réservation confirmée</div>
        <h1 style={{ fontSize: "clamp(32px, 5vw, 52px)" }}>À très bientôt, {resa.firstName}</h1>
        <p style={{ marginTop: 18, fontSize: 16.5, color: "var(--ink-soft)", lineHeight: 1.7, maxWidth: 480, margin: "18px auto 0" }}>
          Un e-mail de confirmation part vers <strong style={{ color: "var(--ink)" }}>{resa.email}</strong>. Votre acompte de {fmtEur(resa.deposit)} a bien été reçu.
        </p>
      </div>

      <div style={{ marginTop: 40, background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 26px", background: "var(--espresso)", color: "var(--bone)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <span style={{ width: 28, height: 28, borderRadius: "50%", display: "grid", placeItems: "center", background: "var(--ember)", color: "var(--paper)" }}><Icon name="flame" size={16} /></span>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 20, letterSpacing: "0.1em" }}>BRAISE</span>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 10.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--gold)" }}>Référence</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 16, letterSpacing: "0.06em" }}>{resa.ref}</div>
          </div>
        </div>
        <div style={{ padding: "8px 26px 22px" }}>
          {[["calendar", "Date", formatLong(resa.dateISO)], [svc ? svc.icon : "moon", "Service & heure", `${svc ? svc.name : ""} · ${resa.slot}`],
            ["users", "Couverts", partyLabel(resa.party)], ["flame", "Ambiance", zone ? zone.name : "—"],
            ...(resa.occasion && resa.occasion !== "Sans occasion" ? [["spark", "Occasion", resa.occasion]] : [])].map(([ic, l, v], i, arr) => (
            <div key={l} style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 0", borderBottom: i < arr.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
              <span style={{ color: "var(--ember)" }}><Icon name={ic} size={18} /></span>
              <span style={{ fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-faint)", width: 130, flexShrink: 0 }}>{l}</span>
              <span style={{ fontSize: 15.5, fontWeight: 500, textTransform: l === "Date" ? "capitalize" : "none" }}>{v}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 22, fontSize: 13.5, color: "var(--ink-soft)", display: "flex", gap: 10, alignItems: "flex-start", lineHeight: 1.6 }}>
        <Icon name="pin" size={16} style={{ color: "var(--ember)", marginTop: 2, flexShrink: 0 }} />
        <span>{RESTO.address}. Merci d'arriver à l'heure — la table est tenue 15 minutes. Pour modifier, retrouvez votre réservation dans votre espace.</span>
      </div>

      <div style={{ marginTop: 32, display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
        <button className="btn btn--ember" onClick={() => go("mes-resas")}>Voir mes réservations <Icon name="arrow-right" size={16} /></button>
        <button className="btn btn--ghost" onClick={() => go("home")}>Retour à l'accueil</button>
      </div>
    </div>
  );
}

// ---- Booking flow orchestrator ----------------------------------------
function BookingFlow({ seed, go, addReservation }) {
  const todayPlus = (() => { const d = new Date(); d.setDate(d.getDate() + 1); if (isClosed(d)) d.setDate(d.getDate() + 1); return toISO(d); })();
  const [b, setB] = useState(() => ({
    date: seed?.date || "", service: seed?.service || "diner", party: seed?.party || 2,
    zone: "salle", slot: "",
    firstName: "", lastName: "", email: "", phone: "", occasion: "Sans occasion", notes: "",
  }));
  const [step, setStep] = useState(seed?.date ? "slots" : "search");
  const [confirmed, setConfirmed] = useState(null);

  useEffect(() => { window.scrollTo({ top: 0, behavior: "smooth" }); }, [step]);

  if (confirmed) return <Confirmation resa={confirmed} go={go} />;

  const goStep = (s) => setStep(s);

  const doConfirm = () => {
    const resa = {
      ref: makeRef(), dateISO: b.date, service: b.service, slot: b.slot, party: b.party,
      zone: b.zone, firstName: b.firstName, lastName: b.lastName, email: b.email, phone: b.phone,
      occasion: b.occasion, notes: b.notes, status: "confirmee", deposit: b.party * DEPOSIT_PER_SEAT,
    };
    addReservation(resa);
    setConfirmed(resa);
  };

  return (
    <div className="container" style={{ padding: "48px 32px 90px" }}>
      <Stepper current={step} />
      <div className="resa-grid" style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 48, alignItems: "start" }}>
        <div>
          {step === "search" && <StepSearch b={b} setB={setB} next={() => setStep("slots")} />}
          {step === "slots" && <StepSlots b={b} setB={setB} next={() => setStep("details")} back={() => setStep("search")} />}
          {step === "details" && <StepDetails b={b} setB={setB} next={() => setStep("payment")} back={() => setStep("slots")} />}
          {step === "payment" && <StepPayment b={b} setB={setB} confirm={doConfirm} back={() => setStep("details")} />}
        </div>
        <AsideSummary b={b} goStep={goStep} />
      </div>
    </div>
  );
}

Object.assign(window, { BookingFlow, Confirmation });
