// ============== Shared Layout: Nav + Footer + WA + Theme ==============
const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

const OBPC_PAGES = [
  { id: "home", label: "Início", href: "/" },
  { id: "sobre", label: "Sobre", href: "/sobre" },
  { id: "fundamentos", label: "Fundamentos", href: "/fundamentos" },
  {
    id: "ministerios", label: "Ministérios", href: "/ministerios",
    mega: [
      { label: "JUBRAC", sub: "Juventude 15–29", href: "/jubrac" },
      { label: "ADOBRAC", sub: "Adolescentes", href: "/ministerios#adobrac" },
      { label: "MENIBRAC", sub: "Crianças", href: "/ministerios#menibrac" },
      { label: "UFEBRAC", sub: "Mulheres", href: "/ministerios#ufebrac" },
      { label: "UMASBRAC", sub: "Homens", href: "/ministerios#umasbrac" },
      { label: "Louvor & Adoração", sub: "Ministério de música", href: "/ministerios#louvor" },
      { label: "Intercessão", sub: "Oração e jejum", href: "/ministerios#intercessao" },
      { label: "Missões", sub: "Evangelismo & plantação", href: "/ministerios#missoes" },
      { label: "Discipulado", sub: "Formação de líderes", href: "/ministerios#discipulado" },
    ],
  },
  { id: "agenda", label: "Agenda", href: "/agenda" },
  { id: "noticias", label: "Notícias", href: "/noticias" },
  { id: "galeria", label: "Galeria", href: "/galeria" },
  { id: "doacoes", label: "Dízimos & Ofertas", href: "/doacoes" },
  { id: "contato", label: "Contato", href: "/contato" },
];

const OBPC_PALETTES = {
  fire:  { bg: "#0f0a06", surface: "#1a100a", fg: "#f5ede0", muted: "rgba(245,237,224,0.6)", accent: "#ff5e1f" },
  deep:  { bg: "#07090e", surface: "#0f1420", fg: "#eef2f8", muted: "rgba(238,242,248,0.55)", accent: "#d4a259" },
  ivory: { bg: "#f5efe4", surface: "#ece4d4", fg: "#1a0f08", muted: "rgba(26,15,8,0.6)", accent: "#c8331a" },
  sober: { bg: "#12131a", surface: "#1b1d28", fg: "#eceaf0", muted: "rgba(236,234,240,0.55)", accent: "#8b6f47" },
  jub:   { bg: "#0a0815", surface: "#15102a", fg: "#f5eef7", muted: "rgba(245,238,247,0.6)", accent: "#7b3ff2" },
};

function usePalette(defaultId) {
  const [id, setId] = useStateL(() => {
    try { return localStorage.getItem("obpc.palette") || defaultId; } catch(e){ return defaultId; }
  });
  useEffectL(() => {
    try { localStorage.setItem("obpc.palette", id); } catch(e){}
    const p = OBPC_PALETTES[id] || OBPC_PALETTES.fire;
    document.body.style.background = p.bg;
    document.body.style.color = p.fg;
  }, [id]);
  const palette = OBPC_PALETTES[id] || OBPC_PALETTES.fire;
  return [palette, id, setId];
}

