// ─────────────────────────────────────────────────────────────
// ABA ANÁLISE DE COMPORTAMENTO
// Re-skin da ferramenta do Dr. Ulisses no design do app.
// A LÓGICA (perguntas, perfis, diagnóstico) vem 100% de
// analise-logic.js (APP_DATA + diagnoseProfile) — NÃO é alterada aqui.
// Estado e localStorage TOTALMENTE separados dos Hábitos.
// ─────────────────────────────────────────────────────────────

const { useState: useStateAnalise, useEffect: useEffectAnalise, useRef: useRefAnalise } = React;

const ANALISE_KEY = "analise_progresso_v1"; // chave própria — não toca em "habitos_v1"

function AnaliseScreen({ t, onBack, initialToken, acessoLivre }) {
  // ── estado isolado (começa SEMPRE do zero; não resume sessão antiga) ──
  // Pelo botão: exige a senha (GRAXA). Pelo link público ou link com token
  // (?token=...): pula o portão e cai direto no aviso legal.
  const [step, setStep] = useStateAnalise(() => {
    if (acessoLivre) { window.USER_TOKEN = null; return "legal"; }
    if (initialToken) { window.USER_TOKEN = initialToken; return "legal"; }
    return "token";
  });
  const [qi, setQi] = useStateAnalise(0);
  const [answers, setAnswers] = useStateAnalise({});
  const [resultCode, setResultCode] = useStateAnalise(null);
  const [tokenInput, setTokenInput] = useStateAnalise("");
  const [burning, setBurning] = useStateAnalise(false);
  const [tokenErro, setTokenErro] = useStateAnalise(null);

  const QUESTIONS = APP_DATA.questions;
  const total = QUESTIONS.length;

  const setAnswer = (id, val) => setAnswers((a) => ({ ...a, [id]: val }));

  const isValid = (q) => {
    const v = answers[q.id];
    if (q.type === "slider") return true;
    if (v === undefined || v === null || v === "") return false;
    if (q.type === "text") return String(v).trim().length > 0;
    if (q.type === "number") {
      const n = parseFloat(v);
      if (isNaN(n)) return false;
      if (q.min !== undefined && n < q.min) return false;
      if (q.max !== undefined && n > q.max) return false;
      return true;
    }
    if (q.type === "single") return !!v;
    if (q.type === "multiple") return Array.isArray(v) && v.length > 0;
    return true;
  };

  // avança SEM revalidar (usado pelo clique em opção única — evita o bug de
  // estado defasado que pedia 2 cliques)
  const goForward = () => {
    if (qi < total - 1) { setQi(qi + 1); scrollTop(); }
    else { setStep("evaluating"); scrollTop(); }
  };
  const next = () => {
    const q = QUESTIONS[qi];
    if (!isValid(q)) { setShake(true); setTimeout(() => setShake(false), 480); return; }
    goForward();
  };
  const back = () => { if (qi > 0) { setQi(qi - 1); scrollTop(); } };

  const [shake, setShake] = useStateAnalise(false);
  const scrollRef = useRefAnalise(null);
  const scrollTop = () => { if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  // ── PROGRESSO ───────────────────────────────────────────────
  const pct =
    step === "question" ? Math.round(((qi + 1) / total) * 100)
    : ["evaluating", "result", "microcopy"].includes(step) ? 100
    : 0;

  // ── TOKEN GATE → vai pro Aviso Legal (a queima acontece ao confirmar o legal,
  //    a validação/queima acontece JÁ AQUI — código inválido é barrado
  //    na hora, antes do Aviso Legal.) ──
  const entrarToken = async (e) => {
    e.preventDefault();
    const token = tokenInput.trim();
    if (!token) { setShake(true); setTimeout(() => setShake(false), 480); return; }
    window.USER_TOKEN = token;
    setTokenErro(null);

    // senha GRAXA / link livre → acesso livre, NÃO queima, vai pro legal
    if (typeof tokenEhLivre === "function" && tokenEhLivre(token)) {
      window.USER_TOKEN_BURNED = false;
      setStep("legal"); scrollTop(); return;
    }

    // valida + queima AGORA; só avança se o servidor confirmar SUCESSO
    setBurning(true);
    try {
      const resp = await fetch("burn_token.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token }),
      });
      const data = await resp.json();
      if (resp.ok && data && data.status === "success") {
        window.USER_TOKEN_BURNED = true;
        setBurning(false); setStep("legal"); scrollTop();
      } else {
        setTokenErro("invalido");
        setShake(true); setTimeout(() => setShake(false), 480);
        setBurning(false);
      }
    } catch (err) {
      // Sem servidor (preview/local): NÃO libera código aleatório.
      setTokenErro("invalido");
      setShake(true); setTimeout(() => setShake(false), 480);
      setBurning(false);
    }
  };

  // CONFIRMAÇÃO do Aviso Legal: o token já foi validado/queimado no gate
  // (ou é acesso livre / link com token). Aqui só queima o token de LINK
  // que ainda não passou pelo gate, e segue.
  const confirmarLegal = async () => {
    const token = window.USER_TOKEN;
    // acesso livre (GRAXA / link público) ou token já queimado no gate → segue
    if (acessoLivre || window.USER_TOKEN_BURNED || (typeof tokenEhLivre === "function" && tokenEhLivre(token))) {
      if (window.track) track("iniciou");
      setStep("intro0"); scrollTop(); return;
    }
    // entrou por LINK com ?token= (não passou pelo gate) → queima aqui
    setBurning(true); setTokenErro(null);
    try {
      const resp = await fetch("burn_token.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token }),
      });
      const data = await resp.json();
      if (resp.ok && data && data.status === "success") {
        if (window.track) track("iniciou");
        window.USER_TOKEN_BURNED = true;
        setBurning(false); setStep("intro0"); scrollTop();
      } else {
        setTokenErro("invalido");
        setBurning(false); setStep("token");
      }
    } catch (e) {
      setTokenErro("invalido");
      setBurning(false); setStep("token");
    }
  };

  // ════════════════════════════════════════════════════════════
  return (
    <div ref={scrollRef} style={{
      position: "absolute", inset: 0,
      background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: step === "question" ? 48 : 80,
      overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* keyframes locais */}
      <style>{`
        @keyframes anaShake { 0%,100%{transform:translateX(0)} 20%{transform:translateX(-7px)} 40%{transform:translateX(7px)} 60%{transform:translateX(-5px)} 80%{transform:translateX(5px)} }
        @keyframes anaFade { from{opacity:0; transform:translateY(8px)} to{opacity:1; transform:translateY(0)} }
        @keyframes anaSpin { to { transform: rotate(360deg); } }
        .ana-fade { animation: anaFade .35s ease both; }
        .ana-shake { animation: anaShake .45s ease; }
        .ana-ring circle.run { transition: stroke-dashoffset 8s linear; }
      `}</style>

      {/* TOPO STICKY */}
      <div style={{
        position: "sticky", top: 0, zIndex: 20, background: t.bg0,
        backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
        padding: "10px 14px 12px", borderBottom: `1px solid ${t.border}`,
        display: "flex", alignItems: "center", gap: 12,
        boxShadow: `0 6px 16px ${t.bg0}`,
      }}>
        <button onClick={onBack} style={{
          flexShrink: 0, width: 38, height: 38, borderRadius: 999,
          background: t.bg1, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2, cursor: "pointer",
        }}>
          <Icon name="back" size={16} stroke="currentColor" />
        </button>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700,
          flex: 1,
        }}>Análise de Comportamento</span>
      </div>

      {/* BARRA DE PROGRESSO */}
      <div style={{ height: 3, background: t.bg2 }}>
        <div style={{ width: `${pct}%`, height: "100%", background: t.accent, transition: "width 0.35s ease" }}></div>
      </div>

      {/* CONTEÚDO POR ETAPA */}
      <div style={{ padding: "0 20px" }}>
        {step === "token"      && <TokenGate t={t} value={tokenInput} onChange={setTokenInput} onSubmit={entrarToken} shake={shake} erro={tokenErro} />}
        {step === "legal"      && <LegalCard t={t} onOk={confirmarLegal} busy={burning} />}
        {step === "intro0"     && <IntroCard t={t} data={APP_DATA.intro[0]} label="01" cta="Continuar" onNext={() => { setStep("intro1"); scrollTop(); }} />}
        {step === "intro1"     && <IntroCard t={t} data={APP_DATA.intro[1]} label="02" cta="Começar" onNext={() => { setStep("question"); setQi(0); scrollTop(); }} />}
        {step === "question"   && <QuestionCard t={t} q={QUESTIONS[qi]} index={qi} total={total} answers={answers} setAnswer={setAnswer} onNext={next} onAuto={goForward} onBack={back} isValid={isValid} shake={shake} />}
        {step === "evaluating" && <Evaluating t={t} onDone={() => {
          let code;
          try { code = diagnoseProfile(answers); } catch (e) { code = "I"; }
          if (window.track) track("concluiu");
          setResultCode(code); setStep("result"); scrollTop();
        }} />}
        {step === "result"     && resultCode && <ResultCard t={t} code={resultCode} onNext={() => { setStep("microcopy"); scrollTop(); }} />}
        {step === "microcopy"  && resultCode && <MicrocopyCard t={t} code={resultCode} />}
      </div>
    </div>
  );
}

