// ============================================
// Shared components: Header, Footer, FloatingWA, LeadModal, Reveal, Accordion
// ============================================

const { useState, useEffect, useRef, useCallback } = React;

const WA_NUMBER = "5511942107127";
const WA_MSG = encodeURIComponent(
  "Olá! Vim pelo site do Albuini Advogados e gostaria de fazer a análise gratuita do meu contrato."
);
const WA_LINK = `https://wa.me/${WA_NUMBER}?text=${WA_MSG}`;

// ---- Reveal on scroll ----
function Reveal({ children, delay = 0, as: As = "div", className = "", ...props }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);

  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setShown(true);
            obs.disconnect();
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -60px 0px" }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  const delayClass = delay ? `delay-${delay}` : "";
  return (
    <As
      ref={ref}
      className={`reveal ${shown ? "in" : ""} ${delayClass} ${className}`}
      {...props}
    >
      {children}
    </As>
  );
}

// ---- Brand mark / logo ----
function BrandMark({ size = 38 }) {
  return (
    <img
      src="assets/logo-albuini.png"
      alt="Albuini Advogados"
      className="brand-mark"
      style={{ width: size, height: size }}
    />
  );
}

// ---- Header ----
function Header({ openModal }) {
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header className={`site-header ${scrolled ? "scrolled" : ""}`}>
      <div className="container inner">
        <a href="#top" className="brand" aria-label="Albuini Advogados — Página inicial">
          <BrandMark size={36} />
          <div>
            <div className="brand-text">ALBUINI</div>
            <div className="brand-sub">Advogados</div>
          </div>
        </a>

        <nav className="nav-links">
          <a href="#metodo">Método</a>
          <a href="#resultados">Resultados</a>
          <a href="#simulador">Simulador</a>
          <a href="blog/index.html">Blog</a>
          <a href="#faq">Perguntas</a>
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <span className="header-oab">OAB/SP 504.166</span>
          <button className="header-cta" onClick={openModal}>
            Começar agora
            <span style={{ fontSize: 16, lineHeight: 1 }}>→</span>
          </button>
        </div>
      </div>
    </header>
  );
}

