// interactive.jsx. Pool calculator, checkout flow, animated counters
const { useState, useEffect, useRef, useMemo } = React;

/* ──────────────────────────────────────────────────────────────
   AnimatedNumber. counts up to target when in view
   ────────────────────────────────────────────────────────────── */
function AnimatedNumber({ value, prefix = "", suffix = "", duration = 1200, decimals = 0, format }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const t0 = performance.now();
          const step = (t) => {
            const p = Math.min(1, (t - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(value * eased);
            if (p < 1) requestAnimationFrame(step);
            else setN(value);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);

  const display = format ? format(n) : n.toFixed(decimals);
  return <span ref={ref} className="num">{prefix}{display}{suffix}</span>;
}

/* ──────────────────────────────────────────────────────────────
   PoolCalculator. interactive widget in the hero
   ────────────────────────────────────────────────────────────── */
function PoolCalculator({ onCta, variant = "vertical" }) {
  const [amount, setAmount] = useState(500);
  const fmtUSD = (v) =>
    v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  const periods = [
    { rate: 0.01, period: "/ dia", label: "1%" },
    { rate: 0.07, period: "/ Mês", label: "7%" },
    { rate: 0.33, period: "/ ano", label: "33%" },
  ];

  const chips = [100, 500, 1000, 5000];

  return (
    <div className={`pool pool--${variant}`} aria-label="Calculadora de pool">
      <div className="pool-head">
        <span className="pool-title">Simulador de pool</span>
        <span className="pool-live">ao vivo</span>
      </div>

      <div className="pool-input">
        <label>
          <span>Quanto você quer aportar?</span>
          <span className="hint">USD</span>
        </label>
        <div className="field">
          <span className="prefix">$</span>
          <input
            type="number"
            min="0"
            value={amount}
            onChange={(e) => setAmount(Math.max(0, Number(e.target.value) || 0))}
            inputMode="decimal"
          />
        </div>
        <div className="chips">
          {chips.map((c) => (
            <button
              key={c}
              className="chip"
              aria-pressed={amount === c}
              onClick={() => setAmount(c)}
            >
              ${c.toLocaleString()}
            </button>
          ))}
        </div>
      </div>

      <div className="rate-cells">
        {periods.map((p, i) => (
          <div className="rate-cell" key={i}>
            <span className="pct">{p.label}</span>
            <span className="period">{p.period}</span>
            <span className="usd">${fmtUSD(amount * p.rate)}</span>
          </div>
        ))}
      </div>

      <p className="pool-foot">
        Simulação ilustrativa. Taxas de pool variam por liquidez, par e momento de mercado. Não é garantia de rendimento.
      </p>

      <a className="btn btn--primary btn--block" href="https://hub.la/r/metododtd" target="_blank" rel="noopener">
        Quero montar minha pool →
      </a>
    </div>
  );
}

function buildSpark() { return ""; } // legacy, unused after refactor

/* ──────────────────────────────────────────────────────────────
   CheckoutModal. multi-step simulated flow
   ────────────────────────────────────────────────────────────── */
function CheckoutModal({ onClose }) {
  const [step, setStep] = useState(0); // 0 method, 1 details, 2 success
  const [method, setMethod] = useState("card");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  const next = () => setStep((s) => s + 1);
  const submit = (e) => {
    e.preventDefault();
    setLoading(true);
    setTimeout(() => { setLoading(false); setStep(2); }, 1100);
  };

  return (
    <div className="modal-veil" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Checkout Método DTD">
        <div className="modal-head">
          <h4>Entrar no Método DTD</h4>
          <button className="x" onClick={onClose} aria-label="Fechar">✕</button>
        </div>

        <div className="modal-body">
          <div className="steps" aria-hidden>
            <div className={`step ${step >= 0 ? (step > 0 ? "done" : "active") : ""}`} />
            <div className={`step ${step >= 1 ? (step > 1 ? "done" : "active") : ""}`} />
            <div className={`step ${step >= 2 ? "active" : ""}`} />
          </div>

          {step === 0 && (
            <>
              <div>
                <div className="modal-h">Escolha a forma de pagamento</div>
                <div className="modal-p" style={{ marginTop: 4 }}>R$ 867,35 à vista &middot; ou 12x de R$ 89,70.</div>
              </div>
              <div className="pay-opts">
                <button className="pay-opt" aria-pressed={method === "card"} onClick={() => setMethod("card")}>
                  <span className="icon">💳</span>
                  <span className="meta">
                    <div className="t">Cartão de crédito</div>
                    <div className="s">12x de R$ 89,70 sem juros</div>
                  </span>
                  <span className="radio" />
                </button>
                <button className="pay-opt" aria-pressed={method === "pix"} onClick={() => setMethod("pix")}>
                  <span className="icon">PIX</span>
                  <span className="meta">
                    <div className="t">Pix à vista</div>
                    <div className="s gold">R$ 867,35 · confirmação instantânea</div>
                  </span>
                  <span className="radio" />
                </button>
                <button className="pay-opt" aria-pressed={method === "boleto"} onClick={() => setMethod("boleto")}>
                  <span className="icon">B</span>
                  <span className="meta">
                    <div className="t">Boleto</div>
                    <div className="s">Compensação em até 3 dias úteis</div>
                  </span>
                  <span className="radio" />
                </button>
              </div>
              <button className="btn btn--primary btn--block" onClick={next}>Continuar →</button>
              <div style={{ display: "flex", gap: 12, justifyContent: "center", fontSize: 12, color: "var(--text-3)", fontFamily: "var(--font-mono)" }}>
                <span>🔒 Pagamento seguro</span>
                <span>Garantia 7 dias</span>
              </div>
            </>
          )}

          {step === 1 && (
            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div>
                <div className="modal-h">Seus dados</div>
                <div className="modal-p" style={{ marginTop: 4 }}>Acesso será liberado nesse e-mail.</div>
              </div>
              <input className="text" type="text" placeholder="Nome completo" required />
              <input className="text" type="email" placeholder="seu@email.com" required />
              <div className="modal-row">
                <input className="text" type="tel" placeholder="WhatsApp" required />
                <input className="text" type="text" placeholder="CPF" required />
              </div>
              {method === "card" && (
                <>
                  <input className="text" type="text" placeholder="Número do cartão" required />
                  <div className="modal-row">
                    <input className="text" type="text" placeholder="Validade MM/AA" required />
                    <input className="text" type="text" placeholder="CVV" required />
                  </div>
                </>
              )}
              <button className="btn btn--primary btn--block" disabled={loading}>
                {loading ? "Processando…" : "Finalizar e ganhar em dólar →"}
              </button>
              <button type="button" onClick={() => setStep(0)} style={{ background: "none", border: "none", color: "var(--text-3)", fontSize: 12, cursor: "pointer", textDecoration: "underline" }}>
                ← voltar
              </button>
            </form>
          )}

          {step === 2 && (
            <div style={{ textAlign: "center", padding: "10px 0 20px" }}>
              <div className="success-anim">
                <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              </div>
              <div className="modal-h" style={{ marginBottom: 8 }}>Bem-vindo ao Método DTD</div>
              <div className="modal-p">
                Esse é apenas um protótipo. Em produção, aqui você cairia na área de membros, com acesso imediato às aulas e ao grupo VIP no WhatsApp.
              </div>
              <button className="btn btn--ghost btn--block" style={{ marginTop: 18 }} onClick={onClose}>Fechar</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────
   FAQ. accordion with single-open behavior
   ────────────────────────────────────────────────────────────── */
function FAQ({ items }) {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq-list">
      {items.map((it, i) => (
        <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
            <span className="num">{String(i + 1).padStart(2, "0")}</span>
            <span className="text">{it.q}</span>
            <span className="toggle" aria-hidden>+</span>
          </button>
          <div className="faq-a">{it.a}</div>
        </div>
      ))}
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────
   Reveal on scroll helper
   ────────────────────────────────────────────────────────────── */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("visible");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.1 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* expose to global */
Object.assign(window, { AnimatedNumber, PoolCalculator, CheckoutModal, FAQ, useReveal, FallingPattern });

/* ──────────────────────────────────────────────────────────────
   FallingPattern — subtle "falling code" backdrop
   Pure CSS animation (keyframes in styles.css), no framer-motion.
   ────────────────────────────────────────────────────────────── */
function FallingPattern({ color = "var(--accent)", bgColor = "var(--bg)", duration = 200, blur = "1em", density = 1.4 }) {
  const bgImage = useMemo(() => {
    const lines = [];
    const rowYs = [
      [235, 117.5], [252, 126], [150, 75], [253, 126.5], [204, 102],
      [134, 67],   [179, 89.5], [299, 149.5], [215, 107.5], [281, 140.5],
      [158, 79],   [210, 105],
    ];
    rowYs.forEach(([streak, dot]) => {
      lines.push(`radial-gradient(4px 100px at 0px ${streak}px, ${color}, transparent)`);
      lines.push(`radial-gradient(4px 100px at 300px ${streak}px, ${color}, transparent)`);
      lines.push(`radial-gradient(1.5px 1.5px at 150px ${dot}px, ${color} 100%, transparent 150%)`);
    });
    return lines.join(", ");
  }, [color]);

  const bgSizes = useMemo(() => {
    const sizes = [235, 252, 150, 253, 204, 134, 179, 299, 215, 281, 158, 210];
    return sizes.flatMap((h) => [`300px ${h}px`, `300px ${h}px`, `300px ${h}px`]).slice(0, 35).join(", ");
  }, []);

  return (
    <div className="fp-root" style={{ "--fp-duration": `${duration}s`, "--fp-blur": blur }}>
      <div
        className="fp-stream"
        style={{
          backgroundImage: bgImage,
          backgroundSize: bgSizes,
        }}
      />
      <div
        className="fp-overlay"
        style={{
          backgroundImage: `radial-gradient(circle at 50% 50%, transparent 0, transparent 2px, ${bgColor} 2px)`,
          backgroundSize: `${8 * density}px ${8 * density}px`,
        }}
      />
      <div className="fp-mask" />
    </div>
  );
}
