/* ============================================================
   checkout.jsx — Create Checkout + Products CRUD + Order Bumps CRUD
   ============================================================ */

// ============================================================
// Create Checkout — main builder for a payment link
// ============================================================
function CreateCheckout(){
  const { products, bumps, pushToast, setModal, setRoute } = useApp();

  const [name, setName] = React.useState(products[1].name);
  const [desc, setDesc] = React.useState(products[1].desc);
  const [price, setPrice] = React.useState(products[1].price);
  const [installments, setInstallments] = React.useState(12);
  const [allowPix, setAllowPix] = React.useState(true);
  const [allowCard, setAllowCard] = React.useState(true);
  const [allowStripe, setAllowStripe] = React.useState(false);
  const [gateway, setGateway] = React.useState("mp"); // mp | stripe — qual gateway processa
  const [customerName, setCustomerName] = React.useState("");
  const [customerEmail, setCustomerEmail] = React.useState("");
  const [customerPhone, setCustomerPhone] = React.useState("");
  const [postUrl, setPostUrl] = React.useState("https://blackx.holdingcriativa.com.br/obrigado");
  const [status, setStatus] = React.useState("ativo");
  const [dueDate, setDueDate] = React.useState(() => {
    const d = new Date(); d.setDate(d.getDate() + 7);
    return d.toISOString().slice(0, 10);
  });

  // Order bumps selected (with active state, separate from the catalog "active" flag)
  const [bumpsOn, setBumpsOn] = React.useState(
    bumps.filter(b => b.active).slice(0, 2).map(b => b.id)
  );

  // Generated link state
  const [generated, setGenerated] = React.useState(null);
  const [generating, setGenerating] = React.useState(false);

  const total = price + bumps.filter(b => bumpsOn.includes(b.id)).reduce((a, b) => a + b.price, 0);

  const generate = () => {
    if (!name.trim() || price <= 0) { pushToast("Preencha nome e valor.", "warn"); return; }
    setGenerating(true);
    setGenerated(null);
    setTimeout(() => {
      setGenerating(false);
      const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 32);
      const id = uid();
      setGenerated({
        url: `https://pagblackx.holdingcriativa.com.br/c/${slug}-${id}`,
        id,
        slug,
      });
      pushToast("Link de pagamento gerado.");
    }, 900);
  };

  const copyLink = async () => {
    if (!generated) return;
    try { await navigator.clipboard.writeText(generated.url); pushToast("Link copiado."); }
    catch { pushToast("Não foi possível copiar.", "bad"); }
  };
  const sendWA = () => {
    if (!generated) return;
    const msg = encodeURIComponent(`Olá! Segue o link de pagamento da BlackX:\n${generated.url}`);
    pushToast("Mensagem preparada no WhatsApp.");
    window.open(`https://wa.me/?text=${msg}`, "_blank");
  };
  const previewCustomer = () => {
    if (!generated) return setRoute("/pay/preview");
    setRoute("/pay/preview");
  };

  return (
    <Shell page="checkouts" eyebrow="Operação" title="Criar checkout"
      actions={<button className="btn btn-light" onClick={() => setRoute("/dashboard")}>Cancelar</button>}>

      <div className="page-head" style={{ marginBottom: 18 }}>
        <div className="lead">
          <span className="eyebrow" style={{ fontSize: 11, letterSpacing: ".2em", color: "var(--mute)", textTransform: "uppercase", fontWeight: 600 }}>Novo</span>
          <h2>Monte uma <em className="serif-em">cobrança</em> em segundos.</h2>
          <p className="sub">Defina o produto, parcelamento e order bumps. Em seguida, gere o link, copie ou envie pelo WhatsApp.</p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16 }}>
        {/* LEFT: builder form */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card">
            <div className="card-head">
              <h3>Produto</h3>
              <span className="sub" style={{ color: "var(--mute)", fontSize: 12.5 }}>O que está sendo vendido</span>
            </div>
            <div style={{ padding: 24, display: "grid", gap: 14 }}>
              <div className="field">
                <label>Selecione um produto existente</label>
                <select className="select" defaultValue={products[1].id}
                  onChange={(e) => {
                    const p = products.find(x => x.id === e.target.value);
                    if (p){ setName(p.name); setDesc(p.desc); setPrice(p.price); }
                  }}>
                  {products.map(p => <option key={p.id} value={p.id}>{p.name} — {fmtBRL(p.price)}</option>)}
                </select>
              </div>
              <div className="field">
                <label>Nome do produto / pacote</label>
                <input className="input" value={name} onChange={(e) => setName(e.target.value)} />
              </div>
              <div className="field">
                <label>Descrição</label>
                <textarea className="textarea" value={desc} onChange={(e) => setDesc(e.target.value)} />
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
                <div className="field">
                  <label>Valor</label>
                  <div className="input-prefix">
                    <span className="pfx">R$</span>
                    <input className="input" type="number" value={price}
                      onChange={(e) => setPrice(Number(e.target.value))} />
                  </div>
                </div>
                <div className="field">
                  <label>Parcelamento</label>
                  <select className="select" value={installments} onChange={(e) => setInstallments(Number(e.target.value))}>
                    {[1, 2, 3, 6, 10, 12].map(n => <option key={n} value={n}>{n}x{n > 1 ? " com juros" : " à vista"}</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>Vencimento</label>
                  <input className="input" type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} />
                </div>
              </div>
              <div>
                <label style={{ display: "block", fontSize: 11.5, fontWeight: 600, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", marginBottom: 8 }}>Métodos aceitos</label>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <PayToggle icon="pix" label="Pix" on={allowPix} onToggle={() => setAllowPix(v => !v)} sub={allowPix ? "Aprovado em segundos" : "Desativado"}/>
                  <PayToggle icon="card" label="Cartão de crédito" on={allowCard} onToggle={() => setAllowCard(v => !v)} sub={allowCard ? `Até ${installments}x` : "Desativado"}/>
                  <PayToggle icon="globe" label="Stripe — Internacional" on={allowStripe} onToggle={() => setAllowStripe(v => !v)} sub={allowStripe ? "USD / EUR / Apple Pay" : "Desativado"}/>
                  <div className="field" style={{ alignSelf: "end" }}>
                    <label style={{ fontSize: 10.5 }}>Gateway preferencial</label>
                    <select className="select" value={gateway} onChange={(e) => setGateway(e.target.value)}>
                      <option value="mp">Mercado Pago (BRL)</option>
                      <option value="stripe">Stripe (multi-moeda)</option>
                      <option value="auto">Auto — escolher por país</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div><h3>Order bumps</h3><div className="sub" style={{ color: "var(--mute)", fontSize: 12.5 }}>Aumente o ticket médio com ofertas extras</div></div>
              <button className="btn-icon" onClick={() => setRoute("/bumps")} aria-label="Gerenciar">
                <Icon name="set"/>
              </button>
            </div>
            <div style={{ padding: 20, display: "grid", gap: 10 }}>
              {bumps.filter(b => b.active).map((b) => {
                const on = bumpsOn.includes(b.id);
                return (
                  <label key={b.id} className={cls("bump", on && "on")}>
                    <span className="checkbox">
                      <input type="checkbox" checked={on}
                        onChange={() => setBumpsOn(arr => on ? arr.filter(x => x !== b.id) : [...arr, b.id])}/>
                      <span className="box"><Icon name="check" size={12}/></span>
                    </span>
                    <span className="info">
                      <b>{b.name}</b>
                      <span>{b.desc}</span>
                    </span>
                    <span className="price">{fmtBRL(b.price)}</span>
                  </label>
                );
              })}
              {bumps.filter(b => b.active).length === 0 && (
                <div className="empty">
                  <div className="ic"><Icon name="bolt"/></div>
                  <h4>Sem order bumps ativos</h4>
                  <span>Crie ofertas extras para somar ao valor total automaticamente.</span>
                </div>
              )}
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h3>Dados do cliente (opcional)</h3></div>
            <div style={{ padding: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <div className="field" style={{ gridColumn: "span 2" }}>
                <label>Nome do cliente</label>
                <input className="input" value={customerName} onChange={(e) => setCustomerName(e.target.value)} placeholder="Mariana Coelho"/>
              </div>
              <div className="field">
                <label>E-mail</label>
                <input className="input" type="email" value={customerEmail} onChange={(e) => setCustomerEmail(e.target.value)} placeholder="cliente@email.com"/>
              </div>
              <div className="field">
                <label>WhatsApp</label>
                <input className="input" value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)} placeholder="(21) 99999-0000"/>
              </div>
              <div className="field" style={{ gridColumn: "span 2" }}>
                <label>URL pós-compra</label>
                <input className="input mono" value={postUrl} onChange={(e) => setPostUrl(e.target.value)}/>
              </div>
              <div className="field">
                <label>Status do checkout</label>
                <select className="select" value={status} onChange={(e) => setStatus(e.target.value)}>
                  <option value="ativo">Ativo</option>
                  <option value="rascunho">Rascunho</option>
                  <option value="inativo">Inativo</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT: live preview + link generator */}
        <div style={{ position: "sticky", top: 88, alignSelf: "start", display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card card-pad-lg">
            <div style={{ fontSize: 11, letterSpacing: ".2em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>Resumo</div>
            <div style={{ fontSize: 30, fontWeight: 600, letterSpacing: "-0.02em", marginTop: 8, fontVariantNumeric: "tabular-nums" }}>{fmtBRL(total)}</div>
            <div style={{ color: "var(--mute)", fontSize: 13, marginTop: 4 }}>
              {bumpsOn.length > 0 ? `${bumpsOn.length} order bump${bumpsOn.length > 1 ? "s" : ""} incluído${bumpsOn.length > 1 ? "s" : ""}.` : "Sem order bumps."}
            </div>
            <div style={{ marginTop: 18, padding: "14px 16px", border: "1px solid var(--line)", borderRadius: 14, background: "var(--paper)" }}>
              <div style={{ fontWeight: 600 }}>{name}</div>
              <div style={{ fontSize: 12.5, color: "var(--mute)", marginTop: 2 }}>{desc}</div>
            </div>
            {bumpsOn.length > 0 && (
              <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 6 }}>
                {bumps.filter(b => bumpsOn.includes(b.id)).map(b => (
                  <div key={b.id} style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, color: "var(--mute)" }}>
                    <span>+ {b.name}</span><span>{fmtBRL(b.price)}</span>
                  </div>
                ))}
              </div>
            )}
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line)" }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                {allowPix && <span className="tag"><Icon name="pix" size={12}/> Pix</span>}
                {allowCard && <span className="tag"><Icon name="card" size={12}/> Cartão {installments > 1 ? `${installments}x` : "à vista"}</span>}
                {allowStripe && <span className="tag"><Icon name="globe" size={12}/> Stripe</span>}
                <span className="tag"><Icon name="calendar" size={12}/> Vence {fmtDate(dueDate)}</span>
              </div>
              <div style={{ marginTop: 8, fontSize: 11.5, color: "var(--graphite)", letterSpacing: ".14em", textTransform: "uppercase", fontWeight: 600 }}>
                via {gateway === "mp" ? "Mercado Pago" : gateway === "stripe" ? "Stripe" : "auto (mp/stripe)"}
              </div>
            </div>

            <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 8 }}>
              <button className="btn btn-lg btn-block" onClick={generate} disabled={generating}>
                {generating ? "Gerando link…" : <><Icon name="link" size={16}/> Gerar link de pagamento</>}
              </button>
              <button className="btn btn-light btn-block" onClick={previewCustomer}>
                <Icon name="eye" size={16}/> Pré-visualizar como cliente
              </button>
            </div>
          </div>

          {/* Generated link surface */}
          <div className="card card-pad-lg" style={{
            background: generated ? "var(--ink)" : "#fff",
            color: generated ? "#fff" : undefined,
            transition: "all .35s var(--ease)",
          }}>
            <div style={{
              fontSize: 11, letterSpacing: ".2em", textTransform: "uppercase",
              color: generated ? "rgba(255,255,255,.55)" : "var(--mute)", fontWeight: 600,
            }}>
              {generating ? "Aguardando" : (generated ? "Link gerado" : "Quando estiver pronto")}
            </div>

            {generating && (
              <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
                <div className="skeleton" style={{ height: 16, width: "70%" }}></div>
                <div className="skeleton" style={{ height: 12, width: "90%" }}></div>
                <div className="skeleton" style={{ height: 40, width: "100%", marginTop: 8 }}></div>
              </div>
            )}

            {!generating && !generated && (
              <div style={{ marginTop: 10, fontSize: 13.5, color: "var(--mute)" }}>
                O link, o QR Code Pix e o botão de WhatsApp aparecerão aqui assim que você gerar a cobrança.
              </div>
            )}

            {generated && (
              <div className="in" style={{ marginTop: 12 }}>
                <div style={{
                  background: "rgba(255,255,255,.06)",
                  border: "1px solid rgba(255,255,255,.12)",
                  borderRadius: 14,
                  padding: "12px 14px",
                  fontFamily: "'JetBrains Mono', ui-monospace, monospace",
                  fontSize: 12.5,
                  wordBreak: "break-all",
                }}>{generated.url}</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 10 }}>
                  <button className="btn btn-light btn-sm" onClick={copyLink}>
                    <Icon name="copy" size={14}/> Copiar
                  </button>
                  <button className="btn btn-light btn-sm" onClick={sendWA}>
                    <Icon name="wa" size={14}/> WhatsApp
                  </button>
                  <button className="btn btn-light btn-sm" onClick={() => setModal({
                    title: "QR Code Pix",
                    sub: "O cliente também pode pagar escaneando o código abaixo.",
                    body: (
                      <div style={{ display: "grid", placeItems: "center", padding: "12px 0" }}>
                        <FakeQR seed={generated.id}/>
                        <div style={{ marginTop: 14, fontSize: 12.5, color: "var(--mute)" }}>
                          Vence em 24h · {fmtBRL(total)}
                        </div>
                      </div>
                    ),
                    foot: <button className="btn" onClick={() => setModal(null)}>Fechar</button>
                  })}>
                    <Icon name="qr" size={14}/> QR Pix
                  </button>
                </div>
                <button className="btn btn-block" style={{ marginTop: 10 }} onClick={previewCustomer}>
                  Abrir como cliente <span className="arrow">→</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </Shell>
  );
}

