/* global React */
const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

/* =====================================================================
   Language (PT / EN) — global state via localStorage + custom event
   ===================================================================== */
const LANG_KEY = "raisa-lang";

function useLang() {
  const [lang, setLangState] = useState(() => {
    try { return localStorage.getItem(LANG_KEY) || "pt"; } catch { return "pt"; }
  });

  useEffect(() => {
    const handler = (e) => setLangState(e.detail);
    window.addEventListener("raisa-lang-change", handler);
    return () => window.removeEventListener("raisa-lang-change", handler);
  }, []);

  const setLang = useCallback((l) => {
    try { localStorage.setItem(LANG_KEY, l); } catch {}
    if (typeof document !== "undefined") {
      document.documentElement.lang = l === "en" ? "en" : "pt-BR";
    }
    window.dispatchEvent(new CustomEvent("raisa-lang-change", { detail: l }));
  }, []);

  return { lang, setLang };
}

// Helper: t(pt, en) returns the right string based on current lang
function tx(pt, en, lang) { return lang === "en" ? en : pt; }

function LangToggle({ light }) {
  const { lang, setLang } = useLang();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const handler = () => setScrolled(window.scrollY > 40);
    handler();
    window.addEventListener("scroll", handler, { passive: true });
    return () => window.removeEventListener("scroll", handler);
  }, []);
  const baseBg = light ? "rgba(244,243,236,0.08)" : "rgba(26,46,79,0.06)";
  const activeBg = light ? "var(--c-offwhite)" : "var(--c-navy)";
  const activeColor = light ? "var(--c-navy)" : "var(--c-offwhite)";
  const inactiveColor = light ? "var(--c-offwhite)" : "var(--c-navy)";
  return (
    <div className={`lang-toggle ${scrolled ? "lang-toggle--scrolled" : ""}`} style={{ display: "inline-flex", background: baseBg, borderRadius: 999, padding: 3, gap: 2 }}>
      {["pt", "en"].map((l) => (
        <button
          key={l}
          onClick={() => setLang(l)}
          aria-label={l === "pt" ? "Português" : "English"}
          aria-pressed={lang === l}
          style={{
            padding: "5px 12px",
            borderRadius: 999,
            border: "none",
            cursor: "pointer",
            fontSize: 11,
            fontWeight: 600,
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            fontFamily: "var(--ff-sans)",
            background: lang === l ? activeBg : "transparent",
            color: lang === l ? activeColor : inactiveColor,
            transition: "all 0.2s var(--ease-out)"
          }}
        >
          {l === "pt" ? "PT" : "EN"}
        </button>
      ))}
    </div>
  );
}

/* =====================================================================
   Logo
   ===================================================================== */
function Logo({ light, compact }) {
  const src = compact
    ? (light ? "uploads/icone-moura-light.png" : "uploads/icone-moura.png")
    : (light ? "uploads/logo-moura-light.png" : "uploads/logo-moura.png");
  return (
    <a href="index.html" className={`logo ${light ? "logo--light" : ""} ${compact ? "logo--compact" : ""}`} aria-label="Moura Immigration">
      <img src={src} alt="Moura Immigration" decoding="async" />
    </a>
  );
}

/* =====================================================================
   Reveal, IntersectionObserver
   ===================================================================== */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.is-in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* =====================================================================
   Modal context, manages which modal is open
   ===================================================================== */
const ModalCtx = createContext(null);

function ModalProvider({ children }) {
  const [open, setOpen] = useState(null); // 'eb3' | 'agenda' | 'equipe' | null

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

  return (
    <ModalCtx.Provider value={{ open, setOpen }}>
      {children}
    </ModalCtx.Provider>
  );
}

function useModal() { return useContext(ModalCtx); }

/* =====================================================================
   Modal shell
   ===================================================================== */
function Modal({ children, wide, onClose }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className={`modal ${wide ? "modal--wide" : ""}`} onClick={(e) => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
}

function ModalHead({ stepper, onClose }) {
  return (
    <div className="modal-head">
      {stepper}
      <button className="modal-close" onClick={onClose} aria-label="Fechar">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
        </svg>
      </button>
    </div>
  );
}

function Stepper({ total, current }) {
  return (
    <div className="modal-stepper">
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={`step ${i < current ? "is-done" : i === current ? "is-active" : ""}`} />
      ))}
    </div>
  );
}

/* =====================================================================
   NAV with scroll-spy
   ===================================================================== */
