// Bolo page — simple configurator: tamanho, massa, recheio, topping, fatias, mensagem + data
const BOLO_IMAGES = [
  "assets/creeks-real/creeks-bolo-frutos.jpg",
  "assets/creeks-real/creeks-bolo-coco.jpg",
  "assets/creeks-real/creeks-bolo-framboesa.jpg",
  "assets/creeks-real/creeks-vedeta-chocolate.jpg",
];

const SIZES = [
  { id: "s", label: "P", diameter: "16 cm", servings: "6 – 8", price: 22 },
  { id: "m", label: "M", diameter: "20 cm", servings: "10 – 12", price: 34 },
  { id: "l", label: "G", diameter: "24 cm", servings: "14 – 18", price: 48 },
  { id: "xl", label: "XG", diameter: "28 cm", servings: "20 – 25", price: 68 },
];

const MASSAS = [
  { id: "baunilha", name: "Baunilha", color: "#f1d9a1", price: 0, note: "Clássica" },
  { id: "chocolate", name: "Chocolate", color: "#5a3320", price: 2, note: "Cacau intenso" },
  { id: "limao", name: "Limão", color: "#e7d266", price: 1, note: "Cítrica" },
  { id: "redvelvet", name: "Red Velvet", color: "#a83244", price: 4, note: "Veludo" },
  { id: "cenoura", name: "Cenoura", color: "#d68b3c", price: 1, note: "Húmida" },
  { id: "amendoa", name: "Amêndoa", color: "#c8a872", price: 3, note: "Sem glúten" },
];

const RECHEIOS = [
  { id: "chantilly", name: "Chantilly", color: "#fffbef", price: 0, note: "Leve" },
  { id: "doceleite", name: "Doce de Leite", color: "#b97a3a", price: 2, note: "Caramelo" },
  { id: "ganache", name: "Ganache", color: "#3a2018", price: 3, note: "Chocolate negro" },
  { id: "framboesa", name: "Framboesa", color: "#a82846", price: 2, note: "Fruta fresca" },
  { id: "morango", name: "Morango Fresco", color: "#c9344c", price: 3, note: "Fruta" },
  { id: "cremoso", name: "Creme Pasteleiro", color: "#f5e5b5", price: 1, note: "Tradicional" },
];

const TOPPINGS = [
  { id: "buttercream", name: "Buttercream", color: "#fff5d8", price: 0, note: "Lisa" },
  { id: "fondant", name: "Pasta Açúcar", color: "#fdfdfd", price: 6, note: "Modelagem" },
  { id: "frutos", name: "Frutos Vermelhos", color: "#a02134", price: 4, note: "Fresco" },
  { id: "drip", name: "Drip Chocolate", color: "#3a2118", price: 5, note: "Escorrido" },
  { id: "naked", name: "Naked Cake", color: "#e9c98c", price: 0, note: "Rústico" },
];

function getContrast(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";
}

