// Menu page — real items from v2 + carta original images
const MENU_LS_KEY = "creeks_menu_v1";

function getMenuPrices() {
  try {
    const s = localStorage.getItem(MENU_LS_KEY);
    if (!s) return {};
    const data = JSON.parse(s);
    const prices = {};
    Object.values(data).forEach(cat => {
      cat.items.forEach(item => { prices[item.name] = item; });
    });
    return prices;
  } catch(e) { return {}; }
}

const MenuItemRow = ({ name }) => {
  const prices = React.useMemo(() => getMenuPrices(), []);
  const data = prices[name];
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "11px 14px", borderRadius: 8, background: "var(--cream)", marginBottom: 6, opacity: data && !data.available ? 0.45 : 1 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ fontWeight: 600, color: "var(--navy-deep)" }}>{name}</span>
        {data && !data.available && <span style={{ background: "var(--coral)", color: "#fff", fontSize: "0.7rem", fontWeight: 800, padding: "2px 8px", borderRadius: 999 }}>Indisponível</span>}
      </div>
      <small style={{ color: data && data.price > 0 ? "var(--gold-deep)" : "var(--muted)", fontWeight: data && data.price > 0 ? 800 : 400, fontSize: "0.86rem" }}>
        {data && data.price > 0 ? `${data.price.toFixed(2).replace(".", ",")}€` : "Preço a confirmar"}
      </small>
    </div>
  );
};

const MENU_DATA = [
  { title: "Brunch", note: "Todos os dias até às 12h, com combinações Creek's para começar sem pressa.", items: ["Beethoven", "Dama e Vagabundo", "101 Dálmatas", "Pluto", "Iogurte natural", "Molletes da manhã"] },
  { title: "Hambúrgueres Gourmet", note: "Servidos em pão artesanal, com nomes da casa e espírito food & fun.", items: ["Rafeiro", "Boxer", "Dálmata", "Rottweiler", "Labrador", "Husky", "Serra da Estrela", "Cocker", "Pastor Belga", "Veggie I", "Veggie II", "Shar-Pei", "S. Bernardo"] },
  { title: "Pizzas na tábua", note: "Para dividir, com salada e combinações descontraídas.", items: ["Edição limitada de verão", "Edição limitada de inverno", "Bacon, azeitonas, tomate e mozarella", "Camarão, ananás, azeitonas, tomate e mozarella", "Queijo chèvre, doce de frutos vermelhos, rúcula e tomate"] },
  { title: "Saladas", note: "Frescas, generosas e coloridas, com combinações que fogem ao óbvio.", items: ["Salada de Camarão", "Salada de Águas Frias", "Salada Muuu", "Grega", "Marselhesa", "Tenório"] },
  { title: "Bowls", note: "Opções frias e quentes, pensadas para almoço leve e saboroso.", items: ["Açaí bowl", "Poké de salmão", "Bowl de camarão e bulgur", "Bowl de camarão, arroz e legumes", "Bowl quente Creek's"] },
  { title: "Tradições & pratos do dia", note: "Cozinha de conforto, pratos de almoço e sugestões que mudam conforme a casa.", items: ["Sopa do dia", "Prego de vitela no bolo do caco", "Strips de vitela", "Pastéis de massa muito tenra", "Pratos de bacalhau", "Sugestões de almoço"] },
  { title: "Tartes e bolos", note: "Life is short... eat dessert first.", items: ["Vedeta", "Brownie de chocolate", "Limão merengada", "Doce de leite e lima", "Noz e ovos moles", "Cheesecake brownie", "Pavlova XS", "Tarte de amêndoa"] },
  { title: "Café & bebidas", note: "Café, sumos e bebidas frescas para acompanhar qualquer momento.", items: ["Café", "Galão", "Cappuccino", "Sumo de laranja", "Limonada", "Bebidas frescas"] },
];