// ── helper: HTML controlado vindo do APP_DATA (apenas <br> e <strong>) ──
function htm(s) { return { dangerouslySetInnerHTML: { __html: s } }; }

// ─────────────────────────────────────────────────────────────
// TOKEN GATE
// ─────────────────────────────────────────────────────────────
function TokenGate({ t, value, onChange, onSubmit, shake, erro }) {
  return (
    <div className={"ana-fade" + (shake ? " ana-shake" : "")} style={{ paddingTop: 40, textAlign: "center" }}>
      <h1 style={{
        fontFamily: TYPE.display, fontSize: 52, lineHeight: 0.92, color: t.ink1,
        letterSpacing: "-0.015em", margin: "0 0 16px", textTransform: "uppercase",
      }}>Acesso<br/>exclusivo</h1>
      <p style={{
        fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink2, lineHeight: 1.6,
        margin: "0 auto 28px", maxWidth: 320,
      }}>Digite o código fornecido pelo<br/>Dr. Ulisses Nakagawa para iniciar</p>

      <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 320, margin: "0 auto" }}>
        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Digite o código"
          autoComplete="off"
          style={{
            width: "100%", padding: "16px 18px", textAlign: "center",
            background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
            color: t.ink1, fontFamily: TYPE.sans, fontSize: 15, fontWeight: 600,
            letterSpacing: "0.04em", boxSizing: "border-box", outline: "none",
          }}
        />
        <button type="submit" style={{
          width: "100%", padding: "17px 18px",
          background: t.ink1, color: t.bg0, border: "none", borderRadius: RADIUS.md,
          cursor: "pointer", fontFamily: TYPE.sans, fontSize: 14, fontWeight: 800,
          letterSpacing: "0.12em", textTransform: "uppercase",
        }}>Entrar</button>
      </form>

      {erro && (
        <div className="ana-shake" style={{
          marginTop: 16, maxWidth: 320, marginLeft: "auto", marginRight: "auto",
          padding: "14px 16px", borderRadius: RADIUS.md,
          border: `1px solid ${t.danger}`, color: t.danger,
          fontFamily: TYPE.sans, fontSize: 13.5, lineHeight: 1.55, fontWeight: 700,
        }}>
          Código inválido!<br/>
          <span style={{ fontWeight: 500 }}>Converse com o Dr. Ulisses Nakagawa.</span>
        </div>
      )}

      <SocialProof t={t} />
    </div>
  );
}

