/* ============================================================
   payment.jsx — Customer-facing checkout + Thank You page
   ============================================================ */

function CustomerPay(){
  const { bumps, setRoute, pushToast, stripeEnabled, pixel, webhooks } = useApp();

  // Helper — fires every active custom webhook for a given event name
  const fireHooks = (event, payload) => {
    if (!window.__pagblackx) return;
    webhooks.filter(w => w.active && !w.system && w.event === event)
      .forEach(w => window.__pagblackx.fireWebhook(w.url, { event, ...payload }));
  };

  // Mocked order coming from the checkout creator
  const order = {
    title: "Identidade Visual — Pacote Prime",
    desc: "Logotipo, paleta, tipografia, papelaria e brand book",
    price: 5990,
  };
  const availableBumps = bumps.filter(b => b.active).slice(0, 3);

  const [method, setMethod] = React.useState("pix"); // pix | card
  const [installments, setInstallments] = React.useState(1);
  const [bumpsOn, setBumpsOn] = React.useState([]);
  const [coupon, setCoupon] = React.useState("");
  const [couponApplied, setCouponApplied] = React.useState(null);

  const [form, setForm] = React.useState({
    name: "", email: "", phone: "", cpf: "",
    cardNumber: "", cardName: "", cardExp: "", cardCvv: "",
  });
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const [paying, setPaying] = React.useState(false);
  const [view, setView] = React.useState("form"); // form | pix-wait | done
  const [error, setError] = React.useState(null);
  const [pixExpired, setPixExpired] = React.useState(false);
  const [pixCountdown, setPixCountdown] = React.useState(900); // 15 min

  // If admin disables Stripe mid-flow, fall back to Pix.
  React.useEffect(() => {
    if (!stripeEnabled && method === "stripe") setMethod("pix");
  }, [stripeEnabled, method]);

  // Fire Pixel InitiateCheckout + checkout.criado webhook once when the page mounts.
  React.useEffect(() => {
    if (pixel?.enabled && pixel?.fbPixelId && pixel?.trackInitiate && window.__pagblackx){
      window.__pagblackx.trackPixel("InitiateCheckout", {
        value: order.price, currency: "BRL", content_name: order.title,
      });
    }
    fireHooks("checkout.criado", {
      product: order.title, value: order.price, currency: "BRL",
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  React.useEffect(() => {
    if (view !== "pix-wait" || pixExpired) return;
    const t = setInterval(() => {
      setPixCountdown(c => {
        if (c <= 1) { setPixExpired(true); return 0; }
        return c - 1;
      });
    }, 1000);
    return () => clearInterval(t);
  }, [view, pixExpired]);

  const subtotal = order.price + bumps.filter(b => bumpsOn.includes(b.id)).reduce((a, b) => a + b.price, 0);
  const discount = couponApplied ? Math.round(subtotal * couponApplied.pct) : 0;
  const total = subtotal - discount;

  const applyCoupon = () => {
    const code = coupon.trim().toUpperCase();
    if (!code) return;
    if (code === "BLACKX10") setCouponApplied({ code, pct: 0.10 });
    else if (code === "STUDIO5") setCouponApplied({ code, pct: 0.05 });
    else { setError({ type: "coupon", msg: "Cupom inválido ou expirado." }); return; }
    setError(null);
    pushToast("Cupom aplicado.");
  };
  const removeCoupon = () => { setCouponApplied(null); setCoupon(""); };

  const validateForm = () => {
    if (!form.name.trim()) return "Informe seu nome completo.";
    if (!form.email.includes("@")) return "E-mail inválido.";
    if (!form.cpf.replace(/\D/g, "").length) return "Informe seu CPF.";
    if (method === "card" || method === "stripe"){
      if (form.cardNumber.replace(/\s/g, "").length < 12) return "Número de cartão inválido.";
      if (!form.cardName) return "Informe o nome no cartão.";
      if (!form.cardExp.match(/^\d{2}\/\d{2}$/)) return "Validade no formato MM/AA.";
      if (form.cardCvv.length < 3) return "CVV inválido.";
    }
    return null;
  };

  // Centraliza disparos de tracking + redirecionamento ao aprovar/recusar.
  const onApproved = (extra = {}) => {
    if (pixel?.enabled && pixel?.fbPixelId && pixel?.trackPurchase && window.__pagblackx){
      window.__pagblackx.trackPixel("Purchase", { value: total, currency: "BRL", content_name: order.title, ...extra });
    }
    fireHooks("pagamento.aprovado", { method, value: total, currency: "BRL", product: order.title, ...extra });
    setView("done");
    pushToast("Pagamento aprovado.");
    setTimeout(() => setRoute("/obrigado"), 700);
  };
  const onDeclined = (reason) => {
    fireHooks("pagamento.recusado", { method, value: total, reason });
  };

  const pay = () => {
    setError(null);
    const v = validateForm();
    if (v){ setError({ type: "form", msg: v }); return; }
    setPaying(true);
    setTimeout(() => {
      setPaying(false);
      if (method === "pix"){
        setView("pix-wait");
        return;
      }
      // Card / Stripe: simulate occasional decline if number ends in 0
      if (form.cardNumber.replace(/\s/g, "").endsWith("0")){
        const msg = method === "stripe"
          ? "Cartão recusado pela Stripe. Tente outro cartão ou pague com Pix."
          : "Cartão recusado pelo emissor. Tente outro cartão ou pague com Pix.";
        setError({ type: "decline", msg });
        onDeclined(msg);
        return;
      }
      onApproved({ installments });
    }, 1400);
  };

  const fakePixApprove = () => onApproved({ method: "pix" });

  // When the Pix expires, notify webhooks.
  React.useEffect(() => {
    if (pixExpired) fireHooks("pix.expirado", { value: total });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pixExpired]);
  const renewPix = () => {
    setPixExpired(false); setPixCountdown(900);
  };
  const mm = String(Math.floor(pixCountdown / 60)).padStart(2, "0");
  const ss = String(pixCountdown % 60).padStart(2, "0");

  return (
    <div className="pay-shell">
      <div className="pay-bar">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <BrandLogo theme="dark" height={22} />
        </div>
        <div className="secure">
          <Icon name="lock" size={14}/> Ambiente seguro · pagamento criptografado
        </div>
      </div>

      <div className="pay-wrap">
        {/* LEFT — form */}
        <div className="pay-card card-pad-lg in">
          {view === "form" && <>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 18 }}>
              <h2>Finalizar <em className="serif-em">pagamento</em></h2>
              <span className="tag"><Icon name="shield" size={12}/> Ambiente seguro</span>
            </div>

            {/* Method picker */}
            <div className="method-tabs" style={{ gridTemplateColumns: stripeEnabled ? "repeat(3, 1fr)" : "1fr 1fr" }}>
              <div className={cls("method", method === "pix" && "active")} onClick={() => setMethod("pix")}>
                <div className="ic"><Icon name="pix" size={18}/></div>
                <div className="row">
                  <div className="name">Pix</div>
                  <div style={{ fontSize: 12, color: "var(--mute)" }}>Aprovado em segundos</div>
                </div>
                <span className="tag badge-ok" style={{ marginLeft: "auto" }}>5% OFF</span>
              </div>
              <div className={cls("method", method === "card" && "active")} onClick={() => setMethod("card")}>
                <div className="ic"><Icon name="card" size={18}/></div>
                <div className="row">
                  <div className="name">Cartão de crédito</div>
                  <div style={{ fontSize: 12, color: "var(--mute)" }}>Até 12x</div>
                </div>
              </div>
              {stripeEnabled && (
                <div className={cls("method", method === "stripe" && "active")} onClick={() => setMethod("stripe")}>
                  <div className="ic"><Icon name="globe" size={18}/></div>
                  <div className="row">
                    <div className="name">Internacional</div>
                    <div style={{ fontSize: 12, color: "var(--mute)" }}>USD / EUR · Apple Pay</div>
                  </div>
                </div>
              )}
            </div>

            {/* Personal data */}
            <div style={{ display: "grid", gap: 12, marginTop: 22 }}>
              <h3 style={{ fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", margin: 0 }}>Seus dados</h3>
              <div className="field"><label>Nome completo</label>
                <input className="input" value={form.name} onChange={set("name")} placeholder="Como aparece no documento"/>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <div className="field"><label>E-mail</label>
                  <input className="input" type="email" value={form.email} onChange={set("email")} placeholder="seu@email.com"/></div>
                <div className="field"><label>WhatsApp</label>
                  <input className="input" value={form.phone} onChange={set("phone")} placeholder="(21) 99999-0000"/></div>
              </div>
              <div className="field"><label>CPF / CNPJ</label>
                <input className="input" value={form.cpf} onChange={set("cpf")} placeholder="000.000.000-00"/></div>
            </div>

            {/* Method specific */}
            {(method === "card" || method === "stripe") && (
              <div style={{ display: "grid", gap: 12, marginTop: 22 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                  <h3 style={{ fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", margin: 0 }}>
                    Dados do cartão
                  </h3>
                  {method === "stripe" && (
                    <span className="tag"><Icon name="globe" size={12}/> via Stripe</span>
                  )}
                </div>

                {method === "stripe" && (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    <button type="button" className="btn"
                      style={{ background: "#000", borderColor: "#000" }}
                      onClick={() => { pushToast("Solicitando Apple Pay…"); setTimeout(() => onApproved({ wallet: "apple_pay" }), 900); }}>
                      <svg width="14" height="16" viewBox="0 0 16 18" fill="currentColor" aria-hidden="true">
                        <path d="M11.6 9.5c0-2 1.6-3 1.7-3-1-1.4-2.4-1.6-2.9-1.6-1.3-.1-2.5.7-3.1.7-.7 0-1.6-.7-2.7-.7-1.4 0-2.7.8-3.4 2-1.5 2.5-.4 6.3 1 8.4.7 1 1.6 2.1 2.7 2.1 1 0 1.4-.7 2.7-.7 1.3 0 1.7.7 2.7.7 1.1 0 1.9-1 2.6-2 .8-1.2 1.1-2.3 1.1-2.4 0 0-2.1-.8-2.1-3.5zM9.6 3.4c.6-.7 1-1.7.9-2.6-.8 0-1.8.5-2.4 1.2-.5.6-1 1.6-.9 2.5.9.1 1.8-.4 2.4-1.1z"/>
                      </svg>
                      Pay
                    </button>
                    <button type="button" className="btn btn-light"
                      onClick={() => { pushToast("Solicitando Google Pay…"); setTimeout(() => onApproved({ wallet: "google_pay" }), 900); }}>
                      <Icon name="globe" size={14}/> Google Pay
                    </button>
                    <div style={{ gridColumn: "span 2", display: "flex", alignItems: "center", gap: 10, color: "var(--graphite)", fontSize: 11.5, letterSpacing: ".14em", textTransform: "uppercase" }}>
                      <span style={{ flex: 1, height: 1, background: "var(--line)" }}></span>
                      ou pague com cartão
                      <span style={{ flex: 1, height: 1, background: "var(--line)" }}></span>
                    </div>
                  </div>
                )}

                <div className="field"><label>Número do cartão</label>
                  <input className="input mono" value={form.cardNumber} onChange={set("cardNumber")} placeholder="0000 0000 0000 0000"/></div>
                <div className="field"><label>Nome impresso no cartão</label>
                  <input className="input" value={form.cardName} onChange={set("cardName")} placeholder="NOME COMO ESTÁ NO CARTÃO"/></div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div className="field"><label>Validade</label>
                    <input className="input mono" value={form.cardExp} onChange={set("cardExp")} placeholder="MM/AA"/></div>
                  <div className="field"><label>CVV</label>
                    <input className="input mono" value={form.cardCvv} onChange={set("cardCvv")} placeholder="000"/></div>
                </div>
                {method === "card" && (
                  <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 de {fmtBRL(total / n)}{n === 1 ? " à vista" : " com juros"}</option>
                      ))}
                    </select>
                  </div>
                )}
                {method === "stripe" && (
                  <div className="hint" style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mute)", fontSize: 12.5 }}>
                    <Icon name="shield" size={14}/> Stripe processa em USD/EUR · 3-D Secure ativo
                  </div>
                )}
              </div>
            )}

            {/* Order bumps */}
            {availableBumps.length > 0 && (
              <div style={{ marginTop: 22 }}>
                <h3 style={{ fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", margin: "0 0 10px" }}>Adicione com desconto</h3>
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {availableBumps.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>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Coupon */}
            <div style={{ marginTop: 22 }}>
              <h3 style={{ fontSize: 13, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", margin: "0 0 10px" }}>Cupom de desconto</h3>
              {couponApplied ? (
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                  padding: 14, border: "1px solid var(--ok)", background: "var(--ok-soft)", borderRadius: 12 }}>
                  <div>
                    <b className="mono" style={{ fontSize: 13 }}>{couponApplied.code}</b>
                    <span style={{ fontSize: 13, color: "var(--mute)", marginLeft: 8 }}>
                      ({Math.round(couponApplied.pct * 100)}% OFF aplicado)
                    </span>
                  </div>
                  <button className="btn-icon" onClick={removeCoupon}><Icon name="x" size={14}/></button>
                </div>
              ) : (
                <div style={{ display: "flex", gap: 8 }}>
                  <input className="input mono" value={coupon} onChange={(e) => setCoupon(e.target.value)} placeholder="Digite seu cupom" />
                  <button className="btn btn-light" onClick={applyCoupon}>Aplicar</button>
                </div>
              )}
              {error?.type === "coupon" && (
                <div style={{ marginTop: 8, color: "var(--bad)", fontSize: 13 }}>{error.msg}</div>
              )}
              <div className="hint" style={{ marginTop: 6, fontSize: 12, color: "var(--graphite)" }}>
                Experimente <span className="mono">BLACKX10</span> ou <span className="mono">STUDIO5</span>.
              </div>
            </div>

            {/* Inline errors */}
            {error && error.type !== "coupon" && (
              <div style={{ marginTop: 18, padding: "14px 16px",
                background: "var(--bad-soft)", border: "1px solid rgba(163,34,28,.2)", borderRadius: 14,
                color: "var(--bad)", display: "flex", alignItems: "flex-start", gap: 10 }}>
                <Icon name="bell" size={16}/>
                <div>
                  <b>{error.type === "decline" ? "Pagamento recusado" : "Erro temporário"}</b>
                  <div style={{ fontSize: 13.5, marginTop: 2 }}>{error.msg}</div>
                </div>
              </div>
            )}

            <button className="btn btn-lg btn-block" style={{ marginTop: 22 }} onClick={pay} disabled={paying}>
              {paying ? "Processando…" : <>
                <Icon name="lock" size={14}/> Finalizar pagamento · {fmtBRL(total)}
              </>}
            </button>
            <div style={{ marginTop: 12, fontSize: 12, color: "var(--graphite)", textAlign: "center" }}>
              Ao continuar você concorda com os <a href="#" style={{ textDecoration: "underline" }}>termos</a> e a <a href="#" style={{ textDecoration: "underline" }}>política de privacidade</a>.
            </div>
          </>}

          {view === "pix-wait" && (
            <div className="in">
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 18 }}>
                <h2>Pague com <em className="serif-em">Pix</em></h2>
                <span className="tag"><Icon name="pix" size={12}/> Aguardando pagamento</span>
              </div>

              {!pixExpired ? <>
                <div className="pix-box">
                  <FakeQR seed={"order-" + total}/>
                  <div style={{ fontSize: 13, color: "var(--mute)", textAlign: "center" }}>
                    Abra o app do seu banco, escolha pagar com Pix por QR Code e escaneie a imagem abaixo. Ou copie o código.
                  </div>
                  <div className="pix-code">
                    00020126770014BR.GOV.BCB.PIX2555api.mercadopago.com/instore/o/v2/qr/{uid()}{uid()}5204000053039865406{total.toFixed(2)}5802BR5916BLACKX STUDIO LT6009SAO PAULO62070503***6304B7A2
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, width: "100%" }}>
                    <button className="btn btn-light" onClick={() => { navigator.clipboard?.writeText("pix-copia-cola"); pushToast("Código Pix copiado."); }}>
                      <Icon name="copy" size={14}/> Copiar código
                    </button>
                    <button className="btn" onClick={fakePixApprove}>
                      Já paguei <span className="arrow">→</span>
                    </button>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--mute)", fontSize: 13 }}>
                    <Icon name="bell" size={14}/> Expira em <b className="mono">{mm}:{ss}</b>
                  </div>
                </div>
              </> : <>
                <div style={{ padding: "20px 16px",
                  background: "var(--bad-soft)", border: "1px solid rgba(163,34,28,.2)", borderRadius: 14,
                  color: "var(--bad)", display: "flex", alignItems: "flex-start", gap: 12 }}>
                  <Icon name="bell" size={18}/>
                  <div>
                    <b>Pix expirado</b>
                    <div style={{ fontSize: 13.5, marginTop: 2 }}>
                      Seu código Pix expirou. Gere um novo para continuar com o pagamento ou troque o método.
                    </div>
                    <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
                      <button className="btn btn-light btn-sm" onClick={renewPix}>Gerar novo Pix</button>
                      <button className="btn btn-soft btn-sm" onClick={() => { setView("form"); setMethod("card"); setError(null); }}>Pagar com cartão</button>
                    </div>
                  </div>
                </div>
              </>}
            </div>
          )}
        </div>

        {/* RIGHT — order summary */}
        <div className="pay-card card-pad-lg pay-summary">
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <h2 style={{ fontSize: 16, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>Seu pedido</h2>
            <span className="badge-silver" style={{ display: "inline-block" }}>Premium</span>
          </div>

          <div className="sum-item" style={{ marginTop: 8 }}>
            <div className="ph">BX</div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span className="name">{order.title}</span>
              <span className="sub">{order.desc}</span>
            </div>
            <span className="price">{fmtBRL(order.price)}</span>
          </div>

          {bumps.filter(b => bumpsOn.includes(b.id)).map(b => (
            <div key={b.id} className="sum-item">
              <div className="ph" style={{ background: "linear-gradient(135deg, var(--ink-2), var(--ink))", color: "#fff" }}>+</div>
              <div style={{ display: "flex", flexDirection: "column" }}>
                <span className="name">{b.name}</span>
                <span className="sub">{b.desc}</span>
              </div>
              <span className="price">{fmtBRL(b.price)}</span>
            </div>
          ))}

          <div className="sum-totals">
            <div className="sum-row"><span>Subtotal</span><span>{fmtBRL(subtotal)}</span></div>
            {couponApplied && <div className="sum-row" style={{ color: "var(--ok)" }}>
              <span>Cupom {couponApplied.code}</span><span>− {fmtBRL(discount)}</span>
            </div>}
            <div className="sum-row"><span>Método</span><span>
              {method === "pix" ? "Pix"
                : method === "card" ? `Cartão de crédito ${installments > 1 ? `${installments}x` : "à vista"}`
                : "Cartão internacional"}
            </span></div>
            <div className="sum-row big"><span>Total</span><span>{fmtBRL(total)}</span></div>
          </div>

          <div style={{
            marginTop: 18, padding: 14,
            borderRadius: 14, border: "1px solid var(--line)", background: "var(--paper)",
            display: "flex", gap: 10, alignItems: "flex-start",
          }}>
            <Icon name="shield" size={16} style={{ marginTop: 1 }}/>
            <div style={{ fontSize: 12.5, color: "var(--mute)", lineHeight: 1.55 }}>
              Ambiente seguro · seus dados são criptografados ponta a ponta. Não armazenamos números de cartão.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Thank You page
// ============================================================
function ThankYou(){
  const { setRoute } = useApp();
  return (
    <div className="pay-shell">
      <div className="pay-bar">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <BrandLogo theme="dark" height={22} />
        </div>
        <button className="btn-icon" onClick={() => setRoute("/dashboard")} aria-label="Painel"><Icon name="x"/></button>
      </div>

      <div style={{ maxWidth: 720, margin: "0 auto", padding: "60px 28px 80px" }}>
        <div className="card card-pad-lg in" style={{
          textAlign: "center", padding: "56px 40px",
          background: "linear-gradient(180deg, #fff, var(--paper))",
        }}>
          <div style={{
            width: 72, height: 72, borderRadius: 22, margin: "0 auto 22px",
            background: "var(--ink)", color: "#fff",
            display: "grid", placeItems: "center",
            boxShadow: "0 22px 44px -22px rgba(0,0,0,.55)",
          }}>
            <Icon name="check" size={32}/>
          </div>

          <div style={{ display: "grid", placeItems: "center", marginBottom: 18 }}>
            <img src="assets/blackx-logo-dark.png" alt="BlackX"
              style={{ height: 18, width: "auto", opacity: .85 }} />
          </div>

          <div style={{ fontSize: 11.5, letterSpacing: ".22em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>
            Pagamento confirmado
          </div>
          <h1 style={{ fontWeight: 600, fontSize: "clamp(34px,4.5vw,52px)", letterSpacing: "-0.035em", margin: "10px 0 12px", lineHeight: 1.05 }}>
            Bem-vindo à <em className="serif-em">BlackX.</em>
          </h1>
          <p style={{ color: "var(--mute)", maxWidth: 46, margin: "0 auto", fontSize: 15, maxWidth: "46ch" }}>
            Recebemos seu pagamento. Em instantes você recebe no e-mail e no WhatsApp todos os próximos passos do seu projeto.
          </p>

          <div style={{
            margin: "32px auto 0", maxWidth: 420,
            display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0,
            border: "1px solid var(--line)", borderRadius: 16, overflow: "hidden",
          }}>
            <DetailCell label="Pedido" value="ORD-7842"/>
            <DetailCell label="Total" value={fmtBRL(5990)}/>
            <DetailCell label="Método" value="Pix" border/>
            <DetailCell label="Confirmado" value="agora" border/>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, maxWidth: 420, margin: "26px auto 0" }}>
            <a className="btn" href="https://wa.me/55" target="_blank" rel="noopener" style={{ background: "var(--ok)", borderColor: "var(--ok)" }}>
              <Icon name="wa" size={16}/> Falar no WhatsApp
            </a>
            <button className="btn btn-light">
              <Icon name="arrow" size={14}/> Acessar produto
            </button>
          </div>

          <div style={{ marginTop: 24, fontSize: 12.5, color: "var(--graphite)" }}>
            Um recibo foi enviado para o seu e-mail. Guarde o código do pedido para referência futura.
          </div>
        </div>

        <div style={{ textAlign: "center", marginTop: 22 }}>
          <a href="#/dashboard" onClick={(e) => { e.preventDefault(); setRoute("/dashboard"); }}
            style={{ color: "var(--mute)", fontSize: 13, textDecoration: "underline" }}>
            Voltar ao painel admin
          </a>
        </div>
      </div>
    </div>
  );
}

function DetailCell({ label, value, border }){
  return (
    <div style={{
      padding: 16, textAlign: "left",
      borderTop: border ? "1px solid var(--line)" : 0,
      borderLeft: label === "Total" || label === "Confirmado" ? "1px solid var(--line)" : 0,
    }}>
      <div style={{ fontSize: 10.5, letterSpacing: ".2em", textTransform: "uppercase", color: "var(--mute)", fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em", marginTop: 4 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { CustomerPay, ThankYou });