const MENU_SHEETS = [
  { title: "Brunch", img: "assets/creeks-real/creeks-menu-brunch.jpg" },
  { title: "Hambúrgueres Gourmet", img: "assets/creeks-real/creeks-menu-hamburgers.jpg" },
  { title: "Pizzas e saladas", img: "assets/creeks-real/creeks-menu-pizzas-saladas.jpg" },
  { title: "Sobremesas", img: "assets/creeks-real/creeks-menu-sobremesa.jpg" },
];

const MenuPage = ({ go, openReserve }) => {
  const [active, setActive] = React.useState(MENU_DATA[0].title);
  const selected = MENU_DATA.find(c => c.title === active);
  return (
    <section className="section">
      <div className="section-inner">
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22 }}>
          <button className="btn ghost sm" onClick={() => go("home")}>
            <Icon name="arrowLeft" size={14} /> Voltar
          </button>
          <p className="eyebrow gold" style={{ margin: 0 }}>Food &amp; Fun</p>
        </div>
        <h1>A carta Creek's, com nomes da casa.</h1>
        <p className="section-copy" style={{ fontSize: "1.1rem", marginBottom: 36 }}>
          Brunch até às 12h, hambúrgueres gourmet, pizzas na tábua, saladas, bowls, pratos do dia, tartes e bolos.
        </p>
        <div style={{ display: "flex", gap: 10, marginBottom: 36, flexWrap: "wrap" }}>
          <button className="btn primary" onClick={() => openReserve && openReserve()}>
            <Icon name="calendar" size={16} /> Reservar Mesa
          </button>
          <button className="btn secondary" onClick={() => go("home")}>
            <Icon name="arrowLeft" size={16} /> Voltar à Home
          </button>
        </div>

        <div className="menu-board-2col">
          <aside className="menu-tabs-vertical">
            {MENU_DATA.map(cat => (
              <button key={cat.title} className={active === cat.title ? "active" : ""} onClick={() => setActive(cat.title)}>
                <span>{cat.title}</span>
              </button>
            ))}
          </aside>

          <div style={{ background: "var(--warm-white)", border: "1px solid var(--line)", borderRadius: 14, padding: 32 }}>
            <p className="eyebrow">Categoria</p>
            <h2 style={{ marginTop: 8 }}>{selected.title}</h2>
            <p style={{ color: "var(--muted)", marginTop: 8, marginBottom: 24 }}>{selected.note}</p>
            <div style={{ display: "grid", gap: 2 }}>
              {selected.items.map(item => (
                <MenuItemRow key={item} name={item} />
              ))}
            </div>
            <p style={{ color: "var(--muted)", fontSize: "0.82rem", marginTop: 20 }}>Menu indicativo. Produtos, preços e disponibilidade podem variar.</p>
          </div>
        </div>

        {/* Carta original — folhas */}
        <div style={{ marginTop: 72 }}>
          <div className="section-title-row" style={{ marginBottom: 32 }}>
            <div>
              <p className="eyebrow">Carta original</p>
              <h2>Textura de papel, ilustração e humor Creek's</h2>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 20 }}>
            {MENU_SHEETS.map(sheet => (
              <article key={sheet.title} style={{ borderRadius: 12, overflow: "hidden", border: "1px solid var(--line)" }}>
                <a href={sheet.img} target="_blank" rel="noreferrer">
                  <img src={sheet.img} alt={sheet.title} style={{ width: "100%", height: 280, objectFit: "cover", display: "block" }} />
                </a>
                <div style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <h3 style={{ fontSize: "1rem" }}>{sheet.title}</h3>
                  <span style={{ color: "var(--muted)", fontSize: "0.82rem" }}>Abrir em grande</span>
                </div>
              </article>
            ))}
          </div>
        </div>

        {/* Cross-sell */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 18, marginTop: 50 }}>
          <article style={{ background: "linear-gradient(135deg, var(--cream), #f3dfb4)", border: "1px solid var(--line)", borderRadius: 14, padding: 28, display: "grid", gap: 12 }}>
            <Icon name="cake" size={28} />
            <h3>Quer algo personalizado?</h3>
            <p style={{ color: "var(--muted)" }}>Para aniversários, eventos ou só por gula. Configure o seu bolo no nosso configurador.</p>
            <button className="btn primary" style={{ justifySelf: "start" }} onClick={() => go("bolo")}>
              Pedir bolo <Icon name="arrowRight" size={14} />
            </button>
          </article>
          <article style={{ background: "linear-gradient(135deg, var(--navy), var(--navy-deep))", color: "var(--warm-white)", border: 0, borderRadius: 14, padding: 28, display: "grid", gap: 12 }}>
            <Icon name="catering" size={28} style={{ color: "var(--gold)" }} />
            <h3 style={{ color: "var(--warm-white)" }}>Eventos &amp; catering</h3>
            <p style={{ color: "#fffdf5cc" }}>Coffee breaks, casamentos, batizados ou jantares privados. Fazemos por medida.</p>
            <button className="btn secondary" style={{ justifySelf: "start" }} onClick={() => go("catering")}>
              Ver catering <Icon name="arrowRight" size={14} />
            </button>
          </article>
        </div>
      </div>
    </section>
  );
};

