/* ============================================================
   5. Análise de Crédito — formulário conversacional
   ============================================================ */

const Q = [
  {
    key: "renda", icon: Icons.coins,
    q: "Qual é a sua renda mensal aproximada?",
    hint: "Pode ser a renda da família somada — é o que define sua faixa no Minha Casa Minha Vida.",
    options: [
      "Até R$ 3.200",
      "R$ 3.200 a R$ 5.000",
      "R$ 5.000 a R$ 9.600",
      "R$ 9.600 a R$ 13.000",
      "Acima de R$ 13.000",
    ],
    faixa: {
      "Até R$ 3.200": "Faixa 1",
      "R$ 3.200 a R$ 5.000": "Faixa 2",
      "R$ 5.000 a R$ 9.600": "Faixa 3",
      "R$ 9.600 a R$ 13.000": "Faixa 4",
      "Acima de R$ 13.000": "Acima do MCMV",
    },
  },
  {
    key: "fgts", icon: Icons.shield,
    q: "Você tem FGTS disponível?",
    hint: "Ele pode virar entrada ou reduzir bastante as parcelas.",
    options: ["Sim, tenho", "Não tenho", "Não sei dizer"],
  },
  {
    key: "regiao", icon: Icons.pin,
    q: "Em qual região de São Paulo você sonha em morar?",
    hint: "Atuo na capital inteira — escolha onde faz sentido pra sua vida.",
    options: ["Zona Sul", "Zona Norte", "Zona Leste", "Zona Oeste", "Centro", "Ainda estou decidindo"],
  },
  {
    key: "tentou", icon: Icons.doc,
    q: "Você já tentou financiar antes?",
    hint: "Não tem resposta errada. Cada perfil tem um caminho.",
    options: ["Nunca tentei", "Sim, e não consegui", "Sim, e deu certo"],
  },
  {
    key: "whats", icon: Icons.whats, input: true,
    q: "Para onde envio sua análise?",
    hint: "Mando o resultado direto no seu WhatsApp, sem custo e sem compromisso.",
  },
];

function maskPhone(v) {
  const d = v.replace(/\D/g, "").slice(0, 11);
  if (d.length <= 2) return d.replace(/(\d{0,2})/, "($1");
  if (d.length <= 7) return d.replace(/(\d{2})(\d{0,5})/, "($1) $2");
  return d.replace(/(\d{2})(\d{5})(\d{0,4})/, "($1) $2-$3");
}