function PayToggle({ icon, label, on, onToggle, sub }){
  return (
    <button onClick={onToggle} className={cls("method", on && "active")} style={{ width: "100%" }} type="button">
      <span className="ic"><Icon name={icon} size={18}/></span>
      <span className="row">
        <span className="name">{label}</span>
        <span style={{ fontSize: 12, color: "var(--mute)" }}>{sub || (on ? "Aceito" : "Desativado")}</span>
      </span>
      <span style={{ marginLeft: "auto" }}>
        <label className="switch" onClick={(e) => e.stopPropagation()}>
          <input type="checkbox" checked={on} onChange={onToggle}/>
          <span className="track"></span><span className="knob"></span>
        </label>
      </span>
    </button>
  );
}

// ============================================================
// Products CRUD
// ============================================================
function Products(){
  const { products, setProducts, setModal, pushToast, setRoute } = useApp();

  const openEditor = (p = null) => {
    setModal({
      title: p ? "Editar produto" : "Novo produto",
      sub: p ? "Atualize os dados desta oferta" : "Crie uma nova oferta para reutilizar nos checkouts",
      body: <ProductForm initial={p} onSave={(data) => {
        if (p) setProducts(arr => arr.map(x => x.id === p.id ? { ...x, ...data } : x));
        else setProducts(arr => [{ id: uid(), sales: 0, ...data }, ...arr]);
        setModal(null);
        pushToast(p ? "Produto atualizado." : "Produto criado.");
      }} onCancel={() => setModal(null)}/>,
    });
  };

  const dupe = (p) => {
    setProducts(arr => [{ ...p, id: uid(), name: p.name + " — cópia", sales: 0 }, ...arr]);
    pushToast("Produto duplicado.");
  };
  const del = (p) => {
    setModal({
      title: "Excluir produto?",
      sub: `Tem certeza que deseja remover "${p.name}"? Esta ação não pode ser desfeita.`,
      body: null,
      foot: <>
        <button className="btn btn-light" onClick={() => setModal(null)}>Cancelar</button>
        <button className="btn" style={{ background: "var(--bad)", borderColor: "var(--bad)" }}
          onClick={() => { setProducts(arr => arr.filter(x => x.id !== p.id)); setModal(null); pushToast("Produto removido.", "bad"); }}>
          Excluir
        </button>
      </>,
    });
  };
  const toggleActive = (p) => setProducts(arr => arr.map(x => x.id === p.id ? { ...x, active: !x.active } : x));

  return (
    <Shell page="products" eyebrow="Catálogo" title="Produtos"
      actions={<button className="btn" onClick={() => openEditor()}><Icon name="plus" size={16}/> Novo produto</button>}>

      <div className="card">
        <div className="card-head">
          <h3>{products.length} produto{products.length !== 1 ? "s" : ""}</h3>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn btn-light btn-sm" onClick={() => setRoute("/checkouts")}>Criar checkout</button>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>Produto</th>
              <th className="num">Valor</th>
              <th className="num">Vendas</th>
              <th>Status</th>
              <th style={{ width: 1 }}></th>
            </tr>
          </thead>
          <tbody>
            {products.map((p) => (
              <tr key={p.id} className="row-hover">
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div className="thumb">
                      {p.image
                        ? <img src={p.image} alt=""/>
                        : <Icon name="tag" size={16}/>}
                    </div>
                    <div>
                      <div style={{ fontWeight: 600 }}>{p.name}</div>
                      <div style={{ fontSize: 12.5, color: "var(--mute)" }}>{p.desc}</div>
                    </div>
                  </div>
                </td>
                <td className="num"><b>{fmtBRL(p.price)}</b></td>
                <td className="num">{p.sales}</td>
                <td><StatusBadge status={p.active ? "ativo" : "inativo"}/></td>
                <td>
                  <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                    <label className="switch" title="Ativar/desativar" style={{ marginRight: 6 }}>
                      <input type="checkbox" checked={p.active} onChange={() => toggleActive(p)}/>
                      <span className="track"></span><span className="knob"></span>
                    </label>
                    <button className="btn-icon" onClick={() => openEditor(p)} aria-label="Editar"><Icon name="edit"/></button>
                    <button className="btn-icon" onClick={() => dupe(p)} aria-label="Duplicar"><Icon name="dup"/></button>
                    <button className="btn-icon" onClick={() => del(p)} aria-label="Excluir"><Icon name="trash"/></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Shell>
  );
}

function ProductForm({ initial, onSave, onCancel }){
  const [d, setD] = React.useState(initial || { name: "", desc: "", price: 0, active: true, image: null });
  return (
    <div style={{ display: "grid", gap: 12 }}>
      <ImageDropper value={d.image} onChange={(img) => setD({...d, image: img})}
        label="Imagem do pacote" hint="Imagem do produto · proporção 4:3"/>
      <div className="field"><label>Nome</label>
        <input className="input" value={d.name} onChange={(e) => setD({...d, name: e.target.value})}/></div>
      <div className="field"><label>Descrição</label>
        <textarea className="textarea" value={d.desc} onChange={(e) => setD({...d, desc: e.target.value})}/></div>
      <div className="field"><label>Valor</label>
        <div className="input-prefix"><span className="pfx">R$</span>
          <input className="input" type="number" value={d.price} onChange={(e) => setD({...d, price: Number(e.target.value)})}/>
        </div>
      </div>
      <label className="checkbox">
        <input type="checkbox" checked={d.active} onChange={(e) => setD({...d, active: e.target.checked})}/>
        <span className="box"><Icon name="check" size={12}/></span>
        Ativo (disponível para checkouts)
      </label>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6 }}>
        <button className="btn btn-light" onClick={onCancel}>Cancelar</button>
        <button className="btn btn-liquid-dark" onClick={() => onSave(d)} disabled={!d.name || d.price <= 0}>Salvar</button>
      </div>
    </div>
  );
}

// ============================================================
// Order Bumps CRUD
// ============================================================
function Bumps(){
  const { bumps, setBumps, setModal, pushToast } = useApp();

  const openEditor = (b = null) => {
    setModal({
      title: b ? "Editar order bump" : "Novo order bump",
      sub: b ? "Atualize os dados desta oferta" : "Crie uma oferta extra para somar ao valor total",
      body: <BumpForm initial={b} onSave={(data) => {
        if (b) setBumps(arr => arr.map(x => x.id === b.id ? { ...x, ...data } : x));
        else setBumps(arr => [{ id: uid(), ...data }, ...arr]);
        setModal(null);
        pushToast(b ? "Order bump atualizado." : "Order bump criado.");
      }} onCancel={() => setModal(null)}/>,
    });
  };
  const del = (b) => {
    setBumps(arr => arr.filter(x => x.id !== b.id));
    pushToast("Order bump removido.", "bad");
  };
  const toggle = (b) => setBumps(arr => arr.map(x => x.id === b.id ? { ...x, active: !x.active } : x));

  return (
    <Shell page="bumps" eyebrow="Catálogo" title="Order bumps"
      actions={<button className="btn" onClick={() => openEditor()}><Icon name="plus" size={16}/> Novo order bump</button>}>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
        {bumps.map((b) => (
          <div key={b.id} className="card card-pad" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--ink)", color: "#fff", display: "grid", placeItems: "center" }}>
                <Icon name="bolt" size={18}/>
              </div>
              <label className="switch">
                <input type="checkbox" checked={b.active} onChange={() => toggle(b)}/>
                <span className="track"></span><span className="knob"></span>
              </label>
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 16, letterSpacing: "-0.01em" }}>{b.name}</div>
              <div style={{ color: "var(--mute)", fontSize: 13, marginTop: 4 }}>{b.desc}</div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 12, borderTop: "1px solid var(--line)" }}>
              <div style={{ fontVariantNumeric: "tabular-nums", fontWeight: 700, fontSize: 18 }}>{fmtBRL(b.price)}</div>
              <div style={{ display: "flex", gap: 4 }}>
                <button className="btn-icon" onClick={() => openEditor(b)}><Icon name="edit"/></button>
                <button className="btn-icon" onClick={() => del(b)}><Icon name="trash"/></button>
              </div>
            </div>
            <StatusBadge status={b.active ? "ativo" : "inativo"}/>
          </div>
        ))}
        <button className="card card-pad" onClick={() => openEditor()}
          style={{ display: "grid", placeItems: "center", border: "1.5px dashed var(--line-strong)", background: "transparent",
            minHeight: 200, gap: 10, cursor: "pointer", color: "var(--mute)", transition: "border-color .35s var(--ease), color .35s var(--ease)" }}
          onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--ink)"; e.currentTarget.style.color = "var(--ink)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--mute)"; }}>
          <div style={{ width: 44, height: 44, borderRadius: 14, background: "var(--paper)", display: "grid", placeItems: "center" }}>
            <Icon name="plus"/>
          </div>
          <div style={{ fontWeight: 600 }}>Adicionar order bump</div>
        </button>
      </div>
    </Shell>
  );
}

