/* GayCard — Checkout flow */
const { useState, useEffect, useRef, useMemo } = React;

const BRL = { fisico: "29,90", digital: "19,90" };
const PLAN_LABEL = { fisico: "Cartão Físico", digital: "Cartão Digital" };

function param(name) {
  return new URLSearchParams(location.search).get(name);
}

function Progress({ idx, total }) {
  const pct = Math.round((idx / (total - 1)) * 100);
  return (
    <div style={{ height: 6, background: "#eee5d4", borderRadius: 999, overflow: "hidden" }}>
      <div style={{ height: "100%", width: pct + "%", background: "var(--rainbow)", transition: "width .4s cubic-bezier(.25,.4,.25,1)" }} />
    </div>
  );
}

function StepHead({ kicker, title, sub }) {
  return (
    <div style={{ marginBottom: 26 }}>
      <div className="eyebrow" style={{ color: "var(--purple)", marginBottom: 10 }}>{kicker}</div>
      <h2 className="display" style={{ fontSize: "clamp(1.7rem,3.4vw,2.4rem)", margin: 0 }}>{title}</h2>
      {sub && <p style={{ color: "var(--ink-70)", marginTop: 10, fontWeight: 500, lineHeight: 1.5 }}>{sub}</p>}
    </div>
  );
}

function Field({ label, children }) {
  return <div style={{ marginBottom: 16 }}><label className="field-label">{label}</label>{children}</div>;
}

function PhotoUpload({ photo, onChange }) {
  const inp = useRef(null);
  return (
    <div>
      <div
        onClick={() => inp.current && inp.current.click()}
        style={{
          border: "2px dashed " + (photo ? "var(--green)" : "#d8d2c4"), borderRadius: 16, padding: photo ? 14 : 28,
          textAlign: "center", cursor: "pointer", background: "#fffdf8", transition: "border-color .2s",
          display: "flex", alignItems: "center", gap: 16, justifyContent: photo ? "flex-start" : "center",
        }}>
        {photo ? (
          <React.Fragment>
            <img src={photo} alt="" style={{ width: 64, height: 64, borderRadius: 12, objectFit: "cover" }} />
            <div style={{ textAlign: "left" }}>
              <div style={{ fontWeight: 700 }}>Foto adicionada ✓</div>
              <div className="mono" style={{ fontSize: "0.75rem", color: "var(--ink-45)" }}>Toque para trocar</div>
            </div>
          </React.Fragment>
        ) : (
          <div>
            <div style={{ width: 46, height: 46, margin: "0 auto 12px", borderRadius: "50%", background: "var(--rainbow)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4"><path d="M12 5v14M5 12h14" strokeLinecap="round"/></svg>
            </div>
            <div style={{ fontWeight: 700 }}>Enviar foto do cartão</div>
            <div className="mono" style={{ fontSize: "0.75rem", color: "var(--ink-45)", marginTop: 4 }}>JPG ou PNG · sua melhor foto</div>
          </div>
        )}
      </div>
      <input ref={inp} type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => {
        const f = e.target.files && e.target.files[0]; if (!f) return;
        const r = new FileReader(); r.onload = () => onChange(r.result); r.readAsDataURL(f);
      }} />
    </div>
  );
}

function Summary({ d }) {
  return (
    <div style={{ background: "#fff", border: "2px solid #efe9dc", borderRadius: 18, padding: 22 }}>
      <div className="eyebrow" style={{ color: "var(--ink-45)", marginBottom: 16 }}>Resumo do pedido</div>
      <div style={{ transform: "rotate(-2deg)", margin: "0 auto 12px", maxWidth: 300 }}>
        <GayCardVisual name={d.name || "Nome Sobrenome"} username={d.username || "@seu_usuario"} photo={d.photo} memberNo="BR-000000" floating />
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, margin: "0 0 20px", color: "var(--ink-45)", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: "0.7rem", letterSpacing: "0.05em" }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5" strokeLinecap="round" strokeLinejoin="round"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        toque no cartão para virar
      </div>
      <Row k={PLAN_LABEL[d.plan]} v={"R$ " + BRL[d.plan]} />
      <Row k="Frete" v={d.plan === "fisico" ? "Grátis" : "—"} vColor="var(--green)" />
      {d.mode === "presente" && <Row k="Modo" v="Presente 🎁" />}
      <div style={{ height: 1, background: "#efe9dc", margin: "14px 0" }} />
      <Row k="Total" v={"R$ " + BRL[d.plan]} big />
    </div>
  );
}
function Row({ k, v, vColor, big }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "5px 0" }}>
      <span style={{ fontWeight: big ? 800 : 500, fontSize: big ? "1.05rem" : "0.92rem", color: big ? "var(--ink)" : "var(--ink-70)" }}>{k}</span>
      <span className={big ? "display" : ""} style={{ fontWeight: big ? 900 : 700, fontSize: big ? "1.3rem" : "0.95rem", color: vColor || "var(--ink)" }}>{v}</span>
    </div>
  );
}