function CreditForm() {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [phone, setPhone] = useState("");
  const [fgtsValor, setFgtsValor] = useState("");
  const [dir, setDir] = useState(1);
  const done = step >= Q.length;
  const total = Q.length;
  const progress = done ? 100 : Math.round((step / total) * 100);

  const pick = (key, val) => {
    setAnswers((a) => ({ ...a, [key]: val }));
    setDir(1);
    // FGTS: ao escolher "Sim, tenho", não avança — abre campo para o valor
    if (key === "fgts" && val === "Sim, tenho") return;
    setTimeout(() => setStep((s) => s + 1), 160);
  };

  const submitFgts = () => { setDir(1); setStep((s) => s + 1); };

  const submitPhone = () => {
    const digits = phone.replace(/\D/g, "");
    if (digits.length < 10) return;
    setAnswers((a) => ({ ...a, whats: phone }));
    setDir(1);
    setStep((s) => s + 1);
  };

  const back = () => { if (step > 0) { setDir(-1); setStep((s) => s - 1); } };
  const restart = () => { setAnswers({}); setPhone(""); setFgtsValor(""); setStep(0); setDir(1); };

  const fgtsLabel = answers.fgts === "Sim, tenho" && fgtsValor.trim()
    ? `Sim — ${fgtsValor.trim()}` : answers.fgts;

  const rendaFaixa = Q[0].faixa?.[answers.renda];
  const resultMsg =
    `Olá Wanderson! Acabei de fazer a análise no site.\n\n` +
    `- Renda mensal: ${answers.renda || "-"}${rendaFaixa ? ` (${rendaFaixa})` : ""}\n` +
    `- FGTS: ${fgtsLabel || "-"}\n` +
    `- Região desejada: ${answers.regiao || "-"}\n` +
    `- Já tentou financiar: ${answers.tentou || "-"}\n\n` +
    `Gostaria de entender minhas possibilidades de aprovação.`;

  const cur = Q[step];

  return (
    <section className="section analise" id="analise">
      <div className="glow" style={{ width: 600, height: 600, top: "10%", right: "-12%", background: "radial-gradient(circle, var(--gold-glow), transparent 66%)", opacity: 0.4 }} />
      <div className="wrap analise-grid">
        {/* LEFT — copy / objeções */}
        <div className="analise-copy">
          <Reveal><span className="kicker">Análise de crédito</span></Reveal>
          <Reveal as="h2" delay={1} className="sec-title">
            Descubra suas <span className="gold-ital">possibilidades</span> de aprovação.
          </Reveal>
          <Reveal as="p" delay={2} className="sec-sub">
            Muitas pessoas acham que não conseguem financiar. Mas existem
            possibilidades que talvez você ainda não conheça.
          </Reveal>
          <Reveal delay={3} className="analise-reassure">
            {[
              ["1 minuto", "Cinco perguntas simples, sem documento nenhum."],
              ["Sem banco, sem robô", "Quem te responde é o Wanderson, pessoalmente."],
              ["Sem compromisso", "Você só avança se sentir segurança."],
            ].map(([t, d], i) => (
              <div key={i} className="reassure-item">
                <span className="reassure-check" style={{ width: 18, height: 18 }}>{Icons.check}</span>
                <div><strong>{t}</strong><span>{d}</span></div>
              </div>
            ))}
          </Reveal>
        </div>

        {/* RIGHT — card interativo */}
        <Reveal delay={2} className="analise-card-wrap">
          <div className="analise-card glass">
            <div className="ac-top">
              <div className="ac-top-l">
                <div className="ac-top-txt">
                  <strong>Análise rápida</strong>
                  <em>{done ? "Concluído" : `Passo ${step + 1} de ${total}`}</em>
                </div>
              </div>
              {!done && step > 0 && (
                <button className="ac-back" onClick={back} aria-label="Voltar">
                  <span style={{ width: 16, height: 16, transform: "rotate(180deg)", display: "block" }}>{Icons.arrow}</span>
                </button>
              )}
            </div>

            <div className="ac-progress"><i style={{ width: `${progress}%` }} /></div>

            <div className="ac-body">
              {!done && (
                <div key={step} className={`ac-step ${dir > 0 ? "from-right" : "from-left"}`}>
                  <div className="ac-q-ico" style={{ width: 30, height: 30 }}>{cur.icon}</div>
                  <h3 className="ac-q">{cur.q}</h3>
                  <p className="ac-hint">{cur.hint}</p>

                  {cur.input ? (
                    <div className="ac-input-block">
                      <div className="ac-input">
                        <span className="ac-input-ico">📱</span>
                        <input
                          type="tel" inputMode="numeric" placeholder="(11) 99999-9999"
                          value={phone}
                          onChange={(e) => setPhone(maskPhone(e.target.value))}
                          onKeyDown={(e) => e.key === "Enter" && submitPhone()}
                          autoFocus
                        />
                      </div>
                      <button
                        className="btn btn-gold btn-block"
                        disabled={phone.replace(/\D/g, "").length < 10}
                        onClick={submitPhone}
                      >
                        Ver minhas possibilidades
                        <span style={{ width: 18, height: 18 }}>{Icons.arrow}</span>
                      </button>
                    </div>
                  ) : (
                    <div className="ac-options">
                      {cur.options.map((opt) => (
                        <button
                          key={opt}
                          className={`ac-opt ${answers[cur.key] === opt ? "sel" : ""}`}
                          onClick={() => pick(cur.key, opt)}
                        >
                          <span>{opt}</span>
                          <span className="ac-opt-arrow" style={{ width: 16, height: 16 }}>{Icons.arrow}</span>
                        </button>
                      ))}

                      {cur.key === "fgts" && answers.fgts === "Sim, tenho" && (
                        <div className="ac-followup">
                          <label>Se sim, quanto?</label>
                          <div className="ac-input">
                            <span className="ac-input-ico">R$</span>
                            <input
                              type="text" inputMode="numeric" placeholder="Valor aproximado"
                              value={fgtsValor}
                              onChange={(e) => setFgtsValor(e.target.value)}
                              onKeyDown={(e) => e.key === "Enter" && submitFgts()}
                              autoFocus
                            />
                          </div>
                          <button className="btn btn-gold btn-block" onClick={submitFgts}>
                            Continuar
                            <span style={{ width: 18, height: 18 }}>{Icons.arrow}</span>
                          </button>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}

              {done && (
                <div className="ac-result from-right">
                  <div className="ac-result-glow" />
                  <div className="ac-result-ico" style={{ width: 34, height: 34 }}>{Icons.spark}</div>
                  <h3 className="ac-result-title">
                    Encontramos possibilidades<br />interessantes para o seu perfil.
                  </h3>
                  <p className="ac-result-sub">
                    Com base nas suas respostas, há caminhos reais de aprovação dentro do
                    Minha Casa Minha Vida. Quero te mostrar quais — no detalhe.
                  </p>
                  <div className="ac-summary">
                    {[["Renda", answers.renda], ["FGTS", fgtsLabel], ["Região", answers.regiao], ["Tentou antes", answers.tentou]].map(([k, v]) => (
                      <div key={k} className="ac-sum-row"><span>{k}</span><strong>{v || "—"}</strong></div>
                    ))}
                  </div>
                  <a className="btn btn-wa btn-block btn-lg" href={waLink(resultMsg)} target="_blank" rel="noopener">
                    <span style={{ width: 19, height: 19 }}>{Icons.whats}</span>
                    Receber análise no WhatsApp
                  </a>
                  <button className="ac-restart" onClick={restart}>Refazer análise</button>
                </div>
              )}
            </div>

            <div className="ac-foot">
              <span style={{ width: 14, height: 14 }}>{Icons.shield}</span>
              Seus dados são usados só para te responder. Sem spam.
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function ExitIntentModal() {
  const [open, setOpen] = useState(false);
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [phone, setPhone] = useState("");
  const [fgtsValor, setFgtsValor] = useState("");
  const [dir, setDir] = useState(1);
  const shown = useRef(false);

  const done = step >= Q.length;
  const total = Q.length;
  const progress = done ? 100 : Math.round((step / total) * 100);

  useEffect(() => {
    const handler = (e) => {
      if (shown.current) return;
      if (e.clientY <= 5) {
        shown.current = true;
        setTimeout(() => setOpen(true), 120);
      }
    };
    document.addEventListener("mouseleave", handler);
    return () => document.removeEventListener("mouseleave", handler);
  }, []);

  useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const close = () => setOpen(false);

  const pick = (key, val) => {
    setAnswers((a) => ({ ...a, [key]: val }));
    setDir(1);
    if (key === "fgts" && val === "Sim, tenho") return;
    setTimeout(() => setStep((s) => s + 1), 160);
  };

  const submitFgts = () => { setDir(1); setStep((s) => s + 1); };

  const submitPhone = () => {
    const digits = phone.replace(/\D/g, "");
    if (digits.length < 10) return;
    setAnswers((a) => ({ ...a, whats: phone }));
    setDir(1);
    setStep((s) => s + 1);
  };

  const back = () => { if (step > 0) { setDir(-1); setStep((s) => s - 1); } };
  const restart = () => { setAnswers({}); setPhone(""); setFgtsValor(""); setStep(0); setDir(1); };

  const fgtsLabel = answers.fgts === "Sim, tenho" && fgtsValor.trim()
    ? `Sim — ${fgtsValor.trim()}` : answers.fgts;

  const rendaFaixa = Q[0].faixa?.[answers.renda];
  const resultMsg =
    `Olá Wanderson! Acabei de fazer a análise no site.\n\n` +
    `- Renda mensal: ${answers.renda || "-"}${rendaFaixa ? ` (${rendaFaixa})` : ""}\n` +
    `- FGTS: ${fgtsLabel || "-"}\n` +
    `- Região desejada: ${answers.regiao || "-"}\n` +
    `- Já tentou financiar: ${answers.tentou || "-"}\n\n` +
    `Gostaria de entender minhas possibilidades de aprovação.`;

  const cur = Q[step];

  if (!open) return null;

  return (
    <div
      className="exit-overlay"
      onClick={(e) => { if (e.target === e.currentTarget) close(); }}
    >
      <div className="exit-modal glass">
        <button className="exit-close" onClick={close} aria-label="Fechar">✕</button>

        <div className="exit-header">
          <div className="exit-ico" style={{ width: 42, height: 42 }}>{Icons.spark}</div>
          <h2 className="exit-title">
            Espera! Você ainda não descobriu<br />suas <span className="gold-ital">possibilidades</span> de aprovação.
          </h2>
          <p className="exit-sub">Leva 1 minuto. Pode mudar tudo.</p>
        </div>

        <div className="ac-top">
          <div className="ac-top-l">
            <div className="ac-top-txt">
              <strong>Análise rápida</strong>
              <em>{done ? "Concluído" : `Passo ${step + 1} de ${total}`}</em>
            </div>
          </div>
          {!done && step > 0 && (
            <button className="ac-back" onClick={back} aria-label="Voltar">
              <span style={{ width: 16, height: 16, transform: "rotate(180deg)", display: "block" }}>{Icons.arrow}</span>
            </button>
          )}
        </div>

        <div className="ac-progress"><i style={{ width: `${progress}%` }} /></div>

        <div className="ac-body">
          {!done && (
            <div key={step} className={`ac-step ${dir > 0 ? "from-right" : "from-left"}`}>
              <div className="ac-q-ico" style={{ width: 30, height: 30 }}>{cur.icon}</div>
              <h3 className="ac-q">{cur.q}</h3>
              <p className="ac-hint">{cur.hint}</p>

              {cur.input ? (
                <div className="ac-input-block">
                  <div className="ac-input">
                    <span className="ac-input-ico">📱</span>
                    <input
                      type="tel" inputMode="numeric" placeholder="(11) 99999-9999"
                      value={phone}
                      onChange={(e) => setPhone(maskPhone(e.target.value))}
                      onKeyDown={(e) => e.key === "Enter" && submitPhone()}
                      autoFocus
                    />
                  </div>
                  <button
                    className="btn btn-gold btn-block"
                    disabled={phone.replace(/\D/g, "").length < 10}
                    onClick={submitPhone}
                  >
                    Ver minhas possibilidades
                    <span style={{ width: 18, height: 18 }}>{Icons.arrow}</span>
                  </button>
                </div>
              ) : (
                <div className="ac-options">
                  {cur.options.map((opt) => (
                    <button
                      key={opt}
                      className={`ac-opt ${answers[cur.key] === opt ? "sel" : ""}`}
                      onClick={() => pick(cur.key, opt)}
                    >
                      <span>{opt}</span>
                      <span className="ac-opt-arrow" style={{ width: 16, height: 16 }}>{Icons.arrow}</span>
                    </button>
                  ))}

                  {cur.key === "fgts" && answers.fgts === "Sim, tenho" && (
                    <div className="ac-followup">
                      <label>Se sim, quanto?</label>
                      <div className="ac-input">
                        <span className="ac-input-ico">R$</span>
                        <input
                          type="text" inputMode="numeric" placeholder="Valor aproximado"
                          value={fgtsValor}
                          onChange={(e) => setFgtsValor(e.target.value)}
                          onKeyDown={(e) => e.key === "Enter" && submitFgts()}
                          autoFocus
                        />
                      </div>
                      <button className="btn btn-gold btn-block" onClick={submitFgts}>
                        Continuar
                        <span style={{ width: 18, height: 18 }}>{Icons.arrow}</span>
                      </button>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {done && (
            <div className="ac-result from-right">
              <div className="ac-result-glow" />
              <div className="ac-result-ico" style={{ width: 34, height: 34 }}>{Icons.spark}</div>
              <h3 className="ac-result-title">
                Encontramos possibilidades<br />interessantes para o seu perfil.
              </h3>
              <p className="ac-result-sub">
                Com base nas suas respostas, há caminhos reais de aprovação dentro do
                Minha Casa Minha Vida. Quero te mostrar quais — no detalhe.
              </p>
              <div className="ac-summary">
                {[["Renda", answers.renda], ["FGTS", fgtsLabel], ["Região", answers.regiao], ["Tentou antes", answers.tentou]].map(([k, v]) => (
                  <div key={k} className="ac-sum-row"><span>{k}</span><strong>{v || "—"}</strong></div>
                ))}
              </div>
              <a className="btn btn-wa btn-block btn-lg" href={waLink(resultMsg)} target="_blank" rel="noopener">
                <span style={{ width: 19, height: 19 }}>{Icons.whats}</span>
                Receber análise no WhatsApp
              </a>
              <button className="ac-restart" onClick={restart}>Refazer análise</button>
            </div>
          )}
        </div>

        <div className="ac-foot">
          <span style={{ width: 14, height: 14 }}>{Icons.shield}</span>
          Seus dados são usados só para te responder. Sem spam.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CreditForm, ExitIntentModal });