function Nav({ links, currentPage }) {
  const [active, setActive] = useState(links[0]?.id);
  const [navOpen, setNavOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const { setOpen } = useModal();

  // Detecta scroll pra encolher o nav
  useEffect(() => {
    const handler = () => setScrolled(window.scrollY > 60);
    handler();
    window.addEventListener("scroll", handler, { passive: true });
    return () => window.removeEventListener("scroll", handler);
  }, []);

  // Scroll-spy only works on homepage with hash links
  useEffect(() => {
    if (currentPage !== "home") return;
    const sectionEls = links
      .filter((l) => l.id.startsWith("#"))
      .map((l) => document.querySelector(l.id))
      .filter(Boolean);
    if (!sectionEls.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) setActive("#" + entry.target.id);
      });
    }, { rootMargin: "-30% 0px -60% 0px" });
    sectionEls.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [currentPage, links]);

  const { lang } = useLang();
  return (
    <header className={`nav ${scrolled ? "nav--scrolled" : ""}`}>
      <div className="nav-inner">
        <Logo />
        <nav className="nav-links" aria-label="Principal">
          {links.map((l) => {
            const isActive = currentPage === "home"
              ? active === l.id
              : l.page === currentPage;
            const label = typeof l.label === "object" ? (l.label[lang] || l.label.pt) : l.label;
            return (
              <a
                key={l.id}
                href={l.href || l.id}
                className={`nav-link ${isActive ? "is-active" : ""}`}
              >
                {label}
              </a>
            );
          })}
        </nav>
        <div className="flex items-center gap-3">
          <LangToggle />
          <button
            className="btn btn--accent btn--sm"
            onClick={() => setOpen("agenda")}
            style={{ height: 42 }}
          >
            <span className="nav-cta-label">{tx("Agendar com a Raísa", "Book with Raísa", lang)}</span>
            <span className="nav-cta-label-short" style={{ display: "none" }}>{tx("Agendar", "Book", lang)}</span>
            <svg className="arrow" viewBox="0 0 16 16" fill="none">
              <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </header>
  );
}

/* =====================================================================
   Footer
   ===================================================================== */
function Footer() {
  const { lang } = useLang();
  return (
    <footer className="footer">
      <div className="container">
        <div className="grid" style={{ gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 48 }}>
          <div>
            <Logo light compact />
            <p className="t-body" style={{ color: "rgba(244,243,236,0.72)", marginTop: 20, maxWidth: 320 }}>
              {tx(
                "Assessoria de imigração para pessoas que querem viver legalmente nos Estados Unidos.",
                "Immigration consulting for people who want to live legally in the United States.",
                lang
              )}
            </p>
            <div className="flex gap-2 mt-6">
              <SocialIcon kind="instagram" />
              <SocialIcon kind="whatsapp" />
              <SocialIcon kind="email" />
            </div>
          </div>
          <div>
            <h4>{tx("Navegação", "Navigation", lang)}</h4>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li><a href="index.html">{tx("Início", "Home", lang)}</a></li>
              <li><a href="servicos.html">{tx("Serviços", "Services", lang)}</a></li>
              <li><a href="sobre.html">{tx("Sobre a Raísa", "About Raísa", lang)}</a></li>
              <li><a href="contato.html">{tx("Contato", "Contact", lang)}</a></li>
            </ul>
          </div>
          <div>
            <h4>{tx("Serviços", "Services", lang)}</h4>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li><a href="servicos.html#green-card">{tx("Green Card por casamento", "Marriage Green Card", lang)}</a></li>
              <li><a href="servicos.html#eb3">{tx("EB-3, visto de trabalho", "EB-3, work visa", lang)}</a></li>
              <li><a href="servicos.html#consulares">{tx("Vistos consulares (B1/B2, F-1, J-1)", "Consular visas (B1/B2, F-1, J-1)", lang)}</a></li>
              <li><a href="servicos.html#i751">{tx("Renovação do Green Card", "Green Card renewal", lang)}</a></li>
              <li><a href="servicos.html#naturalizacao">{tx("Naturalização", "Naturalization", lang)}</a></li>
              <li><a href="servicos.html#individual">{tx("Sessão individual", "Individual consultation", lang)}</a></li>
            </ul>
          </div>
          <div>
            <h4>{tx("Contato", "Contact", lang)}</h4>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <li><a href="https://instagram.com/raisamoura">@raisamoura</a></li>
              <li><a href="mailto:rmouraimmigration@gmail.com">rmouraimmigration@gmail.com</a></li>
              <li><a href="tel:+15084006674">(508) 400-6674</a></li>
            </ul>
          </div>
        </div>

        <div style={{ height: 1, background: "rgba(244,243,236,0.12)", margin: "56px 0 28px" }} />

        <p className="t-caption" style={{ color: "rgba(244,243,236,0.55)", maxWidth: 880, lineHeight: 1.7 }}>
          <strong style={{ color: "rgba(244,243,236,0.85)" }}>Disclaimer:</strong>{" "}
          {tx(
            "A Moura Immigration Management LLC é uma consultoria de gestão imigratória. A decisão final sobre qualquer processo é de responsabilidade exclusiva do USCIS ou demais autoridades governamentais competentes. As taxas oficiais do governo americano não estão incluídas nos valores dos serviços.",
            "Moura Immigration Management LLC is an immigration management consultancy. The final decision on any case is the exclusive responsibility of USCIS or other competent governmental authorities. Official US government fees are not included in service prices.",
            lang
          )}
        </p>

        <div className="flex justify-between items-center mt-8" style={{ flexWrap: "wrap", gap: 16 }}>
          <span className="t-caption" style={{ color: "rgba(244,243,236,0.55)" }}>
            © 2026 Moura Immigration Management LLC. {tx("Todos os direitos reservados.", "All rights reserved.", lang)}
          </span>
          <span className="flex items-center" style={{ gap: 20, fontSize: 12, flexWrap: "wrap" }}>
            <a href="/privacidade" style={{ color: "rgba(244,243,236,0.65)" }}>{tx("Política de Privacidade", "Privacy Policy", lang)}</a>
            <a href="#" style={{ color: "rgba(244,243,236,0.65)" }}>{tx("Termos de Uso", "Terms of Use", lang)}</a>
            <a href="https://www.porfiliocompany.com.br/" target="_blank" rel="noopener noreferrer" className="porfilio-link">
              <span className="porfilio-prefix">{tx("Desenvolvido por", "Built by", lang)}</span>
              <span className="porfilio-mark">
                <span className="porfilio-dot"></span>
                Porfilio Company
              </span>
            </a>
          </span>
        </div>
      </div>
    </footer>
  );
}