function Checkout() {
  const [data, setData] = useState({
    plan: param("plano") === "digital" ? "digital" : "fisico",
    mode: param("modo") === "eu" ? "eu" : "presente",
    photo: null, username: "", name: "",
    cep: "", rua: "", numero: "", compl: "", bairro: "", cidade: "", uf: "",
    recipientName: "", fromName: "", message: "", email: "",
    memberNo: "", date: "",
  });
  const set = (patch) => setData((d) => ({ ...d, ...patch }));
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [pix, setPix] = useState(null);          // { brCode, brCodeBase64, chargeId, amountCents, devMode, expiresAt }
  const [payStatus, setPayStatus] = useState("idle"); // idle | pending | checking | paid
  const memberNoRef = useRef("");

  const steps = useMemo(() => {
    const s = ["tipo", "cartao"];
    if (data.plan === "fisico") s.push("entrega");
    s.push("mensagem", "email", "pagamento", "confirmacao");
    return s;
  }, [data.plan]);

  const [stepName, setStepName] = useState("tipo");
  const idx = Math.max(0, steps.indexOf(stepName));
  useEffect(() => { if (!steps.includes(stepName)) setStepName(steps[Math.min(idx, steps.length - 1)]); }, [steps]);

  const go = (dir) => {
    const cur = steps.indexOf(stepName);
    const next = cur + dir;
    if (next < 0) { location.href = "GayCard.html"; return; }
    if (next >= steps.length) return;
    setStepName(steps[next]);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // validation per step
  const valid = (() => {
    switch (stepName) {
      case "cartao": return data.name.trim().length > 0;
      case "entrega": return data.cep && data.rua && data.numero && data.cidade && data.uf && (data.mode !== "presente" || data.recipientName.trim());
      case "email": return /\S+@\S+\.\S+/.test(data.email);
      default: return true;
    }
  })();

  // Step into payment: create the order, then create the Pix charge.
  const enterPayment = async () => {
    setStepName("pagamento");
    window.scrollTo({ top: 0 });
    if (submitting || pix || memberNoRef.current) return; // already created
    setSubmitting(true); setError("");
    try {
      if (!window.GayCardAPI || !window.GayCardAPI.configured()) {
        throw new Error("Backend não configurado. Copie config.example.js para config.js.");
      }
      // Upload the photo (if any) to Storage, then create the order server-side.
      let photoPath = null;
      if (data.photo) photoPath = await window.GayCardAPI.uploadCardPhoto(data.photo);
      const { memberNo } = await window.GayCardAPI.createOrder(data, photoPath);
      const date = new Date().toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", year: "numeric" }).replace(/\//g, " · ");
      memberNoRef.current = memberNo;
      try {
        localStorage.setItem("gaycard:order:" + memberNo, JSON.stringify({ ...data, photo: null, memberNo, date, ts: Date.now() }));
        localStorage.setItem("gaycard:last", memberNo);
      } catch (e) {}
      set({ memberNo, date });

      // Create the Pix charge (amount comes from the order, server-side).
      const charge = await window.GayCardAPI.createPix(memberNo);
      if (charge && charge.alreadyPaid) { goConfirmed(); return; }
      setPix(charge);
      setPayStatus("pending");
    } catch (e) {
      setError((e && e.message) || "Não foi possível iniciar o pagamento. Tente novamente.");
    } finally {
      setSubmitting(false);
    }
  };

  const goConfirmed = () => {
    setPayStatus("paid");
    setStepName("confirmacao");
    window.scrollTo({ top: 0 });
  };

  // Manual "já paguei" — check once immediately.
  const manualCheck = async () => {
    if (!memberNoRef.current) return;
    setPayStatus("checking"); setError("");
    try {
      const r = await window.GayCardAPI.checkPayment(memberNoRef.current);
      if (r && r.paid) { goConfirmed(); return; }
      setError("Pagamento ainda não identificado. Assim que cair, seguimos automaticamente.");
      setPayStatus("pending");
    } catch (e) {
      setError((e && e.message) || "Não foi possível verificar o pagamento.");
      setPayStatus("pending");
    }
  };

  // DEV ONLY — simulate the Pix payment (needs an AbacatePay sandbox key).
  const simulate = async () => {
    if (!memberNoRef.current) return;
    setPayStatus("checking"); setError("");
    try {
      const r = await window.GayCardAPI.simulatePayment(memberNoRef.current);
      if (r && r.paid) { goConfirmed(); return; }
      setPayStatus("pending");
    } catch (e) {
      setError((e && e.message) || "Falha ao simular.");
      setPayStatus("pending");
    }
  };

  // Auto-poll while waiting for the Pix to clear.
  useEffect(() => {
    if (payStatus !== "pending" || !memberNoRef.current) return;
    let stop = false;
    const tick = async () => {
      try {
        const r = await window.GayCardAPI.checkPayment(memberNoRef.current);
        if (!stop && r && r.paid) goConfirmed();
      } catch (e) { /* keep polling */ }
    };
    const iv = setInterval(tick, 3000);
    return () => { stop = true; clearInterval(iv); };
  }, [payStatus]);

  const showPreview = !["pagamento", "confirmacao"].includes(stepName);

  return (
    <div style={{ minHeight: "100vh", background: "#fbf8f1" }}>
      {/* top bar */}
      <div style={{ position: "sticky", top: 0, zIndex: 20, background: "rgba(251,248,241,0.9)", backdropFilter: "blur(10px)", borderBottom: "1px solid #efe9dc" }}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 64 }}>
          <a href="GayCard.html" style={{ display: "flex", alignItems: "center", gap: 8, textDecoration: "none" }}>
            <PrideFlag width={26} />
            <span className="display" style={{ fontSize: "1.2rem", color: "var(--ink)" }}>Gay<span className="rainbow-text">Card</span></span>
          </a>
          <span className="mono" style={{ fontSize: "0.72rem", color: "var(--ink-45)", letterSpacing: "0.1em" }}>
            {stepName === "confirmacao" ? "PEDIDO CONFIRMADO" : `PASSO ${Math.min(idx + 1, steps.length - 1)} DE ${steps.length - 1}`}
          </span>
        </div>
        {stepName !== "confirmacao" && <div className="wrap" style={{ paddingBottom: 12 }}><Progress idx={idx} total={steps.length - 1} /></div>}
      </div>

      <div className={"wrap " + (showPreview ? "checkout-grid" : "")} style={{ padding: "40px 24px 80px", display: "grid", gridTemplateColumns: showPreview ? "1.3fr 0.9fr" : "1fr", gap: 40, alignItems: "start" }}>
        <div className="checkout-main">
          {stepName === "tipo" && <StepTipo data={data} set={set} />}
          {stepName === "cartao" && <StepCartao data={data} set={set} />}
          {stepName === "entrega" && <StepEntrega data={data} set={set} />}
          {stepName === "mensagem" && <StepMensagem data={data} set={set} />}
          {stepName === "email" && <StepEmail data={data} set={set} />}
          {stepName === "pagamento" && <StepPagamento data={data} pix={pix} payStatus={payStatus} submitting={submitting} error={error} onManualCheck={manualCheck} onSimulate={simulate} />}
          {stepName === "confirmacao" && <StepConfirmacao data={data} />}

          {!["pagamento", "confirmacao"].includes(stepName) && (
            <div style={{ display: "flex", gap: 12, marginTop: 30 }}>
              <button className="btn btn-ghost" onClick={() => go(-1)}>Voltar</button>
              <button className="btn btn-rainbow" disabled={!valid} style={{ opacity: valid ? 1 : 0.4, cursor: valid ? "pointer" : "not-allowed" }}
                onClick={() => { const cur = steps.indexOf(stepName); if (steps[cur + 1] === "pagamento" || steps[cur + 1] === "confirmacao") { enterPayment(); } else go(1); }}>
                {steps[steps.indexOf(stepName) + 1] === "pagamento" ? "Ir para pagamento" : "Continuar"}
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </button>
            </div>
          )}
        </div>

        {showPreview && <div className="checkout-aside" style={{ position: "sticky", top: 110 }}><Summary d={data} /></div>}
      </div>
    </div>
  );
}

