/* global React */
const { useState: useS_sh, useEffect: useE_sh } = React;

/* ──────────────────────────────────────────────
   Page identifiers — used for active nav state
   ────────────────────────────────────────────── */
const NAV_ITEMS = [
  { id: "home",        href: "index.html",       label: "Início" },
  { id: "sobre",       href: "sobre.html",       label: "Sobre" },
  { id: "plataforma",  href: "plataforma.html",  label: "Plataforma" },
  { id: "servicos",    href: "servicos.html",    label: "Serviços" },
  { id: "contato",     href: "contato.html",     label: "Contato" },
];

/* ──────────────────────────────────────────────
   Logo (respeita logo original; fallback elegante)
   ────────────────────────────────────────────── */
function Logo() {
  const [failed, setFailed] = useS_sh(false);
  return (
    <span className="logo-wrap">
      {!failed && (
        <img
          src="https://crimesolution.net/wp-content/uploads/2024/11/logo_retangular_branco-1-1024x233.png"
          alt="Crime Solution"
          className="logo-img"
          referrerPolicy="no-referrer"
          onError={() => setFailed(true)}
        />
      )}
      {failed && (
        <span className="logo-fallback" aria-label="Crime Solution">
          <svg className="logo-mark" viewBox="0 0 32 32" fill="none" aria-hidden="true">
            <path d="M16 3.5l11 4.2v7.6c0 6.4-4.5 11.6-11 12.7C9.5 26.9 5 21.7 5 15.3V7.7L16 3.5z"
              stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" />
            <path d="M11 16.5l3.4 3.4L21 12.6"
              stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          <span className="logo-wordmark">
            <strong>CRIME</strong>
            <span>SOLUTION</span>
          </span>
        </span>
      )}
    </span>
  );
}

/* ──────────────────────────────────────────────
   Nav with active page state
   ────────────────────────────────────────────── */
function Nav({ active }) {
  const [open, setOpen] = useS_sh(false);
  const [scrolled, setScrolled] = useS_sh(false);
  useE_sh(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on(); window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);

  return (
    <header className={"nav " + (scrolled ? "is-scrolled" : "")}>
      <div className="nav-inner container">
        <a href="index.html" className="nav-logo" aria-label="Crime Solution — início">
          <Logo />
        </a>
        <nav className="nav-links" aria-label="Principal">
          {NAV_ITEMS.map((it) => (
            <a
              key={it.id}
              href={it.href}
              className={it.id === active ? "is-active" : ""}
              aria-current={it.id === active ? "page" : undefined}
            >
              {it.label}
            </a>
          ))}
        </nav>
        <div className="nav-cta">
          <a href="area-restrita.html" className="btn btn-ghost" style={{ padding: "9px 14px", fontSize: 13 }}>
            <Icon.Lock /> Área restrita
          </a>
          <a
            href="https://wa.me/5561999949060?text=Precisa%20de%20tranquilidade%20na%20internet%3F"
            target="_blank" rel="noopener noreferrer"
            className="btn btn-primary" style={{ padding: "9px 14px", fontSize: 13 }}
          >
            <Icon.Wa /> Falar agora
          </a>
        </div>
        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen((o) => !o)}>
          <Icon.Menu />
        </button>
      </div>
      {open && (
        <div className="nav-mobile">
          {NAV_ITEMS.map((it) => (
            <a key={it.id} href={it.href} className={it.id === active ? "is-active" : ""}>{it.label}</a>
          ))}
          <a className="btn btn-ghost" href="area-restrita.html"><Icon.Lock /> Área restrita</a>
          <a className="btn btn-primary"
            href="https://wa.me/5561999949060" target="_blank" rel="noopener noreferrer"><Icon.Wa /> Falar agora</a>
        </div>
      )}
    </header>
  );
}

/* ──────────────────────────────────────────────
   Footer
   ────────────────────────────────────────────── */
function Footer() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="foot-grid">
          <div className="foot-brand">
            <div className="foot-logo"><Logo /></div>
            <p className="muted">
              Tranquilidade e proteção na internet. Operamos a partir de Brasília — DF,
              com cobertura nacional e parceiros na LATAM.
            </p>
          </div>

          <div className="foot-col">
            <span className="mono foot-tag">Navegar</span>
            <a href="index.html">Início</a>
            <a href="sobre.html">Sobre</a>
            <a href="plataforma.html">Plataforma</a>
            <a href="servicos.html">Serviços</a>
            <a href="contato.html">Contato</a>
            <a href="area-restrita.html">Área restrita</a>
          </div>

          <div className="foot-col">
            <span className="mono foot-tag">Serviços</span>
            <a href="cyber-investigator.html">Cyber Investigator</a>
            <a href="resposta-incidentes.html">Resposta a Incidentes</a>
            <a href="pentest.html">Pentest & Red Team</a>
            <a href="treinamentos.html">Treinamentos</a>
            <a href="consultoria.html">Consultoria</a>
          </div>

          <div className="foot-col">
            <span className="mono foot-tag">Contato</span>
            <a href="mailto:diretoria@crimesolution.net">diretoria@crimesolution.net</a>
            <a href="tel:5561999949060">+55 (61) 99994‑9060</a>
            <a href="https://wa.me/5561999949060" target="_blank" rel="noopener noreferrer">WhatsApp 24/7</a>
            <span className="mono foot-tag" style={{ marginTop: 18 }}>Social</span>
            <div className="social-row">
              <a href="https://www.linkedin.com/company/crimesolution/" target="_blank" rel="noopener noreferrer" aria-label="LinkedIn"><Icon.Linkedin /></a>
              <a href="https://www.instagram.com/crime.solution" target="_blank" rel="noopener noreferrer" aria-label="Instagram"><Icon.Instagram /></a>
              <a href="https://youtube.com/@crime-solution" target="_blank" rel="noopener noreferrer" aria-label="YouTube"><Icon.Youtube /></a>
              <a href="https://www.facebook.com/people/Crime-Solution/61567674593422/" target="_blank" rel="noopener noreferrer" aria-label="Facebook"><Icon.Facebook /></a>
            </div>
          </div>
        </div>

        <hr className="divider-line" />

        <div className="foot-bottom mono">
          <span>®️ CRIMESOLUTION 2022 — 2026. Todos os direitos reservados.</span>
          <div className="foot-links">
            <a href="termos.html">Termos de uso</a>
            <a href="privacidade.html">Política de privacidade</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ──────────────────────────────────────────────
   Tweaks orchestration — shared across pages via localStorage
   ────────────────────────────────────────────── */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "#5eead4",
  "density": "comfortable",
  "scanlines": true
}/*EDITMODE-END*/;

