// Catering page — portfolio marquee (NO pause on hover) + simple package configurator
const CATERING_TOP = [
  { img: "assets/creeks-real/creeks-bolo-frutos.jpg", title: "Bolo Casamento — Frutos Vermelhos", tag: "Casamento · 80 pax", tall: true },
  { img: "assets/creeks-real/creeks-bolo-coco.jpg", title: "Bolo Coco & Maracujá", tag: "Aniversário · 25 pax" },
  { img: "assets/creeks-real/creeks-vedeta-chocolate.jpg", title: "Naked Cake Chocolate", tag: "Batizado · 40 pax", tall: true },
  { img: "assets/creeks-real/creeks-bolo-framboesa.jpg", title: "Bolo Framboesa & Lima", tag: "Despedida · 18 pax" },
  { img: "assets/creeks-real/creeks-brownie.jpg", title: "Mesa de Doces Brownies", tag: "Empresa · 120 pax", tall: true },
  { img: "assets/creeks-real/creeks-bolo-frutos.jpg", title: "Bolo Andares — Berries", tag: "Casamento · 100 pax" },
];

const CATERING_BOTTOM = [
  { img: "assets/creeks-real/creeks-salada-real.jpg", title: "Mesa Salgada — Workshop", tag: "Coffee break · 35 pax", tall: true },
  { img: "assets/creeks-real/creeks-interior-menu.jpg", title: "Brunch Privado", tag: "Aniversário · 22 pax" },
  { img: "assets/creeks-real/creeks-bolo-coco.jpg", title: "Doces Mini — Comunhão", tag: "Comunhão · 50 pax", tall: true },
  { img: "assets/creeks-real/creeks-brownie.jpg", title: "Caixas Take-Away", tag: "Empresa · 60 pax" },
  { img: "assets/creeks-real/creeks-bolo-framboesa.jpg", title: "Bolo Vegan Limão", tag: "Aniversário · 30 pax", tall: true },
  { img: "assets/creeks-real/creeks-vedeta-chocolate.jpg", title: "Sobremesa Privada", tag: "Jantar · 14 pax" },
];

const EVENT_TYPES = [
  { id: "aniversario", label: "Aniversário", icon: "cake", sub: "Festa privada" },
  { id: "casamento", label: "Casamento", icon: "sparkles", sub: "Cerimónia" },
  { id: "batizado", label: "Batizado", icon: "leaf", sub: "Familiar" },
  { id: "empresa", label: "Empresa", icon: "users", sub: "Corporativo" },
];

const PACKAGES = [
  {
    id: "coffee", label: "Coffee Break", price: 6.5, icon: "coffee",
    color: "#d7b85a",
    desc: "Café, sumos, água, croissants, scones e queijadas.",
    includes: ["Café, sumos naturais, água", "Mini-croissants e scones", "Queijadas variadas", "Fruta fresca"],
  },
  {
    id: "doce", label: "Mesa Doce", price: 9.8, icon: "cookie",
    color: "#a82846",
    desc: "Selecção generosa de doces e bolo central.",
    includes: ["Brownies, tartelettes, macarons", "Queijadas variadas", "Bolo central por medida", "Verrines doces", "Bebidas frias"],
  },
  {
    id: "mista", label: "Mesa Mista", price: 14.5, icon: "catering",
    color: "#6f8a55",
    desc: "Doces e salgados completos para receção.",
    includes: ["Mini-quiches e sandes gourmet", "Saladas em copo, tábua charcutaria", "Mesa de doces completa", "Bebidas (sumos, vinho do Porto)", "Bolo cerimónia opcional"],
    popular: true,
  },
  {
    id: "bolo", label: "Bolo Cerimónia", price: 120, icon: "cake", unit: "base",
    color: "#0e3a4a",
    desc: "Apenas bolo personalizado por andares.",
    includes: ["Bolo até 3 andares", "Decoração tema do evento", "Topper personalizado", "Entrega no local"],
  },
];