const BoloPage = ({ go }) => {
  const [size, setSize] = React.useState("m");
  const [massa, setMassa] = React.useState("chocolate");
  const [recheio, setRecheio] = React.useState("doceleite");
  const [topping, setTopping] = React.useState("drip");
  const [slices, setSlices] = React.useState(12);
  const [previewIdx, setPreviewIdx] = React.useState(0);
  const [msg, setMsg] = React.useState("");
  const [date, setDate] = React.useState("");

  const selSize = SIZES.find(s => s.id === size);
  const selMassa = MASSAS.find(m => m.id === massa);
  const selRecheio = RECHEIOS.find(r => r.id === recheio);
  const selTopping = TOPPINGS.find(t => t.id === topping);

  React.useEffect(() => {
    setSlices(parseInt(selSize.servings.split("–")[1] || selSize.servings.split("–")[0]));
  }, [size]);

  const extra = msg ? 4 : 0;
  const total = selSize.price + selMassa.price + selRecheio.price + selTopping.price + extra;

  return (
    <>
      <section className="section paper-section" style={{ paddingBottom: 40 }}>
        <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 }}>Bolos personalizados</p>
          </div>
          <h1 style={{ fontSize: "clamp(2.2rem, 4vw, 4rem)" }}>Construa o seu bolo.</h1>
          <p className="section-copy" style={{ fontSize: "1.12rem" }}>
            Tamanho, massa, recheio, topping. Simples, atualizado em tempo real — confirmação por email em 24h.
          </p>

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

      <section className="section tight" style={{ paddingTop: 0 }}>
        <div className="section-inner">
          <div className="cake-builder">
            <div className="cake-preview">
              <div className="cake-preview-image">
                <img src={BOLO_IMAGES[previewIdx]} alt="Bolo" />
              </div>
              <div className="cake-preview-thumbs">
                {BOLO_IMAGES.map((src, i) => (
                  <button key={i} className={previewIdx === i ? "active" : ""} onClick={() => setPreviewIdx(i)}>
                    <img src={src} alt="" />
                  </button>
                ))}
              </div>
              <div style={{ background: "var(--cream)", padding: "12px 18px", borderTop: "1px solid var(--line)", display: "flex", gap: 12, alignItems: "center" }}>
                <span style={{ color: "var(--muted)", fontSize: "0.78rem", fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.04em" }}>Cores</span>
                <div style={{ display: "flex", gap: 6, marginLeft: "auto" }}>
                  <span style={{ width: 26, height: 26, borderRadius: 8, background: selMassa.color, border: "1.5px solid #0000001a" }} title={`Massa: ${selMassa.name}`} />
                  <span style={{ width: 26, height: 26, borderRadius: 8, background: selRecheio.color, border: "1.5px solid #0000001a" }} title={`Recheio: ${selRecheio.name}`} />
                  <span style={{ width: 26, height: 26, borderRadius: 8, background: selTopping.color, border: "1.5px solid #0000001a" }} title={`Topping: ${selTopping.name}`} />
                </div>
              </div>
              <div className="cake-summary">
                <div className="row"><strong>{selSize.label} · {selSize.diameter}</strong><span>{slices} fatias</span></div>
                <div className="row"><strong>Massa {selMassa.name}</strong><span>{selMassa.price ? `+${selMassa.price}€` : "incluído"}</span></div>
                <div className="row"><strong>Recheio {selRecheio.name}</strong><span>{selRecheio.price ? `+${selRecheio.price}€` : "incluído"}</span></div>
                <div className="row"><strong>Topping {selTopping.name}</strong><span>{selTopping.price ? `+${selTopping.price}€` : "incluído"}</span></div>
                {msg && <div className="row"><strong>Mensagem</strong><span>+4€</span></div>}
                <div className="row total">
                  <span>Total estimado</span><strong>{total}€</strong>
                </div>
              </div>
            </div>

            <div className="cake-config">
              <ConfigStep n="1" title="Tamanho" hint={`${selSize.servings} pessoas`}>
                <div className="size-grid">
                  {SIZES.map(s => (
                    <button key={s.id} className={"size-pill" + (s.id === size ? " selected" : "")} onClick={() => setSize(s.id)}>
                      <span className="label">{s.label}</span>
                      <span className="sub">{s.diameter}</span>
                      <span className="price">{s.price}€</span>
                    </button>
                  ))}
                </div>
              </ConfigStep>

              <ConfigStep n="2" title="Massa do bolo" hint="Escolha 1">
                <SwatchGrid items={MASSAS} value={massa} onChange={setMassa} />
              </ConfigStep>

              <ConfigStep n="3" title="Recheio" hint="Escolha 1">
                <SwatchGrid items={RECHEIOS} value={recheio} onChange={setRecheio} />
              </ConfigStep>

              <ConfigStep n="4" title="Topping" hint="Escolha 1">
                <SwatchGrid items={TOPPINGS} value={topping} onChange={setTopping} />
              </ConfigStep>

              <ConfigStep n="5" title="Número de fatias" hint={`${slices} fatias`}>
                <div className="slices-row">
                  <div className="slices-display">
                    <span>Fatias previstas</span>
                    <span className="val">{slices}</span>
                  </div>
                  <div className="slices-controls">
                    <button onClick={() => setSlices(Math.max(4, slices - 1))} disabled={slices <= 4}>−</button>
                    <button onClick={() => setSlices(Math.min(40, slices + 1))} disabled={slices >= 40}>+</button>
                  </div>
                </div>
              </ConfigStep>

              <ConfigStep n="6" title="Detalhes finais" hint="Opcional">
                <div style={{ display: "grid", gap: 14 }}>
                  <div className="field">
                    <label>Mensagem ou nome a topo (+4€)</label>
                    <input type="text" placeholder="Ex.: Parabéns Sofia ✿" value={msg} onChange={e => setMsg(e.target.value)} />
                  </div>
                  <div className="field">
                    <label>Data de levantamento</label>
                    <input type="date" value={date} onChange={e => setDate(e.target.value)} />
                  </div>
                </div>
              </ConfigStep>

              <div className="button-row" style={{ marginTop: 12 }}>
                <button className="btn primary lg">
                  <Icon name="check" /> Confirmar pedido — {total}€
                </button>
                <button className="btn ghost lg">
                  <Icon name="download" /> Guardar rascunho
                </button>
              </div>
              <p style={{ color: "var(--muted)", fontSize: "0.88rem" }}>
                * Preço estimado. Confirmação por email em 24h. Pagamento na loja ou MB Way.
              </p>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

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>
);

const SwatchGrid = ({ items, value, onChange }) => (
  <div className="swatch-grid">
    {items.map(it => (
      <button key={it.id} className={"swatch" + (it.id === value ? " selected" : "")} onClick={() => onChange(it.id)}>
        <div className="swatch-color" style={{ background: it.color, color: getContrast(it.color) }}>
          {it.name.slice(0, 1)}
          <span className="check"><Icon name="check" size={12} stroke={3} /></span>
        </div>
        <div className="swatch-body">
          <span className="name">{it.name}</span>
          <span className="price">{it.note} {it.price ? `· +${it.price}€` : ""}</span>
        </div>
      </button>
    ))}
  </div>
);

window.BoloPage = BoloPage;
window.SIZES_DATA = SIZES;
window.MASSAS_DATA = MASSAS;
window.RECHEIOS_DATA = RECHEIOS;
window.TOPPINGS_DATA = TOPPINGS;
window.getContrast = getContrast;