const ACCENTS = ["#5eead4", "#7dd3fc", "#a3e635", "#f0abfc"];

function applyTheme(t) {
  document.documentElement.setAttribute("data-theme", t.theme || "dark");
  document.documentElement.style.setProperty("--accent", t.accent || "#5eead4");
  document.documentElement.style.setProperty(
    "--accent-fg",
    t.theme === "light" ? "#0a0f1c" : "#06121b"
  );
  document.documentElement.dataset.density = t.density || "comfortable";
  document.documentElement.dataset.scanlines = t.scanlines ? "on" : "off";
}

function CrimeTweaks({ extra }) {
  // useTweaks comes from tweaks-panel.jsx and writes to the host through the
  // edit-mode protocol; we ALSO mirror to localStorage so tweaks survive page nav.
  const stored = (() => {
    try { return JSON.parse(localStorage.getItem("cs.tweaks") || "null"); } catch { return null; }
  })();
  const initial = { ...TWEAK_DEFAULTS, ...(stored || {}) };
  const [t, setTweak] = useTweaks(initial);

  useE_sh(() => { applyTheme(t); localStorage.setItem("cs.tweaks", JSON.stringify(t)); }, [t]);

  return (
    <TweaksPanel title="Tweaks · Crime Solution">
      <TweakSection label="Aparência">
        <TweakRadio
          label="Tema"
          value={t.theme}
          options={[{ value: "dark", label: "Dark SOC" }, { value: "light", label: "Claro" }]}
          onChange={(v) => setTweak("theme", v)}
        />
        <TweakColor
          label="Acento"
          value={t.accent}
          options={ACCENTS}
          onChange={(v) => setTweak("accent", v)}
        />
      </TweakSection>
      {extra && extra(t, setTweak)}
      <TweakSection label="Atmosfera">
        <TweakRadio
          label="Densidade"
          value={t.density}
          options={[{ value: "comfortable", label: "Arejada" }, { value: "compact", label: "Compacta" }]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakRadio
          label="Scanlines"
          value={t.scanlines ? "on" : "off"}
          options={[{ value: "on", label: "Ligado" }, { value: "off", label: "Desligado" }]}
          onChange={(v) => setTweak("scanlines", v === "on")}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

/* ──────────────────────────────────────────────
   Page shell — wraps Nav + main + Footer + Tweaks + Security
   ────────────────────────────────────────────── */
function PageShell({ active, tweaksExtra, children }) {
  // Active runtime hardening on every page
  usePageHardening();

  // Reveal-on-scroll for .reveal elements
  useE_sh(() => {
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) e.target.classList.add("in"); }),
      { threshold: 0.12 }
    );
    document.querySelectorAll(".reveal").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  // Apply persisted theme even before tweaks panel mounts
  useE_sh(() => {
    try {
      const stored = JSON.parse(localStorage.getItem("cs.tweaks") || "null");
      if (stored) applyTheme(stored);
    } catch {}
  }, []);

  return (
    <>
      <Nav active={active} />
      <main className="page-main">{children}</main>
      <Footer />
      <CrimeTweaks extra={tweaksExtra} />
      <SecurityStancePanel />
    </>
  );
}

/* ──────────────────────────────────────────────
   Small reusable section header
   ────────────────────────────────────────────── */
function PageHeader({ eyebrow, title, lead, children }) {
  return (
    <section className="page-head">
      <div className="grid-bg" />
      <div className="hero-glow" aria-hidden="true" />
      <div className="container page-head-inner">
        {eyebrow && <span className="eyebrow">{eyebrow}</span>}
        <h1 className="h-display page-h1">{title}</h1>
        {lead && <p className="lead page-lead">{lead}</p>}
        {children && <div className="page-head-foot">{children}</div>}
      </div>
    </section>
  );
}

function FinalCta({ title, body, ctaText = "Falar com um especialista", ctaHref = "contato.html" }) {
  return (
    <section className="final-cta">
      <div className="container final-cta-inner">
        <div>
          <h2 className="h-section">{title}</h2>
          {body && <p className="lead">{body}</p>}
        </div>
        <div className="final-cta-actions">
          <a className="btn btn-primary" href={ctaHref}>{ctaText} <Icon.Arrow className="arr" /></a>
          <a className="btn btn-ghost" href="https://wa.me/5561999949060" target="_blank" rel="noopener noreferrer">
            <Icon.Wa /> WhatsApp
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Logo, Nav, Footer, CrimeTweaks, PageShell, PageHeader, FinalCta, NAV_ITEMS, applyTheme });