/* ---------- Steps ---------- */
function PlanOpt({ active, onClick, name, price, desc, accent }) {
  return (
    <button onClick={onClick} style={{
      textAlign: "left", cursor: "pointer", borderRadius: 18, padding: 22, background: "#fff",
      border: "2px solid " + (active ? accent : "#efe9dc"), boxShadow: active ? `0 14px 30px -16px ${accent}` : "none",
      transition: "all .2s", position: "relative", width: "100%",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="display" style={{ fontSize: "1.4rem" }}>{name}</span>
        <span style={{ width: 22, height: 22, borderRadius: "50%", border: "2px solid " + (active ? accent : "#cfc9bb"), background: active ? accent : "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>
          {active && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5"><path d="M5 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
        </span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 3, margin: "8px 0 6px" }}>
        <span style={{ fontWeight: 700, fontSize: "0.85rem", opacity: 0.6 }}>R$</span>
        <span className="display" style={{ fontSize: "2.2rem" }}>{price}</span>
      </div>
      <p style={{ color: "var(--ink-70)", margin: 0, fontWeight: 500, fontSize: "0.9rem" }}>{desc}</p>
    </button>
  );
}

function StepTipo({ data, set }) {
  return (
    <div>
      <StepHead kicker="Passo 1 · Tipo" title="Como você quer o seu GayCard?" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <PlanOpt active={data.plan === "fisico"} onClick={() => set({ plan: "fisico" })} name="Físico" price="29,90" accent="var(--purple)" desc="Cartão impresso + carta entregues em casa. Frete grátis." />
        <PlanOpt active={data.plan === "digital"} onClick={() => set({ plan: "digital" })} name="Digital" price="19,90" accent="var(--blue)" desc="Só o certificado online, na hora, por e-mail." />
      </div>

      <div className="eyebrow" style={{ color: "var(--ink-45)", margin: "28px 0 12px" }}>Pra quem é?</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <PlanOpt active={data.mode === "presente"} onClick={() => set({ mode: "presente" })} name="Presente 🎁" price="" accent="var(--green)" desc="Enviar direto pra outra pessoa." />
        <PlanOpt active={data.mode === "eu"} onClick={() => set({ mode: "eu" })} name="Pra mim" price="" accent="var(--red)" desc="Eu sou o membro orgulhoso." />
      </div>
    </div>
  );
}

function StepCartao({ data, set }) {
  const isGift = data.mode === "presente";
  return (
    <div>
      <StepHead kicker="Passo 2 · Seu cartão" title={isGift ? "Monte o cartão do presenteado" : "Monte o seu cartão"} sub="A foto e o nome aparecem direto no cartão — e o mesmo nome vai na carta. Veja a prévia ao lado." />
      <Field label="Foto do cartão"><PhotoUpload photo={data.photo} onChange={(p) => set({ photo: p })} /></Field>
      <Field label={isGift ? "Nome e sobrenome do presenteado" : "Seu nome e sobrenome"}>
        <input className="input" value={data.name} onChange={(e) => set({ name: e.target.value })} placeholder="Ex: Alexander Souza" />
      </Field>
      <p className="mono" style={{ fontSize: "0.72rem", color: "var(--ink-45)", margin: "-8px 0 0" }}>Vai no cartão (primeiro nome em cima, sobrenome embaixo) e na carta.</p>
    </div>
  );
}

function StepEntrega({ data, set }) {
  const isGift = data.mode === "presente";
  return (
    <div>
      <StepHead kicker="Passo 3 · Entrega" title={isGift ? "Endereço do presenteado" : "Endereço de entrega"} sub="Frete grátis pra todo o Brasil. Chega em uma carta lacrada." />
      {isGift && <Field label="Nome de quem vai receber"><input className="input" value={data.recipientName} onChange={(e) => set({ recipientName: e.target.value })} placeholder="Nome completo" /></Field>}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 14 }}>
        <Field label="CEP"><input className="input" value={data.cep} onChange={(e) => set({ cep: e.target.value })} placeholder="00000-000" /></Field>
        <Field label="Cidade"><input className="input" value={data.cidade} onChange={(e) => set({ cidade: e.target.value })} placeholder="Cidade" /></Field>
      </div>
      <Field label="Rua / Logradouro"><input className="input" value={data.rua} onChange={(e) => set({ rua: e.target.value })} placeholder="Rua, avenida..." /></Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 0.6fr", gap: 14 }}>
        <Field label="Número"><input className="input" value={data.numero} onChange={(e) => set({ numero: e.target.value })} placeholder="123" /></Field>
        <Field label="Complemento"><input className="input" value={data.compl} onChange={(e) => set({ compl: e.target.value })} placeholder="Apto, bloco" /></Field>
        <Field label="UF"><input className="input" value={data.uf} onChange={(e) => set({ uf: e.target.value.toUpperCase().slice(0, 2) })} placeholder="SP" /></Field>
      </div>
      <Field label="Bairro"><input className="input" value={data.bairro} onChange={(e) => set({ bairro: e.target.value })} placeholder="Bairro" /></Field>
    </div>
  );
}

function StepMensagem({ data, set }) {
  const isGift = data.mode === "presente";
  return (
    <div>
      <StepHead kicker={`Passo ${data.plan === "fisico" ? 4 : 3} · Mensagem`} title="Uma mensagem na carta" sub="Tudo aqui é opcional — pode deixar em branco. O que você escrever vai impresso na carta, junto da mensagem oficial." />
      {isGift && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="De (seu nome) · opcional"><input className="input" value={data.fromName} onChange={(e) => set({ fromName: e.target.value })} placeholder="Você" /></Field>
        </div>
      )}
      <Field label="Sua mensagem personalizada · opcional">
        <textarea className="textarea" value={data.message} onChange={(e) => set({ message: e.target.value })} maxLength={240}
          placeholder="Ex: Seja sempre exatamente quem você é. Te amo. 🏳️‍🌈" />
      </Field>
      <p className="mono" style={{ fontSize: "0.72rem", color: "var(--ink-45)", textAlign: "right" }}>{(data.message || "").length}/240</p>
      <div style={{ marginTop: 16 }}>
        <div className="eyebrow" style={{ color: "var(--ink-45)", marginBottom: 12 }}>Prévia da carta</div>
        <div style={{ maxHeight: 320, overflow: "auto", borderRadius: 12, border: "1px solid #efe9dc" }}>
          <LetterDocument name={data.name || "Membro"} custom={data.message} fromName={data.fromName} gift={isGift} date="" />
        </div>
      </div>
    </div>
  );
}