// ---------- Global Nav with mega dropdown ----------
const GlobalNav = ({ active, palette, paletteId, setPaletteId }) => {
  const [scrolled, setScrolled] = useStateL(false);
  const [openMega, setOpenMega] = useStateL(null);
  const [mobileOpen, setMobileOpen] = useStateL(false);

  useEffectL(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header className={`obpc-gnav ${scrolled ? "is-scrolled" : ""}`}
      style={{ color: palette.fg, "--accent": palette.accent, "--bg": palette.bg }}
      onKeyDown={(e) => { if (e.key === "Escape") { setOpenMega(null); setMobileOpen(false); } }}>
      <a href="/" className="obpc-gnav-brand">
        <span className="obpc-gnav-logo" style={{ borderColor: palette.accent }}>
          <span style={{ color: palette.accent }}>✝</span>
        </span>
        <span className="obpc-gnav-wordmark">
          <strong>OBPC</strong>
          <span style={{ color: palette.muted }}>O Brasil Para Cristo</span>
        </span>
      </a>

      <img src="/src/assets/logo.png" alt="Igreja O Brasil Para Cristo" className="obpc-gnav-logo-img"/>

      <nav className="obpc-gnav-links">
        {OBPC_PAGES.map((p) => (
          <div key={p.id} className="obpc-gnav-item"
            onMouseEnter={() => p.mega && setOpenMega(p.id)}
            onMouseLeave={() => p.mega && setOpenMega(null)}
            onFocus={() => p.mega && setOpenMega(p.id)}
            onBlur={(e) => { if (p.mega && !e.currentTarget.contains(e.relatedTarget)) setOpenMega(null); }}
          >
            <a href={p.href} className={`obpc-gnav-link ${active === p.id ? "is-active" : ""}`}
              aria-haspopup={p.mega ? "true" : undefined} aria-expanded={p.mega ? openMega === p.id : undefined}>
              {p.label}
              {p.mega && <span className="obpc-gnav-caret">▾</span>}
            </a>
            {p.mega && openMega === p.id && (
              <div className="obpc-gnav-mega" style={{ background: palette.surface, borderColor: `${palette.fg}15` }}>
                <div className="obpc-gnav-mega-head" style={{ color: palette.muted }}>
                  <span>Departamentos & ministérios</span>
                  <span>Todos →</span>
                </div>
                <div className="obpc-gnav-mega-grid">
                  {p.mega.map((m) => (
                    <a key={m.label} href={m.href} className="obpc-gnav-mega-card">
                      <strong>{m.label}</strong>
                      <span style={{ color: palette.muted }}>{m.sub}</span>
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        ))}
      </nav>

      <div className="obpc-gnav-right">
        <button type="button" className="obpc-gnav-theme" onClick={() => {
          const order = ["fire", "ivory", "deep", "sober", "jub"];
          const next = order[(order.indexOf(paletteId) + 1) % order.length];
          setPaletteId(next);
        }} title="Mudar paleta" aria-label="Mudar paleta de cores">
          <span style={{ background: palette.bg, borderColor: palette.fg }}/>
          <span style={{ background: palette.accent }}/>
        </button>
        <a href="/doacoes" className="obpc-gnav-donate" style={{ color: palette.accent, borderColor: `${palette.accent}66` }}>
          Contribuir
        </a>
        <button type="button" className="obpc-gnav-burger" onClick={() => setMobileOpen(!mobileOpen)}
          aria-label={mobileOpen ? "Fechar menu" : "Abrir menu"} aria-expanded={mobileOpen} aria-controls="obpc-menu-mobile">
          <span/><span/><span/>
        </button>
      </div>

      {mobileOpen && (
        <div id="obpc-menu-mobile" className="obpc-gnav-mobile" style={{ background: palette.bg, color: palette.fg }}>
          {OBPC_PAGES.map((p) => (
            <a key={p.id} href={p.href} className="obpc-gnav-mobile-link">{p.label}</a>
          ))}
          <a href="/doacoes" className="obpc-gnav-mobile-link" style={{ color: palette.accent }}>Contribuir</a>
        </div>
      )}
    </header>
  );
};

// ---------- Floating Actions (WhatsApp + Orar) ----------
const FloatingWA = ({ palette }) => {
  const [modalOpen, setModalOpen] = React.useState(false);
  const FORM_VAZIO = { nome: "", telefone: "", pedido: "", consentimento: false, _hp: "" };
  const [form, setForm] = React.useState(FORM_VAZIO);
  const [status, setStatus] = React.useState("idle");
  const [erroMsg, setErroMsg] = React.useState("");

  // Esc fecha o diálogo
  React.useEffect(() => {
    if (!modalOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setModalOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [modalOpen]);

  async function enviar(e) {
    e.preventDefault();
    if (!form.nome.trim()) { setStatus("error"); setErroMsg("Escreva seu nome."); return; }
    if (!form.pedido.trim()) { setStatus("error"); setErroMsg("Escreva o seu pedido de oração."); return; }
    if (!form.consentimento) { setStatus("error"); setErroMsg("Marque a autorização para enviar o pedido."); return; }
    setStatus("loading");
    setErroMsg("");
    const r = await window.salvarPedidoOracao({ ...form, origem: "site" });
    if (r.ok) { setStatus("success"); } else { setErroMsg(r.mensagem); setStatus("error"); }
  }

  const rotulo = { display: "block", fontFamily: "JetBrains Mono, monospace", fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: palette.accent, marginBottom: 4 };

  return (<>
    {/* Overlay */}
    {modalOpen && (
      <div onClick={() => setModalOpen(false)} aria-hidden="true" style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.6)",
        backdropFilter: "blur(4px)", zIndex: 998
      }}/>
    )}

    {/* Modal pedido de oração */}
    {modalOpen && (
      <div role="dialog" aria-modal="true" aria-labelledby="oracao-titulo" style={{
        position: "fixed", bottom: 100, right: 24, zIndex: 999,
        background: palette.surface, border: `1px solid ${palette.fg}15`,
        borderRadius: 16, padding: 28, width: 320,
        boxShadow: "0 20px 60px rgba(0,0,0,0.5)"
      }}>
        {status === "success" ? (
          <div style={{ textAlign: "center", padding: "16px 0" }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>🙏</div>
            <div style={{ fontFamily: "Fraunces, serif", fontSize: 20, fontWeight: 300, marginBottom: 8 }}>
              Pedido <em style={{ color: palette.accent }}>recebido!</em>
            </div>
            <p style={{ fontFamily: "Fraunces, serif", fontSize: 14, color: palette.muted, lineHeight: 1.6 }}>
              Nossa equipe de intercessão vai orar por você.
            </p>
            <button type="button" onClick={() => { setModalOpen(false); setStatus("idle"); setForm(FORM_VAZIO); }}
              style={{ marginTop: 20, fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: palette.accent, background: "none", border: "none", cursor: "pointer" }}>
              Fechar
            </button>
          </div>
        ) : (
          <form onSubmit={enviar}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
              <div>
                <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: palette.accent, marginBottom: 2 }}>Pedido de Oração</div>
                <div id="oracao-titulo" style={{ fontFamily: "Fraunces, serif", fontSize: 17, fontWeight: 300 }}>Estamos com você.</div>
              </div>
              <button type="button" onClick={() => setModalOpen(false)} aria-label="Fechar pedido de oração"
                style={{ background: "none", border: "none", color: palette.muted, fontSize: 20, cursor: "pointer", lineHeight: 1 }}>×</button>
            </div>

            {/* honeypot: invisível para pessoas, robôs preenchem */}
            <input type="text" name="website" tabIndex={-1} autoComplete="off" aria-hidden="true" value={form._hp}
              onChange={e => setForm(v => ({ ...v, _hp: e.target.value }))}
              style={{ position: "absolute", left: -9999, width: 1, height: 1, opacity: 0 }}/>

            {[
              { id: "nome", label: "Seu nome", placeholder: "Como você se chama?", type: "text", auto: "name" },
              { id: "telefone", label: "WhatsApp (opcional)", placeholder: "(11) 99999-9999", type: "tel", auto: "tel" },
            ].map(f => (
              <div key={f.id} style={{ marginBottom: 12 }}>
                <label htmlFor={`oracao-${f.id}`} style={rotulo}>{f.label}</label>
                <input id={`oracao-${f.id}`} type={f.type} placeholder={f.placeholder} value={form[f.id]} autoComplete={f.auto}
                  maxLength={f.id === "nome" ? 120 : 40}
                  onChange={e => setForm(v => ({ ...v, [f.id]: e.target.value }))}
                  style={{ width: "100%", background: `${palette.fg}08`, border: `1px solid ${palette.fg}15`, borderRadius: 8, padding: "10px 12px", fontFamily: "Fraunces, serif", fontSize: 14, color: palette.fg, outline: "none", boxSizing: "border-box" }}/>
              </div>
            ))}

            <div style={{ marginBottom: 12 }}>
              <label htmlFor="oracao-pedido" style={rotulo}>Pedido de oração</label>
              <textarea id="oracao-pedido" placeholder="Conte o que está no seu coração..." value={form.pedido} maxLength={2000}
                onChange={e => setForm(v => ({ ...v, pedido: e.target.value }))}
                rows={3} style={{ width: "100%", background: `${palette.fg}08`, border: `1px solid ${palette.fg}15`, borderRadius: 8, padding: "10px 12px", fontFamily: "Fraunces, serif", fontSize: 14, color: palette.fg, outline: "none", resize: "none", boxSizing: "border-box" }}/>
            </div>

            <label htmlFor="oracao-consentimento" style={{ display: "flex", gap: 8, alignItems: "flex-start", marginBottom: 14, fontFamily: "Fraunces, serif", fontSize: 12, lineHeight: 1.5, color: palette.muted, cursor: "pointer" }}>
              <input id="oracao-consentimento" type="checkbox" checked={form.consentimento} style={{ marginTop: 3, accentColor: palette.accent }}
                onChange={e => setForm(v => ({ ...v, consentimento: e.target.checked }))}/>
              <span>
                Li a <a href="/privacidade" target="_blank" rel="noopener noreferrer" style={{ color: palette.accent }}>Política de Privacidade</a> e
                autorizo o uso destes dados, inclusive o pedido de oração (que pode conter informação sensível), para oração e contato pela equipe da igreja.
              </span>
            </label>

            {status === "error" && (
              <div role="alert" style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, lineHeight: 1.5, color: "#ff8a80", marginBottom: 12 }}>
                {erroMsg || "Não foi possível enviar agora. Tente pelo WhatsApp."}
              </div>
            )}

            <button type="submit" disabled={status === "loading"} aria-busy={status === "loading"}
              style={{ width: "100%", padding: "12px", borderRadius: 999, border: "none", background: palette.accent, color: palette.bg, fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", cursor: "pointer", opacity: status === "loading" ? 0.5 : 1 }}>
              {status === "loading" ? "Enviando..." : "Enviar pedido"}
            </button>
          </form>
        )}
      </div>
    )}

    {/* Botão Orar — lado esquerdo */}
    <button onClick={() => { setModalOpen(!modalOpen); if (!modalOpen) window.trackInteracao && window.trackInteracao("abrir_oracao"); }}
      style={{ position: "fixed", bottom: 24, left: 24, zIndex: 997, display: "flex", alignItems: "center", gap: 8, padding: "10px 16px 10px 14px", borderRadius: 999, border: "none", background: palette.accent, color: palette.bg, cursor: "pointer", boxShadow: "0 4px 20px rgba(255,94,31,0.4)", fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", transition: "transform 200ms, box-shadow 200ms" }}
      onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 8px 28px rgba(255,94,31,0.5)"; }}
      onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "0 4px 20px rgba(255,94,31,0.4)"; }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>
      </svg>
      Quero orar
    </button>
    {/* WhatsApp — lado direito, posicionado pelo CSS .obpc-fab-wa */}
    <a href="https://wa.me/5511972771969?text=Paz%20do%20Senhor!" target="_blank" rel="noopener"
      className="obpc-fab-wa" style={{ background: "#25D366" }} title="Fale conosco no WhatsApp">
      <svg viewBox="0 0 32 32" width="26" height="26" fill="#fff">
        <path d="M16 3C9 3 3 9 3 16c0 2.3.6 4.5 1.8 6.5L3 29l6.7-1.8c1.9 1 4.1 1.6 6.3 1.6 7 0 13-6 13-13S23 3 16 3zm0 23.6c-2 0-3.9-.5-5.5-1.5l-.4-.2-4 1 1.1-3.9-.3-.4c-1.1-1.7-1.7-3.7-1.7-5.7 0-5.8 4.7-10.5 10.8-10.5s10.8 4.7 10.8 10.5-4.9 10.7-10.8 10.7zm6-8c-.3-.2-1.9-.9-2.2-1-.3-.1-.5-.2-.7.2-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-.3-.2-1.3-.5-2.5-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.5-.5.2-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.2-.7-1.6-1-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.2.2 2.1 3.3 5.2 4.6.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.8-.7 2.1-1.5.3-.7.3-1.4.2-1.5 0-.2-.2-.2-.4-.3z"/>
      </svg>
    </a>
  </>);
};

// ---------- Global Footer ----------
const GlobalFooter = ({ palette }) => (
  <footer className="obpc-gfooter" style={{ background: palette.surface, color: palette.muted, borderColor: `${palette.fg}15` }}>
    <div className="obpc-gfooter-grid">
      <div className="obpc-gfooter-brand">
        <div style={{ fontSize: 24, fontFamily: "Fraunces, serif", color: palette.fg, letterSpacing: "-0.02em" }}>
          <em>O Brasil</em> Para Cristo
        </div>
        <p style={{ maxWidth: 320, lineHeight: 1.6, marginTop: 12 }}>
          Igreja Evangélica Pentecostal fundada em 1955 pelo missionário Manoel de Mello.
          Uma obra dedicada a ganhar almas e cuidar de vidas.
        </p>
      </div>

      <div className="obpc-gfooter-col">
        <span className="obpc-gfooter-head" style={{ color: palette.fg }}>Institucional</span>
        <a href="/sobre">Sobre a Obra</a>
        <a href="/fundamentos">Fundamentos</a>
        <a href="/ministerios">Ministérios</a>
        <a href="/noticias">Notícias</a>
      </div>

      <div className="obpc-gfooter-col">
        <span className="obpc-gfooter-head" style={{ color: palette.fg }}>Comunidade</span>
        <a href="/jubrac">JUBRAC</a>
        <a href="/agenda">Agenda</a>
        <a href="/galeria">Galeria</a>
        <a href="/doacoes">Contribuir</a>
      </div>

      <div className="obpc-gfooter-col">
        <span className="obpc-gfooter-head" style={{ color: palette.fg }}>Contato</span>
        <a href="/visitantes">Quero conhecer a OBPC</a>
        <a href="/contato">Venha visitar</a>
        <a href="https://wa.me/5511972771969?text=Paz%20do%20Senhor!" target="_blank" rel="noopener">WhatsApp</a>
        <a href="https://instagram.com/obpcjundiai" target="_blank" rel="noopener">@obpcjundiai</a>
        <a href="https://www.facebook.com/obpcjundiaivilaarens/" target="_blank" rel="noopener">Facebook</a>
        <a href="https://www.youtube.com/@OBPCJundiai" target="_blank" rel="noopener">YouTube</a>
        <a href="https://share.google/DiN2dyeg36ZU3fvkT" target="_blank" rel="noopener">Google Maps</a>
        <span style={{ marginTop: 16, fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: palette.muted }}>
          Dom 18h30 · Ter 08h · Qua 20h<br/>R. Dante Júlio Spina, 62 · Vila Arens
        </span>
      </div>
    </div>

    <div className="obpc-gfooter-base" style={{ borderTopColor: `${palette.fg}15` }}>
      <span>© {new Date().getFullYear()} OBPC Jundiaí · "Venha ser OBPC. Nossa igreja espera por você."</span>
      <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
        DESDE 1955 · Pr. Carlos Gomes · obpcjundiai@gmail.com
        <a href="/privacidade" style={{ color: palette.muted, textDecoration: "none", opacity: 0.5, fontSize: 9, letterSpacing: "0.2em" }}
          onMouseEnter={e => e.target.style.opacity = 1}
          onMouseLeave={e => e.target.style.opacity = 0.5}>
          PRIVACIDADE &amp; LGPD
        </a>
      </span>
    </div>
  </footer>
);

Object.assign(window, {
  OBPC_PAGES, OBPC_PALETTES, usePalette,
  GlobalNav, FloatingWA, GlobalFooter,
});
