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

// ── ARCTMIND wordmark / mark ────────────────────────────────
function Mark({ size = 22, color }) {
  const c = color || "var(--accent)";
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" aria-hidden="true">
      <rect x="2" y="2" width="28" height="28" rx="7" fill={c}/>
      <path d="M9 22 L16 9 L23 22" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
      <path d="M12.2 17 L19.8 17" stroke="white" strokeWidth="2.2" strokeLinecap="round"/>
    </svg>
  );
}

function Wordmark({ size = 22, dark = false }) {
  return (
    <a href="index.html" className="row center gap-8" style={{ color: dark ? "#fff" : "var(--text)" }}>
      <Mark size={size}/>
      <span style={{
        fontFamily: "var(--font-sans)",
        fontWeight: 700,
        letterSpacing: "-0.01em",
        fontSize: size * 0.82,
      }}>
        arct<span style={{ color: "#818CF8" }}>·</span>mind
      </span>
    </a>
  );
}

// ── Nav ─────────────────────────────────────────────────────
function Nav({ active }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const links = [
    { href: "pages/como-funciona.html", label: "Como funciona", id: "como" },
    { href: "pages/conectores.html", label: "Conectores", id: "conectores" },
    { href: "pages/precos.html", label: "Preços", id: "precos" },
    { href: "pages/segmentos.html", label: "Segmentos", id: "segmentos" },
    { href: "pages/sobre.html", label: "Sobre", id: "sobre" },
  ];
  const inPages = typeof window !== "undefined" && window.location.pathname.includes("/pages/");
  const fix = (h) => {
    if (h === "index.html") return inPages ? "../index.html" : "index.html";
    if (inPages) return h.replace("pages/", "");
    return h;
  };

  useEffect(() => {
    if (mobileOpen) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  return (
    <React.Fragment>
      <header className="nav">
        <div className="container nav-inner">
          <a href={fix("index.html")} className="row center gap-8" style={{ textDecoration: "none" }}>
            <img src={inPages ? "../assets/images/logo-light.svg" : "assets/images/logo-light.svg"} alt="ARCTMIND" height={32} style={{ display: "block" }}/>
          </a>
          <nav className="nav-links">
            {links.map(l => (
              <a key={l.id} href={fix(l.href)} className={active === l.id ? "active" : ""}>{l.label}</a>
            ))}
          </nav>
          <div className="row center gap-8">
            <a href={fix("pages/contato.html")} className="btn btn-soft btn-sm" style={{ display: "inline-flex" }}>Falar com vendas</a>
            <a href={fix("pages/contato.html")} className="btn btn-primary btn-sm">
              Começar grátis
              <svg className="arr" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
            <button className="nav-hamburger" aria-label="Menu" onClick={() => setMobileOpen(o => !o)}>
              <span style={{ opacity: mobileOpen ? 0 : 1 }}/>
              <span style={{ transform: mobileOpen ? "rotate(45deg) translate(4px, 4px)" : "none" }}/>
              <span style={{ transform: mobileOpen ? "rotate(-45deg) translate(4px, -4px)" : "none" }}/>
            </button>
          </div>
        </div>
      </header>
      {mobileOpen && (
        <div className="nav-drawer" onClick={() => setMobileOpen(false)}>
          {links.map(l => (
            <a key={l.id} href={fix(l.href)} className={active === l.id ? "active" : ""}>{l.label}</a>
          ))}
          <div style={{ marginTop: 8, paddingTop: 16, borderTop: "1px solid var(--border)" }}>
            <a href={fix("pages/contato.html")} className="btn btn-primary" style={{ width: "100%", justifyContent: "center" }}>
              Começar grátis · 14 dias
            </a>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

// ── Footer ──────────────────────────────────────────────────
function Footer() {
  const inPages = typeof window !== "undefined" && window.location.pathname.includes("/pages/");
  const fix = (h) => {
    if (h === "index.html") return inPages ? "../index.html" : "index.html";
    if (inPages) return h.replace("pages/", "");
    return h;
  };
  const cols = [
    { title: "EMPRESA", items: [
      ["Sobre", "pages/sobre.html"],
      ["Contato", "pages/contato.html"],
      ["Carreiras", "pages/carreiras.html"],
      ["Segurança", "pages/seguranca.html"],
    ]},
    { title: "RECURSOS", items: [
      ["Documentação", "pages/documentacao.html"],
      ["Status", "pages/status.html"],
      ["Changelog", "pages/changelog.html"],
      ["Conectores", "pages/conectores.html"],
    ]},
    { title: "LEGAL", items: [
      ["Privacidade (LGPD)", "pages/privacidade.html"],
      ["Termos de Uso", "pages/termos.html"],
      ["DPA", "pages/dpa.html"],
      ["Política de Cookies", "pages/cookies.html"],
    ]},
  ];
  return (
    <footer className="footer">
      <div className="container">
        <div className="grid" style={{ gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 56 }}>
          <div>
            <a href={fix("index.html")} style={{ textDecoration: "none", display: "inline-flex" }}>
              <img src={inPages ? "../assets/images/logo-light.svg" : "assets/images/logo-light.svg"} alt="ARCTMIND" height={32} style={{ display: "block" }}/>
            </a>
            <p style={{ marginTop: 14, color: "#818CF8", fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.04em" }}>
              Build minds, not bots.
            </p>
            <p style={{ marginTop: 12, color: "#6B7185", fontSize: 14, lineHeight: 1.65, maxWidth: 300 }}>
              Inteligência operacional para PMEs brasileiras. Detectamos onde sua operação perde dinheiro — antes que vire prejuízo.
            </p>
            <p style={{ marginTop: 16, color: "#4A4F63", fontSize: 12, fontFamily: "var(--font-mono)" }}>
              © 2026 ARCTMIND. Todos os direitos reservados.
            </p>
          </div>
          {cols.map(c => (
            <div key={c.title} className="col gap-12">
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "#6B7185", fontFamily: "var(--font-mono)", marginBottom: 6, fontWeight: 500 }}>{c.title}</div>
              {c.items.map(([label, href]) => (
                <a key={label} href={fix(href)} style={{ fontSize: 14, color: "#A0A6B8", lineHeight: 1.5 }}>{label}</a>
              ))}
            </div>
          ))}
        </div>

        <div style={{ height: 1, background: "rgba(255,255,255,0.06)", marginTop: 56, marginBottom: 24 }}/>
        <div className="row between" style={{ flexWrap: "wrap", gap: 12, alignItems: "center" }}>
          <div style={{ fontSize: 12, color: "#6B7185", fontFamily: "var(--font-mono)" }}>
            © 2026 ARCTMIND Tecnologia Ltda. CNPJ XX.XXX.XXX/0001-XX
          </div>
          <div style={{ fontSize: 12, color: "#6B7185", fontFamily: "var(--font-mono)" }}>
            Dados armazenados no Brasil · LGPD compliant
          </div>
        </div>
      </div>
    </footer>
  );
}

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

// ── BRL formatter ──────────────────────────────────────────
function fmtBRL(n) {
  return n.toLocaleString("pt-BR", { style: "currency", currency: "BRL", maximumFractionDigits: 0 });
}

// ── Severity badge ─────────────────────────────────────────
function SeverityBadge({ level }) {
  const map = {
    critico: { label: "Crítico", cls: "tag-critical" },
    alto: { label: "Alto", cls: "tag-warning" },
    medio: { label: "Médio", cls: "tag-muted" },
    info: { label: "Info", cls: "tag-accent" },
  };
  const m = map[level] || map.medio;
  return <span className={`tag ${m.cls}`}><span className="dot"/>{m.label}</span>;
}

// ── Tiny sparkline ─────────────────────────────────────────
function Sparkline({ values, w = 96, h = 28, color, fill }) {
  const c = color || "var(--accent)";
  const max = Math.max(...values), min = Math.min(...values);
  const span = max - min || 1;
  const stepX = w / (values.length - 1);
  const pts = values.map((v, i) => `${i * stepX},${h - ((v - min) / span) * (h - 4) - 2}`).join(" ");
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      {fill && <polygon fill={fill} points={`0,${h} ${pts} ${w},${h}`} opacity="0.12"/>}
      <polyline fill="none" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" points={pts}/>
    </svg>
  );
}

// expose
Object.assign(window, { Mark, Wordmark, Nav, Footer, useReveal, fmtBRL, SeverityBadge, Sparkline });