function StepEmail({ data, set }) {
  return (
    <div>
      <StepHead kicker="Quase lá" title="Pra onde mandamos a confirmação?" sub="Você recebe o comprovante, o acompanhamento da entrega e o link do certificado." />
      <Field label="Seu e-mail"><input className="input" type="email" value={data.email} onChange={(e) => set({ email: e.target.value })} placeholder="voce@email.com" /></Field>
      <div style={{ display: "flex", gap: 12, background: "#fff4cc", border: "1px solid #ffe48a", borderRadius: 14, padding: "14px 16px", marginTop: 4 }}>
        <span style={{ fontSize: "1.2rem", lineHeight: 1 }}>📩</span>
        <p style={{ margin: 0, color: "#8a6d00", fontSize: "0.88rem", lineHeight: 1.5, fontWeight: 500 }}>
          <strong>Confira sua caixa de spam.</strong> Nosso e-mail pode cair no spam/lixo eletrônico. Quando chegar, marque como <strong>"não é spam"</strong> e adicione aos contatos — assim você garante o recebimento do <strong>código de rastreio</strong> assim que o pedido for enviado.
        </p>
      </div>
      <div style={{ background: "#fff", border: "2px solid #efe9dc", borderRadius: 16, padding: 20, marginTop: 8 }}>
        <div className="eyebrow" style={{ color: "var(--ink-45)", marginBottom: 14 }}>Conferindo</div>
        <Row k="Tipo" v={PLAN_LABEL[data.plan]} />
        <Row k="Nome no cartão" v={data.name || "—"} />
        {data.plan === "fisico" && <Row k="Entrega" v={data.cidade ? `${data.cidade}/${data.uf}` : "—"} />}
        {data.mode === "presente" && <Row k="Presente para" v={data.recipientName || data.name || "—"} />}
      </div>
      <p style={{ marginTop: 14, fontSize: "0.8rem", color: "var(--ink-45)", lineHeight: 1.5, fontWeight: 500 }}>
        Ao ir para o pagamento, você concorda com a nossa{" "}
        <a href="Privacidade.html" target="_blank" rel="noopener" style={{ color: "var(--ink)" }}>Política de Privacidade e Termos</a>
        {" "}— incluindo que o certificado do cartão é <strong>público</strong> para quem tiver o link ou o QR.
      </p>
    </div>
  );
}