// ── Prova social: "473 pessoas já fizeram" (conta real + base) ──
function SocialProof({ t }) {
  const base = (window.LINKS && LINKS.analise_total_feitas) || 473;
  const [n, setN] = useStateAnalise(base);
  useEffectAnalise(() => {
    let vivo = true;
    (async () => {
      try {
        const r = await fetch("eventos.php", {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action: "count", base, evento: "iniciou" }),
        });
        const d = await r.json();
        if (vivo && d && d.status === "success" && typeof d.total === "number") setN(d.total);
      } catch (e) { /* sem servidor: mantém a base */ }
    })();
    return () => { vivo = false; };
  }, []);
  return (
    <div style={{
      marginTop: 30, display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
    }}>
      <span style={{ display: "flex" }}>
        {[0, 1, 2].map((i) => (
          <span key={i} style={{
            width: 22, height: 22, borderRadius: 999,
            background: t.bg2, border: `1.5px solid ${t.bg0}`,
            marginLeft: i === 0 ? 0 : -8, display: "inline-block",
          }}></span>
        ))}
      </span>
      <span style={{
        fontFamily: TYPE.sans, fontSize: 12, color: t.ink3, fontWeight: 600,
      }}><b style={{ color: t.ink1, fontWeight: 800 }}>{n.toLocaleString("pt-BR")}</b> pessoas já fizeram</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AVISO LEGAL  (CONFIG_ALERTAS.tela1)
// ─────────────────────────────────────────────────────────────
function LegalCard({ t, onOk, busy }) {
  const c = CONFIG_ALERTAS.tela1;
  return (
    <div className="ana-fade" style={{ paddingTop: 30 }}>
      <div style={{
        background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.lg,
        padding: "30px 24px 26px", textAlign: "center",
      }}>
        <div style={{
          width: 52, height: 52, margin: "0 auto 22px", borderRadius: 999,
          border: `1.5px solid ${t.border}`, display: "flex", alignItems: "center", justifyContent: "center", color: t.ink2,
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
          </svg>
        </div>
        {c.titulo && <h2 style={{
          fontFamily: TYPE.display, fontSize: 34, color: t.ink1, margin: "0 0 18px",
          letterSpacing: "-0.01em", textTransform: "uppercase", lineHeight: 1,
        }}>{c.titulo}</h2>}
        <p style={{ fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink2, lineHeight: 1.65, margin: "0 0 14px" }} {...htm(c.texto1)}></p>
        <p style={{ fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink2, lineHeight: 1.65, margin: 0 }} {...htm(c.texto2)}></p>
      </div>
      <SocialProof t={t} />
      <button onClick={onOk} disabled={busy} style={{ ...primaryBtn(t), opacity: busy ? 0.6 : 1, cursor: busy ? "default" : "pointer" }}>{busy ? "Validando..." : c.botao}</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CARDS DE INTRO
// ─────────────────────────────────────────────────────────────
function IntroCard({ t, data, label, cta, onNext }) {
  return (
    <div className="ana-fade" style={{ paddingTop: 30 }}>
      <div style={{
        fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
        letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 700, marginBottom: 14,
      }}>{label} · Antes de começar</div>
      {data.title && <h1 style={{
        fontFamily: TYPE.display, fontSize: 44, lineHeight: 0.95, color: t.ink1,
        letterSpacing: "-0.015em", margin: "0 0 20px", textTransform: "uppercase",
      }} {...htm(data.title)}></h1>}
      <p style={{
        fontFamily: TYPE.sans, fontSize: 14.5, color: t.ink2, lineHeight: 1.7, margin: 0,
      }} {...htm(data.text)}></p>
      <button onClick={onNext} style={primaryBtn(t)}>{cta}</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PERGUNTA
// ─────────────────────────────────────────────────────────────
function QuestionCard({ t, q, index, total, answers, setAnswer, onNext, onAuto, onBack, isValid, shake }) {
  const val = answers[q.id];
  const valid = isValid(q);

  return (
    <div key={q.id} className={"ana-fade" + (shake ? " ana-shake" : "")} style={{ paddingTop: 24 }}>
      <div style={{
        fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
        letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700, marginBottom: 14,
        fontVariantNumeric: "tabular-nums",
      }}>Pergunta {index + 1} / {total}</div>

      <h2 style={{
        fontFamily: TYPE.display, fontSize: 30, lineHeight: 1.02, color: t.ink1,
        letterSpacing: "-0.01em", margin: "0 0 10px", textTransform: "uppercase",
      }} {...htm(q.question)}></h2>
      {q.description && <p style={{
        fontFamily: TYPE.sans, fontSize: 13, color: t.ink3, lineHeight: 1.55, margin: "0 0 22px",
      }}>{q.description}</p>}
      {!q.description && <div style={{ height: 20 }}></div>}

      {/* INPUTS */}
      {(q.type === "text" || q.type === "number") && (
        <input
          type={q.type}
          value={val || ""}
          onChange={(e) => setAnswer(q.id, e.target.value)}
          onKeyDown={(e) => { if (e.key === "Enter") onNext(); }}
          placeholder="Digite aqui..."
          min={q.min} max={q.max}
          autoFocus
          style={{
            width: "100%", padding: "16px 18px",
            background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
            color: t.ink1, fontFamily: TYPE.sans, fontSize: 16, fontWeight: 600,
            boxSizing: "border-box", outline: "none",
          }}
        />
      )}

      {q.type === "single" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          {q.options.map((opt, i) => {
            const sel = val === opt;
            return (
              <button key={i} onClick={() => { setAnswer(q.id, opt); if (q.autoAdvance) setTimeout(onAuto, 240); }}
                style={optBtn(t, sel)} {...htm(opt)}></button>
            );
          })}
        </div>
      )}

      {q.type === "multiple" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          {q.options.map((opt, i) => {
            const arr = Array.isArray(val) ? val : [];
            const sel = arr.includes(opt);
            return (
              <button key={i} onClick={() => {
                const nextArr = sel ? arr.filter((x) => x !== opt) : [...arr, opt];
                setAnswer(q.id, nextArr);
              }} style={optBtn(t, sel, true)}>
                <span style={{
                  flexShrink: 0, width: 18, height: 18, borderRadius: 5,
                  border: `1.5px solid ${sel ? t.accent : t.ink4}`,
                  background: sel ? t.accent : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  {sel && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={t.accentInk} strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-11"/></svg>}
                </span>
                <span style={{ textAlign: "left", flex: 1 }} {...htm(opt)}></span>
              </button>
            );
          })}
        </div>
      )}

      {q.type === "slider" && (
        <SliderInput t={t} q={q} val={val !== undefined ? val : q.min} onChange={(n) => setAnswer(q.id, n)} />
      )}

      {/* NAV */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 34, gap: 12 }}>
        <button onClick={onBack} style={{
          visibility: index === 0 ? "hidden" : "visible",
          background: "transparent", border: "none", cursor: "pointer",
          color: t.ink3, fontFamily: TYPE.sans, fontSize: 12, fontWeight: 700,
          letterSpacing: "0.1em", textTransform: "uppercase", padding: "8px 4px",
        }}>Voltar</button>

        {q.type !== "single" && (
          <button onClick={onNext} style={{
            ...primaryBtnInline(t), opacity: valid ? 1 : 0.4, pointerEvents: valid ? "auto" : "none",
            width: "auto", minWidth: 150, marginTop: 0,
          }}>{index === total - 1 ? "Finalizar" : "Continuar"}</button>
        )}
      </div>
    </div>
  );
}

function SliderInput({ t, q, val, onChange }) {
  return (
    <div style={{ paddingTop: 8 }}>
      <div style={{ textAlign: "center", marginBottom: 18 }}>
        <span style={{
          fontFamily: TYPE.display, fontSize: 72, color: t.ink1, lineHeight: 1,
          letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums",
        }}>{val}</span>
        <span style={{ fontFamily: TYPE.sans, fontSize: 16, color: t.ink3, marginLeft: 6 }}>/ {q.max}</span>
      </div>
      <input
        type="range" min={q.min} max={q.max} value={val}
        onChange={(e) => onChange(parseInt(e.target.value, 10))}
        style={{ width: "100%", accentColor: t.accent, height: 6, cursor: "pointer" }}
      />
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontFamily: TYPE.sans, fontSize: 11, color: t.ink4, fontWeight: 600 }}>
        <span>{q.min}</span><span>{q.max}</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AVALIANDO (8s — fiel ao original)
// ─────────────────────────────────────────────────────────────
function Evaluating({ t, onDone }) {
  const ringRef = useRefAnalise(null);
  useEffectAnalise(() => {
    const c = ringRef.current;
    if (c) { c.getBoundingClientRect(); requestAnimationFrame(() => { c.style.strokeDashoffset = "0"; }); }
    const id = setTimeout(onDone, 8000);
    return () => clearTimeout(id);
  }, []);
  return (
    <div className="ana-fade" style={{ textAlign: "center", paddingTop: 80 }}>
      <svg className="ana-ring" width="120" height="120" style={{ transform: "rotate(-90deg)" }}>
        <circle stroke={t.bg2} strokeWidth="7" fill="transparent" r="52" cx="60" cy="60"/>
        <circle ref={ringRef} className="run" stroke={t.accent} strokeWidth="7" fill="transparent" r="52" cx="60" cy="60"
          strokeDasharray="327" strokeDashoffset="327" strokeLinecap="round"/>
      </svg>
      <h1 style={{
        fontFamily: TYPE.display, fontSize: 34, color: t.ink1, margin: "30px 0 12px",
        letterSpacing: "-0.01em", textTransform: "uppercase", lineHeight: 1,
      }}>Estou avaliando<br/>tuas respostas</h1>
      <p style={{ fontFamily: TYPE.sans, fontSize: 13.5, color: t.ink3, lineHeight: 1.6, margin: 0 }}>
        Um momento, por favor.<br/>Tua análise merece atenção e respeito.
      </p>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RESULTADO
// ─────────────────────────────────────────────────────────────
function ResultCard({ t, code, onNext }) {
  const p = APP_DATA.results[code];
  return (
    <div className="ana-fade" style={{ paddingTop: 30 }}>
      <div style={{ textAlign: "center", marginBottom: 22 }}>
        <div style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.22em", textTransform: "uppercase", fontWeight: 700, marginBottom: 14,
        }}>Seu perfil</div>
        <div style={{
          width: 64, height: 64, margin: "0 auto 18px", borderRadius: 999,
          border: `1.5px solid ${t.border}`, display: "flex", alignItems: "center", justifyContent: "center", color: t.accent,
        }}>
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="M22 4 12 14.01l-3-3"/>
          </svg>
        </div>
        <h1 style={{
          fontFamily: TYPE.display, fontSize: 46, color: t.ink1, margin: 0,
          letterSpacing: "-0.015em", textTransform: "uppercase", lineHeight: 0.95,
        }}>{p.title}</h1>
      </div>
      <div style={{
        background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.lg, padding: "22px 20px",
        fontFamily: TYPE.sans, fontSize: 14.5, color: t.ink2, lineHeight: 1.72,
        whiteSpace: "pre-line", textAlign: "justify",
      }} {...htm(p.description)}></div>
      <button onClick={onNext} style={primaryBtn(t)}>Continuar</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MICROCOPY / CTA FINAL
// ─────────────────────────────────────────────────────────────
function MicrocopyCard({ t, code }) {
  return (
    <div className="ana-fade" style={{ paddingTop: 40, textAlign: "center" }}>
      <div style={{
        width: 56, height: 56, margin: "0 auto 24px", borderRadius: 999,
        border: `1.5px solid ${t.border}`, display: "flex", alignItems: "center", justifyContent: "center", color: t.accent,
      }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="M22 4 12 14.01l-3-3"/>
        </svg>
      </div>
      <p style={{
        fontFamily: TYPE.display, fontSize: 30, color: t.ink1, lineHeight: 1.08,
        letterSpacing: "-0.01em", textTransform: "uppercase", margin: "0 0 14px",
      }}>Entender é o primeiro passo.<br/>Resolver é o próximo.</p>
      <p style={{
        fontFamily: TYPE.sans, fontSize: 14, color: t.ink2, lineHeight: 1.6, margin: "0 auto 30px", maxWidth: 320,
      }}>Leve essa análise pra uma consulta comigo<br/>e a gente monta o teu plano de verdade.</p>

      {/* BOTÃO IDÊNTICO AO DA ABA CONSULTA */}
      <a
        href={waLink(`Olá Dr. Ulisses! Fiz a Análise de Comportamento e o meu perfil deu "${(APP_DATA.results[code] && APP_DATA.results[code].title) || ""}". Quero AGENDAR UMA CONSULTA com você para alcançar os meus objetivos.`)}
        target="_blank" rel="noreferrer"
        onClick={() => { if (window.track) track("clicou_consulta"); }}
        className="cta-agendar"
        style={{
          position: "relative", overflow: "hidden",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4,
          padding: "20px 20px",
          background: t.ink1, color: t.bg0,
          borderRadius: RADIUS.md, textDecoration: "none",
          fontFamily: TYPE.sans, textAlign: "center",
          boxShadow: "0 10px 28px rgba(0,0,0,0.4)",
        }}
      >
        <span style={{
          fontSize: 16, fontWeight: 800, letterSpacing: "0.10em",
          textTransform: "uppercase", lineHeight: 1.1,
        }}>Agendar Consulta</span>
        <span style={{
          fontSize: 11, fontWeight: 700, letterSpacing: "0.16em",
          textTransform: "uppercase", opacity: 0.72, lineHeight: 1.1,
        }}>Com o Dr. Ulisses Nakagawa</span>
        <span aria-hidden="true" className="cta-sheen"></span>
      </a>

      {/* COMPARTILHAR NOS STORIES — opcional, nunca invasivo */}
      <ShareStoriesButton t={t} code={code} />

      {/* CONTATO OPCIONAL — recolhido por padrão, totalmente pulável */}
      <LeadCapture t={t} />
    </div>
  );
}

// ── Captura de contato opcional (recolhida; nada obrigatório) ──
function LeadCapture({ t }) {
  const [open, setOpen] = useStateAnalise(false);
  const [nome, setNome] = useStateAnalise("");
  const [wpp, setWpp] = useStateAnalise("");
  const [done, setDone] = useStateAnalise(false);
  const [busy, setBusy] = useStateAnalise(false);

  const enviar = async () => {
    const digits = (wpp || "").replace(/\D/g, "");
    if (!nome.trim() || digits.length < 10) { return; }
    setBusy(true);
    try {
      await fetch("leads.php", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ nome: nome.trim(), whatsapp: digits }),
        keepalive: true,
      });
    } catch (e) {}
    if (window.track) track("lead");
    setBusy(false); setDone(true);
  };

  if (done) {
    return (
      <p style={{
        marginTop: 18, fontFamily: TYPE.sans, fontSize: 13, color: t.ink3,
        lineHeight: 1.5, textAlign: "center",
      }}>Recebido. O Dr. Ulisses vai falar com você. ✓</p>
    );
  }

  if (!open) {
    return (
      <button onClick={() => setOpen(true)} style={{
        marginTop: 16, width: "100%", background: "transparent", border: "none",
        cursor: "pointer", color: t.ink3, fontFamily: TYPE.sans, fontSize: 12.5,
        textDecoration: "underline", textUnderlineOffset: 3,
      }}>Prefere que o Dr. entre em contato? Toque aqui</button>
    );
  }

  const inp = {
    width: "100%", padding: "13px 15px", boxSizing: "border-box",
    background: t.bg0, border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
    color: t.ink1, fontFamily: TYPE.sans, fontSize: 14, fontWeight: 600, outline: "none",
  };
  return (
    <div style={{
      marginTop: 16, padding: "16px", background: t.bg1,
      border: `1px solid ${t.border}`, borderRadius: RADIUS.lg, textAlign: "left",
    }}>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <input value={nome} onChange={(e) => setNome(e.target.value)} placeholder="Seu nome" style={inp} />
        <input value={wpp} onChange={(e) => setWpp(e.target.value)} placeholder="Seu WhatsApp (com DDD)" inputMode="tel" style={inp} />
        <button onClick={enviar} disabled={busy} style={{
          width: "100%", padding: "14px", background: t.ink1, color: t.bg0, border: "none",
          borderRadius: RADIUS.md, cursor: busy ? "default" : "pointer", opacity: busy ? 0.6 : 1,
          fontFamily: TYPE.sans, fontSize: 13, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase",
        }}>{busy ? "Enviando..." : "Enviar"}</button>
      </div>
    </div>
  );
}

// ── Botão "Compartilhar nos Stories" (gera a imagem 1080×1920) ──
function ShareStoriesButton({ t, code }) {
  const [busy, setBusy] = useStateAnalise(false);
  const onShare = async () => {
    if (busy) return;
    setBusy(true);
    try {
      if (typeof compartilharResultado === "function") await compartilharResultado(code);
    } catch (e) {}
    setBusy(false);
  };
  return (
    <button onClick={onShare} disabled={busy} style={{
      marginTop: 12, width: "100%",
      display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
      padding: "15px 18px", cursor: busy ? "default" : "pointer",
      background: "transparent", border: `1px solid ${t.border}`,
      borderRadius: RADIUS.md, color: t.ink2,
      fontFamily: TYPE.sans, fontSize: 12.5, fontWeight: 700,
      letterSpacing: "0.1em", textTransform: "uppercase",
    }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><path d="M16 6l-4-4-4 4"/><path d="M12 2v13"/>
      </svg>
      {busy ? "Gerando imagem..." : "Compartilhar nos Stories"}
    </button>
  );
}

// ── estilos compartilhados ──────────────────────────────────
function primaryBtn(t) {
  return {
    width: "100%", marginTop: 26, padding: "18px",
    background: t.ink1, color: t.bg0, border: "none", borderRadius: RADIUS.md,
    cursor: "pointer", fontFamily: TYPE.sans, fontSize: 14, fontWeight: 800,
    letterSpacing: "0.12em", textTransform: "uppercase",
  };
}
function primaryBtnInline(t) {
  return {
    padding: "16px 22px", background: t.ink1, color: t.bg0, border: "none", borderRadius: RADIUS.md,
    cursor: "pointer", fontFamily: TYPE.sans, fontSize: 13, fontWeight: 800,
    letterSpacing: "0.1em", textTransform: "uppercase",
  };
}
function optBtn(t, sel, withBox) {
  return {
    width: "100%", padding: withBox ? "15px 16px" : "16px 18px",
    background: sel ? t.accentMuted : t.bg1,
    border: `1.5px solid ${sel ? t.accent : t.border}`, borderRadius: RADIUS.md,
    color: sel ? t.ink1 : t.ink2, cursor: "pointer",
    fontFamily: TYPE.sans, fontSize: 14.5, fontWeight: 600, lineHeight: 1.4,
    textAlign: withBox ? "left" : "center",
    display: "flex", alignItems: "center", gap: 12,
    justifyContent: withBox ? "flex-start" : "center",
    transition: "border-color .12s ease, background .12s ease",
  };
}

Object.assign(window, { AnaliseScreen });