const ContactosPage = ({ go, openReserve }) => (
  <section className="section">
    <div className="section-inner">
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22 }}>
        <button className="btn ghost sm" onClick={() => go("home")}>
          <Icon name="arrowLeft" size={14} /> Voltar
        </button>
        <p className="eyebrow gold" style={{ margin: 0 }}>Contactos</p>
      </div>
      <h1>Creek's Caffé na Venda do Pinheiro</h1>
      <p className="section-copy" style={{ fontSize: "1.1rem" }}>
        Brunch, café, pastelaria artesanal, bolos, almoço e catering num espaço acolhedor.
      </p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 20, marginTop: 36 }}>
        <article style={{ background: "var(--warm-white)", border: "1px solid var(--line)", borderRadius: 14, padding: 30, boxShadow: "var(--shadow-sm)", display: "grid", gap: 14 }}>
          <Icon name="mapPin" size={28} />
          <p className="eyebrow">Morada</p>
          <h2 style={{ fontSize: "1.3rem" }}>Av. 9 de Julho, 94B,<br />2665-522 Venda do Pinheiro</h2>
          <a className="btn primary" href="https://www.google.com/maps/search/?api=1&query=Av.%209%20de%20Julho%2C%2094B%2C%202665-522%20Venda%20do%20Pinheiro" target="_blank" rel="noreferrer">
            Abrir no Google Maps <Icon name="arrowRight" size={14} />
          </a>
        </article>

        <article style={{ background: "var(--warm-white)", border: "1px solid var(--line)", borderRadius: 14, padding: 30, boxShadow: "var(--shadow-sm)", display: "grid", gap: 14 }}>
          <Icon name="phone" size={28} />
          <p className="eyebrow">Telefone</p>
          <h2 style={{ fontSize: "1.3rem" }}>211 334 336</h2>
          <a className="btn secondary" href="tel:211334336">Ligar</a>
        </article>

        <article style={{ background: "var(--warm-white)", border: "1px solid var(--line)", borderRadius: 14, padding: 30, boxShadow: "var(--shadow-sm)", display: "grid", gap: 10 }}>
          <p className="eyebrow">Horário</p>
          {[
            { label: "Segunda a sexta", value: "07h45 – 16h00" },
            { label: "Sábado", value: "08h30 – 15h00" },
            { label: "Domingo", value: "Encerrado" },
          ].map(h => (
            <div key={h.label} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--line)" }}>
              <span style={{ color: "var(--muted)" }}>{h.label}</span>
              <strong style={{ color: "var(--navy-deep)" }}>{h.value}</strong>
            </div>
          ))}
        </article>

        <article style={{ background: "var(--warm-white)", border: "1px solid var(--line)", borderRadius: 14, padding: 30, boxShadow: "var(--shadow-sm)", display: "grid", gap: 14 }}>
          <p className="eyebrow">Redes sociais</p>
          <div style={{ display: "flex", gap: 12 }}>
            <a href="https://www.instagram.com/creekscaffe/" target="_blank" rel="noreferrer"
              style={{ width: 42, height: 42, borderRadius: "50%", border: "1px solid var(--line)", display: "grid", placeItems: "center" }}>
              <Icon name="instagram" size={18} />
            </a>
            <a href="https://www.facebook.com/creekscaffe" target="_blank" rel="noreferrer"
              style={{ width: 42, height: 42, borderRadius: "50%", border: "1px solid var(--line)", display: "grid", placeItems: "center" }}>
              <Icon name="facebook" size={18} />
            </a>
          </div>
          <div style={{ display: "grid", gap: 8 }}>
            <button className="btn primary" onClick={() => openReserve && openReserve()}>Reservar Mesa</button>
            <button className="btn secondary" onClick={() => go("bolo")}>Pedir Bolo</button>
          </div>
        </article>
      </div>
    </div>
  </section>
);