function BumpForm({ initial, onSave, onCancel }){
  const [d, setD] = React.useState(initial || { name: "", desc: "", price: 0, active: true, image: null });
  return (
    <div style={{ display: "grid", gap: 12 }}>
      <ImageDropper value={d.image} onChange={(img) => setD({...d, image: img})}
        label="Imagem do order bump" hint="Mostrada no checkout · proporção 4:3"/>
      <div className="field"><label>Nome</label>
        <input className="input" value={d.name} onChange={(e) => setD({...d, name: e.target.value})}/></div>
      <div className="field"><label>Descrição</label>
        <textarea className="textarea" value={d.desc} onChange={(e) => setD({...d, desc: e.target.value})}/></div>
      <div className="field"><label>Valor</label>
        <div className="input-prefix"><span className="pfx">R$</span>
          <input className="input" type="number" value={d.price} onChange={(e) => setD({...d, price: Number(e.target.value)})}/>
        </div>
      </div>
      <label className="checkbox">
        <input type="checkbox" checked={d.active} onChange={(e) => setD({...d, active: e.target.checked})}/>
        <span className="box"><Icon name="check" size={12}/></span>
        Ativo (disponível nos checkouts)
      </label>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 6 }}>
        <button className="btn btn-light" onClick={onCancel}>Cancelar</button>
        <button className="btn btn-liquid-dark" onClick={() => onSave(d)} disabled={!d.name || d.price <= 0}>Salvar</button>
      </div>
    </div>
  );
}

Object.assign(window, { CreateCheckout, Products, Bumps });