function SocialIcon({ kind }) {
  const hrefs = {
    instagram: "https://instagram.com/raisamoura",
    whatsapp: "https://wa.me/15084006674",
    email: "mailto:rmouraimmigration@gmail.com",
  };
  const paths = {
    instagram: "M12 2.2c2.6 0 2.9 0 4 .1 2.6.1 3.8 1.3 3.9 3.9.1 1 .1 1.4.1 4s0 2.9-.1 4c-.1 2.6-1.3 3.8-3.9 3.9-1 .1-1.4.1-4 .1s-2.9 0-4-.1c-2.6-.1-3.8-1.3-3.9-3.9-.1-1-.1-1.4-.1-4s0-2.9.1-4c.1-2.6 1.3-3.8 3.9-3.9 1-.1 1.4-.1 4-.1zm0 4.4a5.4 5.4 0 100 10.8 5.4 5.4 0 000-10.8zm0 8.9a3.5 3.5 0 110-7 3.5 3.5 0 010 7zm5.6-9.1a1.3 1.3 0 100-2.6 1.3 1.3 0 000 2.6z",
    whatsapp: "M12 2a10 10 0 00-8.5 15.3L2 22l4.8-1.4A10 10 0 1012 2zm5.6 13.6c-.2.7-1.4 1.3-2 1.4-.5.1-1.2.1-1.9-.1-.4-.1-1-.3-1.7-.6a13 13 0 01-5-4.4c-.4-.5-1-1.4-1-2.6 0-1.3.7-1.9 1-2.2.2-.3.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .5l-.3.5-.4.4c-.1.2-.3.3-.1.6.2.3.8 1.4 1.8 2.3a8 8 0 002.5 1.6c.3.1.5.1.7-.1l.7-.9c.2-.3.4-.2.7-.1l1.9.9c.3.2.6.3.6.4.1.2.1.7-.1 1.2z",
    email: "M3 5h18a2 2 0 012 2v10a2 2 0 01-2 2H3a2 2 0 01-2-2V7a2 2 0 012-2zm0 2v.5l9 5.5 9-5.5V7H3zm18 2.7l-8.4 5.1a1 1 0 01-1.2 0L3 9.7V17h18V9.7z",
  };
  return (
    <a className="social-icon" href={hrefs[kind] || "#"} target={kind === "email" ? undefined : "_blank"} rel="noopener noreferrer" aria-label={kind} style={{
      width: 38, height: 38, borderRadius: "50%",
      border: "1px solid rgba(244,243,236,0.2)",
      display: "grid", placeItems: "center",
      color: "var(--c-offwhite)", opacity: 0.78,
      transition: "all .2s",
    }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
        <path d={paths[kind]} />
      </svg>
    </a>
  );
}

/* =====================================================================
   Helper: validation
   ===================================================================== */
function validateEmail(s) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s); }
function validatePhone(s) { return s.replace(/\D/g, "").length >= 9; }

/* =====================================================================
   Form submission helper — POSTs to Apps Script with text/plain to avoid CORS preflight
   ===================================================================== */
const FORM_SUBMIT_URL = "https://script.google.com/macros/s/AKfycbypMxXSHtVZtbijwCEf_tg63upF90wruoc_i69zuR1Q6fC6K-5Xo6kFfp4mT52mUOctAA/exec";
async function submitLead(payload) {
  try {
    await fetch(FORM_SUBMIT_URL, {
      method: "POST",
      body: JSON.stringify(payload),
      // no Content-Type header => browser sends text/plain => no CORS preflight
    });
    return true;
  } catch (err) {
    console.error("submitLead error", err);
    return false;
  }
}

/* expose globally so other Babel scripts can use them */
Object.assign(window, {
  Logo, Nav, Footer, ModalProvider, useModal, useReveal,
  Modal, ModalHead, Stepper, validateEmail, validatePhone,
  SocialIcon, submitLead, FORM_SUBMIT_URL,
});