// FLOATING ORDER WINDOW — minimal version of Bolo/Catering inside a popup
const FloatingOrderWindow = ({ kind, onClose, go }) => {
  const isCatering = kind === "catering";
  const [size, setSize] = React.useState(isCatering ? null : "m");
  const [event, setEvent] = React.useState(isCatering ? "aniversario" : null);
  const [pax, setPax] = React.useState(30);
  const [massa, setMassa] = React.useState("chocolate");
  const [recheio, setRecheio] = React.useState("doceleite");

  const total = isCatering ? pax * 8.5 : (size === "s" ? 22 : size === "m" ? 34 : size === "l" ? 48 : 68) + 2 + 2;

  return (
    <>
      <button onClick={onClose} aria-label="Fechar"
        style={{ position: "fixed", inset: 0, zIndex: 65, background: "#082a3866", border: 0, cursor: "pointer" }} />
      <div className="float-window">
        <div className="float-window-head">
          <span className="ic"><Icon name={isCatering ? "catering" : "cake"} size={18} /></span>
          <div>
            <strong>{isCatering ? "Pedir Catering" : "Pedir Bolo"}</strong>
            <span>Janela rápida · {isCatering ? "estimativa por pax" : "configuração simples"}</span>
          </div>
          <button onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="float-window-body">
          {!isCatering ? (
            <>
              <div className="config-step">
                <div className="config-step-head"><span className="num">01</span><h3 style={{ fontSize: "1.1rem" }}>Tamanho</h3></div>
                <div className="size-grid">
                  {window.SIZES_DATA.map(s => (
                    <button key={s.id} className={"size-pill" + (s.id === size ? " selected" : "")} onClick={() => setSize(s.id)}>
                      <span className="label" style={{ fontSize: "1rem" }}>{s.label}</span>
                      <span className="sub">{s.diameter}</span>
                      <span className="price">{s.price}€</span>
                    </button>
                  ))}
                </div>
              </div>
              <div className="config-step">
                <div className="config-step-head"><span className="num">02</span><h3 style={{ fontSize: "1.1rem" }}>Massa</h3></div>
                <div className="swatch-grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
                  {window.MASSAS_DATA.slice(0, 3).map(it => (
                    <button key={it.id} className={"swatch" + (it.id === massa ? " selected" : "")} onClick={() => setMassa(it.id)} style={{ minHeight: 0 }}>
                      <div className="swatch-color" style={{ background: it.color, height: 40, color: window.getContrast(it.color), fontSize: "0.9rem" }}>
                        {it.name.slice(0, 1)}<span className="check"><Icon name="check" size={10} stroke={3} /></span>
                      </div>
                      <div className="swatch-body" style={{ padding: "8px 10px" }}>
                        <span className="name" style={{ fontSize: "0.84rem" }}>{it.name}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
              <div className="config-step">
                <div className="config-step-head"><span className="num">03</span><h3 style={{ fontSize: "1.1rem" }}>Recheio</h3></div>
                <div className="swatch-grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
                  {window.RECHEIOS_DATA.slice(0, 3).map(it => (
                    <button key={it.id} className={"swatch" + (it.id === recheio ? " selected" : "")} onClick={() => setRecheio(it.id)} style={{ minHeight: 0 }}>
                      <div className="swatch-color" style={{ background: it.color, height: 40, color: window.getContrast(it.color), fontSize: "0.9rem" }}>
                        {it.name.slice(0, 1)}<span className="check"><Icon name="check" size={10} stroke={3} /></span>
                      </div>
                      <div className="swatch-body" style={{ padding: "8px 10px" }}>
                        <span className="name" style={{ fontSize: "0.84rem" }}>{it.name}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="config-step">
                <div className="config-step-head"><span className="num">01</span><h3 style={{ fontSize: "1.1rem" }}>Tipo de evento</h3></div>
                <div className="event-type-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
                  {window.EVENT_TYPES_DATA.slice(0, 4).map(et => (
                    <button key={et.id} className={"event-type-card" + (et.id === event ? " selected" : "")} onClick={() => setEvent(et.id)} style={{ padding: "12px 8px" }}>
                      <span className="ic" style={{ width: 36, height: 36 }}><Icon name={et.icon} size={18} /></span>
                      <span className="label" style={{ fontSize: "0.94rem" }}>{et.label}</span>
                    </button>
                  ))}
                </div>
              </div>
              <div className="config-step">
                <div className="config-step-head"><span className="num">02</span><h3 style={{ fontSize: "1.1rem" }}>Nº pessoas</h3></div>
                <div className="pax-bar">
                  <div className="pax-display">
                    <span className="lbl">Pax</span>
                    <span className="num">{pax}</span>
                  </div>
                  <div className="pax-quick">
                    {[10, 20, 30, 50, 80, 120].map(p => (
                      <button key={p} className={pax === p ? "selected" : ""} onClick={() => setPax(p)}>{p}</button>
                    ))}
                  </div>
                </div>
              </div>
              <div className="config-step">
                <div className="config-step-head"><span className="num">03</span><h3 style={{ fontSize: "1.1rem" }}>Data e contacto</h3></div>
                <div className="field"><label>Data do evento</label><input type="date" /></div>
                <div className="field" style={{ marginTop: 8 }}><label>Telefone</label><input placeholder="912 345 678" /></div>
              </div>
            </>
          )}
        </div>
        <div className="float-window-foot">
          <div>
            <span className="total-label">Estimativa</span>
            <div className="total">{total.toFixed(0)}€</div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn ghost sm" onClick={() => { onClose(); go(kind); }}>
              Ver detalhe completo
            </button>
            <button className="btn primary sm">Enviar pedido</button>
          </div>
        </div>
      </div>
    </>
  );
};

window.MenuPage = MenuPage;
window.ContactosPage = ContactosPage;
window.FloatingOrderWindow = FloatingOrderWindow;

const TIME_SLOTS = ["08:00","09:00","10:00","11:00","12:30","13:30","14:30","16:00","17:00","18:00","19:00"];
const CAPACITY = 30;

function getSlotLoad(dateStr) {
  const reservations = window.creeksData ? window.creeksData.getReservations() : [];
  const loads = {};
  reservations.forEach(r => {
    if (r.reservation_date === dateStr && r.status !== "cancelled") {
      const guests = parseInt(r.guests) || 1;
      loads[r.reservation_time] = (loads[r.reservation_time] || 0) + guests;
    }
  });
  return loads;
}

const ReservationModal = ({ onClose }) => {
  const [step, setStep] = React.useState(1);
  const [people, setPeople] = React.useState(2);
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [pref, setPref] = React.useState("indiferente");
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [notes, setNotes] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const DAY_PT = ["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"];
  const MON_PT = ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"];
  const dates = Array.from({ length: 14 }, (_, i) => {
    const d = new Date(); d.setDate(d.getDate() + i); return d;
  });

  const dateStr = date ? date.toISOString().slice(0,10) : null;
  const slotLoad = dateStr ? getSlotLoad(dateStr) : {};

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const canContinue = date !== null && time !== null;

  const submit = (e) => {
    e.preventDefault();
    setSubmitting(true);
    if (window.creeksData) {
      window.creeksData.createReservation({
        name, phone, email,
        reservation_date: dateStr,
        reservation_time: time,
        guests: people,
        area: pref,
        message: notes,
      });
    }
    setSubmitted(true);
    setTimeout(onClose, 2800);
  };

  return (
    <div className="res-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="res-modal-v2" role="dialog" aria-modal="true">

        {/* HEADER */}
        <div className="res-v2-header">
          <div className="res-v2-brand">
            <img src="assets/creeks-logo.jpg" alt="Creek's Caffé" />
            <div>
              <small>Creek's Caffé</small>
              <strong>Reservar Mesa</strong>
            </div>
          </div>
          <button className="res-v2-close" onClick={onClose} aria-label="Fechar">✕</button>
        </div>

        {/* STEP TABS */}
        <div className="res-v2-steps">
          <button className={"res-v2-step" + (step === 1 ? " active" : "")} onClick={() => setStep(1)}>
            <span className="res-v2-step-num">1</span> QUANDO
          </button>
          <button className={"res-v2-step" + (step === 2 ? " active" : "")}
            onClick={() => canContinue && setStep(2)} disabled={!canContinue}>
            <span className="res-v2-step-num">2</span> DETALHES
          </button>
        </div>

        {/* STEP 1 */}
        {step === 1 && !submitted && (
          <div className="res-v2-body">
            <div className="res-v2-group">
              <label className="res-v2-label">PESSOAS</label>
              <div className="res-v2-people">
                {[1,2,3,4,5,6,7,8].map(n => (
                  <button key={n} className={"res-v2-num" + (people === n ? " active" : "")} onClick={() => setPeople(n)}>{n}</button>
                ))}
                <button className={"res-v2-num" + (people >= 9 ? " active" : "")} onClick={() => setPeople(9)}>9+</button>
              </div>
            </div>

            <div className="res-v2-group">
              <label className="res-v2-label">DATA</label>
              <div className="res-v2-date-strip">
                {dates.map((d, i) => (
                  <button key={i}
                    className={"res-v2-date-cell" + (date && date.toDateString() === d.toDateString() ? " active" : "") + (i === 0 ? " today" : "")}
                    onClick={() => { setDate(d); setTime(null); }}>
                    <span className="rdday">{DAY_PT[d.getDay()]}</span>
                    <span className="rdnum">{d.getDate()}</span>
                    <span className="rdmon">{MON_PT[d.getMonth()]}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* TIME SLOTS — only show after date selected */}
            {date && (
              <div className="res-v2-group">
                <label className="res-v2-label">HORA</label>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {TIME_SLOTS.map(slot => {
                    const booked = slotLoad[slot] || 0;
                    const full = booked + people > CAPACITY;
                    const selected = time === slot;
                    return (
                      <button key={slot}
                        disabled={full}
                        onClick={() => setTime(slot)}
                        style={{
                          padding: "10px 16px", borderRadius: 10, border: "1.5px solid",
                          fontWeight: 800, fontSize: "0.92rem", cursor: full ? "not-allowed" : "pointer",
                          transition: "all 0.15s",
                          background: selected ? "var(--navy)" : full ? "#0e3a4a08" : "var(--warm-white)",
                          color: selected ? "var(--warm-white)" : full ? "#0e3a4a40" : "var(--navy-deep)",
                          borderColor: selected ? "var(--navy)" : full ? "#0e3a4a14" : "#0e3a4a1e",
                          boxShadow: selected ? "0 6px 18px #082a3830" : "none",
                          textDecoration: full ? "line-through" : "none",
                        }}>
                        {slot}
                        {full && <span style={{ fontSize: "0.7rem", display: "block", fontWeight: 600, opacity: 0.6 }}>Lotado</span>}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            <div className="res-v2-group">
              <label className="res-v2-label">PREFERÊNCIA</label>
              <div className="res-v2-pref">
                {["interior","exterior","indiferente"].map(p => (
                  <button key={p} className={"res-v2-pref-btn" + (pref === p ? " active" : "")} onClick={() => setPref(p)}>
                    {p.toUpperCase()}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* STEP 2 */}
        {step === 2 && !submitted && (
          <form className="res-v2-body" onSubmit={submit}>
            <div className="res-v2-group">
              <label className="res-v2-label">NOME</label>
              <input className="res-v2-input" required value={name} onChange={e => setName(e.target.value)} placeholder="O seu nome" />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div className="res-v2-group">
                <label className="res-v2-label">TELEFONE</label>
                <input className="res-v2-input" required type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="912 345 678" />
              </div>
              <div className="res-v2-group">
                <label className="res-v2-label">EMAIL <span style={{ opacity:0.45, fontWeight:500, textTransform:"none", letterSpacing:0 }}>(opcional)</span></label>
                <input className="res-v2-input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="email@exemplo.pt" />
              </div>
            </div>
            <div className="res-v2-group">
              <label className="res-v2-label">OBSERVAÇÕES <span style={{ opacity:0.45, fontWeight:500, textTransform:"none", letterSpacing:0 }}>(opcional)</span></label>
              <textarea className="res-v2-input" rows="3" value={notes} onChange={e => setNotes(e.target.value)} placeholder="Aniversário, cadeira para bebé, intolerâncias…" />
            </div>
            <div className="res-v2-summary">
              <strong>Resumo</strong>
              {people} {people===1?"pessoa":"pessoas"} · {date ? date.toLocaleDateString("pt-PT",{weekday:"long",day:"numeric",month:"long"}) : ""} às {time} · {pref}
            </div>
            <button type="submit" className="btn primary full lg" disabled={submitting} style={{ marginTop: 4 }}>
              <Icon name="check" size={16} /> Confirmar Reserva
            </button>
            <p style={{ color:"var(--muted)", fontSize:"0.8rem", textAlign:"center", marginTop:-8 }}>
              Confirmação por SMS. Cancelamento até 2h antes.
            </p>
          </form>
        )}

        {/* SUCCESS */}
        {submitted && (
          <div className="res-v2-success">
            <div className="res-v2-success-icon">✓</div>
            <div>
              <h3>Pedido recebido!</h3>
              <p>Confirmamos por SMS em breve.</p>
            </div>
          </div>
        )}

        {/* FOOTER step 1 */}
        {step === 1 && !submitted && (
          <div className="res-v2-footer">
            <span className="res-v2-hint">
              {!date ? "Escolhe data e hora para continuar" : !time ? "Escolhe um horário" : `${people} ${people===1?"pessoa":"pessoas"} · ${date.toLocaleDateString("pt-PT",{day:"numeric",month:"short"})} às ${time}`}
            </span>
            <button className="btn primary" style={{ minHeight:48, paddingInline:28 }} onClick={() => setStep(2)} disabled={!canContinue}>
              CONTINUAR →
            </button>
          </div>
        )}
        {step === 2 && !submitted && (
          <div className="res-v2-footer">
            <button className="btn ghost sm" onClick={() => setStep(1)}>← Voltar</button>
            <span />
          </div>
        )}
      </div>
    </div>
  );
};

window.ReservationModal = ReservationModal;