const EXTRAS = [
  { id: "entrega", label: "Entrega no local", price: 35, icon: "truck", flat: true },
  { id: "montagem", label: "Montagem + decoração", price: 60, icon: "sparkles", flat: true },
  { id: "louca", label: "Louça e talheres", price: 1.5, icon: "package" },
  { id: "empregado", label: "Empregado de mesa", price: 95, icon: "users", flat: true },
];

const CateringPage = ({ go }) => {
  const [event, setEvent] = React.useState("aniversario");
  const [pkg, setPkg] = React.useState("mista");
  const [pax, setPax] = React.useState(30);
  const [paxCustom, setPaxCustom] = React.useState(false);
  const [extras, setExtras] = React.useState(["entrega"]);
  const [eventDate, setEventDate] = React.useState("");
  const [eventTime, setEventTime] = React.useState("");
  const [notes, setNotes] = React.useState("");

  const selEvent = EVENT_TYPES.find(e => e.id === event);
  const selPkg = PACKAGES.find(p => p.id === pkg);
  const isFlatPkg = selPkg.unit === "base";
  const pkgCost = isFlatPkg ? selPkg.price : selPkg.price * pax;
  const extrasCost = extras.reduce((s, id) => {
    const ex = EXTRAS.find(e => e.id === id);
    if (!ex) return s;
    return s + (ex.flat ? ex.price : ex.price * pax);
  }, 0);
  const total = Math.round(pkgCost + extrasCost);
  const perPax = (total / pax).toFixed(1);

  const toggleExtra = (id) => setExtras(e => e.includes(id) ? e.filter(x => x !== id) : [...e, id]);

  return (
    <>
      <section className="section paper-section" style={{ paddingBottom: 56 }}>
        <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 }}>Catering & Eventos</p>
          </div>
          <h1 style={{ fontSize: "clamp(2.4rem, 4.5vw, 4.6rem)" }}>
            Os bolos que já fizemos. <span style={{ color: "var(--gold-deep)" }}>Inspire-se.</span>
          </h1>
          <p className="section-copy" style={{ fontSize: "1.14rem", maxWidth: 720 }}>
            Mais de 600 eventos desde 2015. Casamentos, aniversários, batizados, coffee breaks e jantares
            privados — fazemos por medida.
          </p>

          <div className="cake-mode-tabs" style={{ marginTop: 36, maxWidth: 520 }}>
            <button onClick={() => go("bolo")}>
              <Icon name="cake" /> Pedir Bolo
            </button>
            <button className="active">
              <Icon name="catering" /> Pedir Catering
            </button>
          </div>
        </div>
      </section>

      {/* DUAL MARQUEE PORTFOLIO — no pause on hover */}
      <section className="section tight" style={{ paddingTop: 8, paddingBottom: 64 }}>
        <div style={{ marginBottom: 22, paddingLeft: "max(20px, 50vw - 620px)" }}>
          <p className="eyebrow gold">Portefólio</p>
          <h2 style={{ marginTop: 8 }}>O que entregámos esta época.</h2>
        </div>

        <div className="catering-marquee">
          <div className="marquee-track">
            {[...CATERING_TOP, ...CATERING_TOP].map((c, i) => <MarqueeCard key={`top-${i}`} {...c} />)}
          </div>
        </div>
        <div className="catering-marquee" style={{ marginTop: 18 }}>
          <div className="marquee-track reverse">
            {[...CATERING_BOTTOM, ...CATERING_BOTTOM].map((c, i) => <MarqueeCard key={`bot-${i}`} {...c} />)}
          </div>
        </div>
      </section>

      {/* CONFIGURATOR — simplified with pre-built packages */}
      <section className="section" style={{ paddingTop: 0 }}>
        <div className="section-inner">
          <div style={{ marginBottom: 32, maxWidth: 720 }}>
            <p className="eyebrow gold">Configurar evento</p>
            <h2 style={{ marginTop: 8 }}>Escolha o seu pacote.</h2>
            <p className="section-copy">
              Tipo de evento, pessoas, pacote. Estimativa em tempo real — orçamento final em 24h.
            </p>
          </div>

          <div className="cake-builder">
            {/* SUMMARY */}
            <div className="cake-preview">
              <div className="cake-preview-image" style={{ aspectRatio: "16/10", background: `linear-gradient(135deg, ${selPkg.color}cc, ${selPkg.color})`, padding: 30, display: "grid", placeItems: "center" }}>
                <div style={{ textAlign: "center", color: "var(--warm-white)" }}>
                  <Icon name={selPkg.icon} size={56} style={{ color: "var(--gold)" }} />
                  <h3 style={{ color: "var(--warm-white)", marginTop: 14, fontSize: "1.7rem" }}>{selPkg.label}</h3>
                  <p style={{ color: "#ffffffcc", marginTop: 4 }}>{selEvent.label} · {pax} pessoas</p>
                </div>
              </div>
              <div style={{ padding: "18px 18px 14px", background: "var(--cream)", borderTop: "1px solid var(--line)" }}>
                <span style={{ color: "var(--muted)", fontSize: "0.78rem", fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.04em" }}>Inclui</span>
                <ul style={{ display: "grid", gap: 6, marginTop: 8, padding: 0, listStyle: "none" }}>
                  {selPkg.includes.map((it, i) => (
                    <li key={i} style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--navy-deep)", fontSize: "0.9rem", fontWeight: 600 }}>
                      <span style={{ color: "var(--gold-deep)", flex: "none" }}><Icon name="check" size={14} stroke={3} /></span>
                      {it}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="cake-summary">
                <div className="row"><strong>{selPkg.label}</strong><span>{isFlatPkg ? `${selPkg.price}€ base` : `${selPkg.price}€/pax`}</span></div>
                <div className="row"><strong>{pax} pessoas</strong><span>{isFlatPkg ? "fixo" : `+${pkgCost.toFixed(0)}€`}</span></div>
                {extras.length > 0 && <div className="row"><strong>{extras.length} extra{extras.length > 1 ? "s" : ""}</strong><span>+{extrasCost.toFixed(0)}€</span></div>}
                <div className="row total">
                  <span>Estimativa · {perPax}€/pax</span><strong>{total}€</strong>
                </div>
              </div>
            </div>

            {/* CONFIG */}
            <div className="cake-config">
              <ConfigStep n="1" title="Tipo de evento" hint="Escolha 1">
                <div className="event-type-grid">
                  {EVENT_TYPES.map(et => (
                    <button key={et.id} className={"event-type-card" + (et.id === event ? " selected" : "")} onClick={() => setEvent(et.id)}>
                      <span className="ic"><Icon name={et.icon} size={22} /></span>
                      <span className="label">{et.label}</span>
                      <span className="sub">{et.sub}</span>
                    </button>
                  ))}
                </div>
              </ConfigStep>

              <ConfigStep n="2" title="Número de pessoas" hint={`${pax} pax`}>
                <div className="pax-bar">
                  <div className="pax-display">
                    <span className="lbl">Convidados estimados</span>
                    <span className="num">{pax}</span>
                  </div>
                  <div className="pax-quick">
                    {[10, 20, 30, 50, 80, 120, 200].map(p => (
                      <button key={p} className={pax === p && !paxCustom ? "selected" : ""} onClick={() => { setPax(p); setPaxCustom(false); }}>
                        {p}
                      </button>
                    ))}
                    <input type="number" min={5} max={500} placeholder="Outro" value={paxCustom ? pax : ""}
                      onChange={e => { setPax(parseInt(e.target.value) || 0); setPaxCustom(true); }}
                      style={{ width: 90, padding: "6px 12px", borderRadius: 999, border: "1.5px solid var(--line)", textAlign: "center", fontWeight: 800, color: "var(--navy)" }} />
                  </div>
                </div>
              </ConfigStep>

              <ConfigStep n="3" title="Pacote" hint="Escolha 1">
                <div style={{ display: "grid", gap: 12 }}>
                  {PACKAGES.map(p => (
                    <button key={p.id} className={"pkg-card" + (p.id === pkg ? " selected" : "")} onClick={() => setPkg(p.id)}>
                      <div className="pkg-color" style={{ background: p.color }}>
                        <Icon name={p.icon} size={22} style={{ color: getContrastForPkg(p.color) }} />
                      </div>
                      <div className="pkg-body">
                        <div className="pkg-head">
                          <span className="pkg-name">{p.label}</span>
                          {p.popular && <span className="pkg-badge">Mais pedido</span>}
                        </div>
                        <span className="pkg-desc">{p.desc}</span>
                      </div>
                      <div className="pkg-price">
                        <span className="amt">{p.price}€</span>
                        <span className="unit">{p.unit === "base" ? "base" : "/ pax"}</span>
                      </div>
                      <span className="pkg-tick">{p.id === pkg ? <Icon name="check" size={14} stroke={3} /> : <Icon name="plus" size={14} />}</span>
                    </button>
                  ))}
                </div>
              </ConfigStep>

              <ConfigStep n="4" title="Serviços extra" hint="Opcional">
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  {EXTRAS.map(ex => (
                    <button key={ex.id} className={"menu-item-pick" + (extras.includes(ex.id) ? " selected" : "")} onClick={() => toggleExtra(ex.id)}>
                      <span className="ribbon">{extras.includes(ex.id) ? <Icon name="check" size={12} stroke={3} /> : <Icon name="plus" size={12} stroke={2.5} />}</span>
                      <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <Icon name={ex.icon} size={16} />
                        <span className="name" style={{ padding: 0 }}>{ex.label}</span>
                      </span>
                      <span className="price">+{ex.price}€ {ex.flat ? "" : "/ pax"}</span>
                    </button>
                  ))}
                </div>
              </ConfigStep>

              <ConfigStep n="5" title="Data e contacto" hint="Mínimo 2 semanas">
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                  <div className="field"><label>Data</label><input type="date" value={eventDate} onChange={e => setEventDate(e.target.value)} /></div>
                  <div className="field"><label>Hora</label><input type="time" value={eventTime} onChange={e => setEventTime(e.target.value)} /></div>
                </div>
                <div className="field" style={{ marginTop: 12 }}>
                  <label>Notas (opcional)</label>
                  <textarea rows="2" value={notes} onChange={e => setNotes(e.target.value)} placeholder="Alergias, referências, local…" />
                </div>
              </ConfigStep>

              <div className="button-row" style={{ marginTop: 12 }}>
                <button className="btn primary lg">
                  <Icon name="check" /> Pedir orçamento — {total}€
                </button>
                <button className="btn ghost lg">
                  <Icon name="download" /> Guardar rascunho
                </button>
              </div>
              <p style={{ color: "var(--muted)", fontSize: "0.88rem" }}>
                * Valor estimado. Confirmação detalhada por email em 24h.
              </p>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

const MarqueeCard = ({ img, title, tag, tall }) => (
  <div className={"marquee-card" + (tall ? " tall" : "")}>
    <img src={img} alt={title} />
    <div className="marquee-overlay">
      <span>{tag}</span>
      <h4>{title}</h4>
    </div>
  </div>
);

const ConfigStep = ({ n, title, hint, children }) => (
  <div className="config-step">
    <div className="config-step-head">
      <span className="num">{Number(n) < 10 ? "0" + n : n}</span>
      <h3>{title}</h3>
      {hint && <span className="hint">{hint}</span>}
    </div>
    {children}
  </div>
);

function getContrastForPkg(hex) {
  const c = hex.replace("#", "");
  const r = parseInt(c.slice(0, 2), 16), g = parseInt(c.slice(2, 4), 16), b = parseInt(c.slice(4, 6), 16);
  return (r * 299 + g * 587 + b * 114) / 1000 >= 160 ? "#0e3a4a" : "#fffdf5";
}

window.CateringPage = CateringPage;
window.EVENT_TYPES_DATA = EVENT_TYPES;