function StepPagamento({ data, pix, payStatus, submitting, error, onManualCheck, onSimulate }) {
  const total = BRL[data.plan];
  const [copied, setCopied] = useState(false);
  const brCode = pix && pix.brCode;
  const checking = payStatus === "checking";

  // While the order + charge are being created.
  if (submitting || !pix) {
    return (
      <div style={{ maxWidth: 560, margin: "0 auto" }}>
        <div style={{ background: "#fff", border: "2px solid #efe9dc", borderRadius: 22, padding: 48, textAlign: "center" }}>
          <div className="eyebrow" style={{ color: "var(--green)", marginBottom: 16 }}>Pagamento via Pix</div>
          {error
            ? <p style={{ color: "var(--red)", fontWeight: 600 }}>{error}</p>
            : <p style={{ color: "var(--ink-70)", fontWeight: 500, margin: 0 }}>Gerando sua cobrança Pix…</p>}
        </div>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 560, margin: "0 auto" }}>
      <div style={{ background: "#fff", border: "2px solid #efe9dc", borderRadius: 22, padding: 32, textAlign: "center" }}>
        <div className="eyebrow" style={{ color: "var(--green)", marginBottom: 10 }}>Pagamento via Pix</div>
        <h2 className="display" style={{ fontSize: "1.8rem", margin: "0 0 4px" }}>R$ {total}</h2>
        <p style={{ color: "var(--ink-70)", fontWeight: 500, margin: "0 0 22px" }}>Escaneie o QR no app do seu banco ou use o copia e cola.</p>
        <div style={{ display: "inline-flex", padding: 16, background: "#fff", border: "1px solid #eee", borderRadius: 16 }}>
          {pix.brCodeBase64
            ? <img src={pix.brCodeBase64} alt="QR Code Pix" style={{ width: 180, height: 180, display: "block" }} />
            : <QRCode value={brCode} size={180} />}
        </div>
        <div style={{ display: "flex", gap: 8, margin: "22px 0 10px" }}>
          <input className="input mono" readOnly value={brCode} style={{ fontSize: "0.72rem" }} />
          <button className="btn btn-ink" style={{ flexShrink: 0, padding: "0.85rem 1.1rem" }}
            onClick={() => { navigator.clipboard && navigator.clipboard.writeText(brCode); setCopied(true); setTimeout(() => setCopied(false), 1800); }}>
            {copied ? "Copiado!" : "Copiar"}
          </button>
        </div>
        <p className="mono" style={{ fontSize: "0.68rem", color: "var(--ink-45)", marginBottom: 20 }}>
          <span style={{ display: "inline-block", width: 7, height: 7, borderRadius: "50%", background: "var(--green)", marginRight: 6 }} />
          AGUARDANDO PAGAMENTO · CONFIRMA SOZINHO QUANDO CAIR
        </p>
        {error && <p style={{ color: "var(--red)", fontWeight: 600, fontSize: "0.9rem", marginBottom: 14 }}>{error}</p>}
        <button className="btn btn-rainbow" style={{ width: "100%", justifyContent: "center", opacity: checking ? 0.6 : 1, cursor: checking ? "wait" : "pointer" }} onClick={onManualCheck} disabled={checking}>
          {checking ? "Verificando..." : "Já fiz o pagamento"}
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
        {pix.devMode && (
          <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", marginTop: 10 }} onClick={onSimulate} disabled={checking}>
            Simular pagamento (teste)
          </button>
        )}
      </div>
    </div>
  );
}