// ---- Floating WhatsApp ----
function FloatingWA() {
  const [shown, setShown] = useState(false);

  useEffect(() => {
    const onScroll = () => setShown(window.scrollY > 600);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  if (!shown) return null;

  return (
    <a
      className="fab-wa"
      href={WA_LINK}
      target="_blank"
      rel="noopener noreferrer"
      aria-label="Falar no WhatsApp"
    >
      <span className="fab-wa-icon">
        <svg viewBox="0 0 24 24" fill="white">
          <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.2 5.1 4.5.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 1.9-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.6-.3z"/>
          <path d="M12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.7 1.5 5.3L2 22l4.8-1.5c1.5.8 3.3 1.3 5.2 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18.2c-1.7 0-3.3-.5-4.7-1.3l-.3-.2-3.4 1 1-3.3-.2-.3c-.9-1.4-1.4-3.1-1.4-4.9 0-5 4-9 9-9s9 4 9 9-4 9-9 9z"/>
        </svg>
      </span>
      <span className="fab-wa-text">Falar no WhatsApp</span>
    </a>
  );
}

// ---- Accordion (reusable for objections + FAQ) ----
function Accordion({ items, allowMultiple = false }) {
  const [open, setOpen] = useState(new Set());
  const refs = useRef({});

  const toggle = (i) => {
    setOpen((prev) => {
      const next = allowMultiple ? new Set(prev) : new Set();
      if (prev.has(i)) next.delete(i);
      else next.add(i);
      return next;
    });
  };

  // markdown-lite for **bold**
  const renderText = (text) => {
    const parts = text.split(/(\*\*[^*]+\*\*)/g);
    return parts.map((p, idx) => {
      if (p.startsWith("**") && p.endsWith("**")) {
        return <strong key={idx}>{p.slice(2, -2)}</strong>;
      }
      return <React.Fragment key={idx}>{p}</React.Fragment>;
    });
  };

  return (
    <div className="obj-list">
      {items.map((item, i) => {
        const isOpen = open.has(i);
        return (
          <div key={i} className={`obj-item ${isOpen ? "open" : ""}`}>
            <button
              className="obj-q"
              onClick={() => toggle(i)}
              aria-expanded={isOpen}
            >
              <span>{item.q}</span>
              <span className="icon" aria-hidden="true"></span>
            </button>
            <div
              className="obj-a"
              style={{
                maxHeight: isOpen
                  ? (refs.current[i]?.scrollHeight || 600) + "px"
                  : 0
              }}
            >
              <div className="obj-a-inner" ref={(el) => (refs.current[i] = el)}>
                {renderText(item.a)}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---- Lead Modal (multi-step form) ----
function LeadModal({ open, onClose }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    name: "",
    phone: "",
    debt: "",
    type: "",
    consent: false
  });
  const [submitted, setSubmitted] = useState(false);

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

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape" && open) onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const canAdvance = () => {
    if (step === 0) return data.name.trim().length >= 2;
    if (step === 1) return !!data.type;
    if (step === 2) return data.debt.trim().length > 0;
    if (step === 3) return data.phone.replace(/\D/g, "").length >= 10 && data.consent;
    return true;
  };

  const next = () => {
    if (step < 3) setStep(step + 1);
    else submit();
  };

  const back = () => {
    if (step > 0) setStep(step - 1);
  };

  const submit = () => {
    // In production, would POST somewhere. Here just simulate success.
    setSubmitted(true);
    setTimeout(() => {
      const msg = encodeURIComponent(
        `Olá! Sou ${data.name}. Vim pelo site do Albuini Advogados e gostaria de fazer a análise gratuita do meu contrato.\n\n` +
          `Tipo: ${data.type}\nValor aproximado da dívida: R$ ${data.debt}\nTelefone: ${data.phone}`
      );
      window.open(`https://wa.me/${WA_NUMBER}?text=${msg}`, "_blank");
    }, 900);
  };

  const formatBRL = (v) => {
    const clean = v.replace(/\D/g, "");
    if (!clean) return "";
    return Number(clean).toLocaleString("pt-BR");
  };

  const formatPhone = (v) => {
    const c = v.replace(/\D/g, "").slice(0, 11);
    if (c.length <= 2) return c;
    if (c.length <= 7) return `(${c.slice(0, 2)}) ${c.slice(2)}`;
    if (c.length <= 10) return `(${c.slice(0, 2)}) ${c.slice(2, 6)}-${c.slice(6)}`;
    return `(${c.slice(0, 2)}) ${c.slice(2, 7)}-${c.slice(7)}`;
  };

  return (
    <div
      className={`modal-overlay ${open ? "open" : ""}`}
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="modal" role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Fechar">
          ✕
        </button>

        {submitted ? (
          <div className="modal-success">
            <div className="checkmark"></div>
            <div className="modal-title">Pronto, {data.name.split(" ")[0]}.</div>
            <p style={{ color: "var(--muted)", marginTop: 16, lineHeight: 1.6 }}>
              Te redirecionamos pro WhatsApp em instantes pra você concluir o envio
              dos documentos. Resposta da análise em até <strong style={{color: "var(--ink)"}}>5 dias úteis</strong>, sem
              compromisso.
            </p>
            <p style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--muted)", marginTop: 32 }}>
              OAB/SP 504.166
            </p>
          </div>
        ) : (
          <>
            <div className="modal-progress">
              {[0, 1, 2, 3].map((i) => (
                <div
                  key={i}
                  className={`dot ${i === step ? "active" : ""} ${i < step ? "done" : ""}`}
                ></div>
              ))}
            </div>

            <div className="modal-step-label">Etapa {step + 1} de 4</div>

            {step === 0 && (
              <>
                <h3 className="modal-title">Como podemos te chamar?</h3>
                <p className="modal-sub">
                  Análise gratuita do contrato em até 5 dias úteis. Sem compromisso.
                </p>
                <div className="form-field">
                  <label>Nome completo</label>
                  <input
                    type="text"
                    autoFocus
                    value={data.name}
                    onChange={(e) => update("name", e.target.value)}
                    placeholder="Seu nome"
                  />
                </div>
              </>
            )}

            {step === 1 && (
              <>
                <h3 className="modal-title">Qual é o tipo de dívida, {data.name.split(" ")[0]}?</h3>
                <p className="modal-sub">
                  Atuamos especificamente em direito bancário. Selecione abaixo:
                </p>
                <div className="form-radio-group">
                  {window.CONTRACT_TYPES.map((t) => (
                    <label key={t} className="form-radio">
                      <input
                        type="radio"
                        name="type"
                        checked={data.type === t}
                        onChange={() => update("type", t)}
                      />
                      <span className="circle"></span>
                      <span>{t}</span>
                    </label>
                  ))}
                </div>
              </>
            )}

            {step === 2 && (
              <>
                <h3 className="modal-title">Valor aproximado da dívida?</h3>
                <p className="modal-sub">
                  Estimativa do saldo devedor atual. Usado só pra estimar o caso —
                  você confirma na análise.
                </p>
                <div className="form-field">
                  <label>Saldo devedor estimado</label>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8, borderBottom: "1px solid var(--ink)", paddingBottom: 8 }}>
                    <span style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--muted)" }}>R$</span>
                    <input
                      type="text"
                      inputMode="numeric"
                      autoFocus
                      value={formatBRL(data.debt)}
                      onChange={(e) => update("debt", e.target.value.replace(/\D/g, ""))}
                      placeholder="0"
                      style={{ fontSize: 28, fontFamily: "var(--serif)", border: "none", paddingBottom: 4, color: "var(--ink)", background: "transparent", outline: "none", flex: 1 }}
                    />
                  </div>
                </div>
              </>
            )}

            {step === 3 && (
              <>
                <h3 className="modal-title">Pra onde devolvemos com o diagnóstico?</h3>
                <p className="modal-sub">
                  Vamos te chamar no WhatsApp pra receber os documentos e confirmar o caso.
                </p>
                <div className="form-field">
                  <label>WhatsApp</label>
                  <input
                    type="tel"
                    autoFocus
                    value={formatPhone(data.phone)}
                    onChange={(e) => update("phone", e.target.value.replace(/\D/g, ""))}
                    placeholder="(11) 99999-9999"
                  />
                </div>

                <label className="form-consent">
                  <input
                    type="checkbox"
                    checked={data.consent}
                    onChange={(e) => update("consent", e.target.checked)}
                  />
                  <span>
                    Ao enviar meus dados, autorizo o tratamento conforme a{" "}
                    <a href="#privacy">Política de Privacidade</a> e a LGPD. Os
                    dados serão usados exclusivamente para análise do meu caso.
                  </span>
                </label>
              </>
            )}

            <div className="modal-actions">
              {step > 0 ? (
                <button className="back" onClick={back}>
                  ← Voltar
                </button>
              ) : (
                <span></span>
              )}
              <button
                className="btn btn-primary"
                onClick={next}
                disabled={!canAdvance()}
                style={{
                  opacity: canAdvance() ? 1 : 0.4,
                  cursor: canAdvance() ? "pointer" : "not-allowed"
                }}
              >
                {step === 3 ? "Enviar e abrir WhatsApp" : "Continuar"}
                <span className="arrow"></span>
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ---- Footer ----
function Footer() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <img
              src="assets/logo-albuini.png"
              alt="Albuini Advogados"
              className="footer-brand-mark"
            />
            <div className="footer-name">ALBUINI ADVOGADOS</div>
            <address className="footer-addr">
              Av. Guapira, 1234, sala 16<br/>
              Tucuruvi, São Paulo/SP<br/>
              CEP 02265-002
            </address>
          </div>

          <div className="footer-col">
            <h4>Contato</h4>
            <ul>
              <li><a href={WA_LINK} target="_blank" rel="noopener noreferrer">WhatsApp · (11) 94210-7127</a></li>
              <li><a href="mailto:comercial@albuiniadvbancario.com.br">comercial@albuiniadvbancario.com.br</a></li>
              <li><a href="#">Google Meu Negócio</a></li>
              <li><a href="#">LinkedIn</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Navegação</h4>
            <ul>
              <li><a href="#metodo">Método</a></li>
              <li><a href="#resultados">Resultados</a></li>
              <li><a href="#simulador">Simulador</a></li>
              <li><a href="blog/index.html">Blog · Matérias</a></li>
              <li><a href="#objecoes">Dúvidas frequentes</a></li>
              <li><a href="#faq">FAQ completo</a></li>
            </ul>
          </div>

          <div className="footer-col">
            <h4>Legal</h4>
            <ul>
              <li><a href="#privacy">Política de Privacidade</a></li>
              <li><a href="#terms">Termos de Uso</a></li>
              <li><a href="#">Provimento 205/2021 OAB</a></li>
              <li><a href="#">LGPD</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <p className="footer-legal">
            Em conformidade com o Provimento 205/2021 da OAB. Este site tem
            caráter meramente informativo, não constitui captação de clientela
            e não promete resultados, que dependem de análise técnica
            individualizada de cada caso. Depoimentos exibidos com autorização
            de uso dos clientes; percentuais e prazos variam por caso.
          </p>
          <div className="footer-meta">
            <span>© 2026 Albuini Advogados · OAB/SP 504.166</span>
            <span>Todos os direitos reservados</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Reveal, BrandMark, Header, FloatingWA, Accordion, LeadModal, Footer,
  WA_LINK, WA_NUMBER
});