function StepConfirmacao({ data }) {
  const certUrl = location.origin + location.pathname.replace(/Comprar\.html$/, "Certificado.html") + "?id=" + data.memberNo;
  return (
    <div style={{ maxWidth: 620, margin: "0 auto", textAlign: "center" }}>
      <div style={{ width: 72, height: 72, margin: "0 auto 22px", borderRadius: "50%", background: "var(--rainbow)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 16px 40px -14px rgba(139,20,201,0.5)" }}>
        <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><path d="M5 12l5 5L20 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </div>
      <h2 className="display" style={{ fontSize: "clamp(2rem,4vw,2.8rem)", margin: 0 }}>Bem-vindo(a) à <span className="rainbow-text">comunidade!</span></h2>
      <p style={{ color: "var(--ink-70)", fontWeight: 500, fontSize: "1.05rem", margin: "14px 0 6px" }}>
        {data.plan === "fisico"
          ? (data.mode === "presente" ? "Seu presente está a caminho da casa do(a) sortudo(a)." : "Seu cartão está sendo produzido e logo chega na sua casa.")
          : "Seu certificado digital já está pronto."}
      </p>
      <p className="mono" style={{ color: "var(--ink-45)", letterSpacing: "0.1em", marginBottom: 30 }}>MEMBRO Nº {data.memberNo} · {data.date}</p>

      <div className="confirm-grid" style={{ background: "#fff", border: "2px solid #efe9dc", borderRadius: 22, padding: 30, display: "grid", gridTemplateColumns: "1fr auto", gap: 26, alignItems: "center", textAlign: "left" }}>
        <div>
          <div className="eyebrow" style={{ color: "var(--purple)", marginBottom: 10 }}>Seu certificado online</div>
          <p style={{ color: "var(--ink-70)", fontWeight: 500, margin: "0 0 18px", lineHeight: 1.5 }}>
            Este é o QR que vai impresso no cartão. Ele abre a sua página de Certificado de Membro — pronta pra compartilhar.
          </p>
          <a className="btn btn-rainbow" href={"Certificado.html?id=" + data.memberNo}>Ver meu certificado
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
        </div>
        <div style={{ padding: 14, border: "1px solid #eee", borderRadius: 16, background: "#fff" }}>
          <QRCode value={certUrl} size={150} flag />
        </div>
      </div>

      <a href="GayCard.html" style={{ display: "inline-block", marginTop: 26, color: "var(--ink-70)", fontWeight: 600, textDecoration: "none" }}>← Voltar ao início</a>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Checkout />);
