/* SISMO one-page — Nav, Hero, Manifiesto */
const { useState, useEffect, useRef } = React;

/* hooks */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.rv');
    const io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } }), { threshold: .15 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

const NAV_LINKS = [
  ["inicio", "Inicio"], ["nosotras", "Nosotras"], ["servicios", "Servicios"],
  ["trabajos", "Trabajos"], ["proceso", "Proceso"], ["contacto", "Contacto"],
];

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState("inicio");
  useEffect(() => {
    const ids = NAV_LINKS.map(([id]) => id);
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        setScrolled(window.scrollY > 40);
        const pos = window.scrollY + window.innerHeight * .35;
        let cur = ids[0];
        for (const id of ids) {
          const el = document.getElementById(id);
          if (el && el.getBoundingClientRect().top + window.scrollY <= pos) cur = id;
        }
        setActive(cur);
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); cancelAnimationFrame(raf); };
  }, []);
  const go = () => setOpen(false);
  return (
    <>
      <nav className={"nav" + (scrolled ? " scrolled" : "")}>
        <a href="#inicio"><img className="nav__logo" src="assets/logo-sismo-nuevo.png" alt="Agencia SISMO"/></a>
        <div className="nav__links">
          {NAV_LINKS.slice(0, 5).map(([id, label]) => (
            <a key={id} href={"#" + id} className={active === id ? "active" : ""}>{label}</a>
          ))}
        </div>
        <a className="nav__cta" href="#contacto">Hablemos →</a>
        <button className={"nav__burger" + (open ? " open" : "")} aria-label="Menú" aria-expanded={open} onClick={() => setOpen(!open)}>
          <span></span><span></span><span></span>
        </button>
      </nav>
      <div className={"nav__panel" + (open ? " open" : "")}>
        <button className="nav__panel-close" aria-label="Cerrar menú" onClick={go}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><path d="M5 5l14 14M19 5L5 19"/></svg>
        </button>
        <div className="nav__panel-inner">
          {NAV_LINKS.map(([id, label], i) => <a key={id} href={"#" + id} onClick={go} style={{ transitionDelay: open ? (.08 + i * .07) + "s" : "0s" }}>{label}</a>)}
          <a className="nav__panel-cta" href="#contacto" onClick={go} style={{ transitionDelay: open ? (.08 + NAV_LINKS.length * .07) + "s" : "0s" }}>Hablemos por WhatsApp</a>
          <div className="nav__panel-social" style={{ transitionDelay: open ? (.15 + NAV_LINKS.length * .07) + "s" : "0s" }}>
            <a href="https://www.instagram.com/agenciasismo/" target="_blank" rel="noopener" aria-label="Instagram">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="2.5" y="2.5" width="19" height="19" rx="5.5"/><circle cx="12" cy="12" r="4.5"/><circle cx="17.6" cy="6.4" r="1.3" fill="currentColor" stroke="none"/></svg>
            </a>
            <a href="https://www.facebook.com/SismoMarketingDigital" target="_blank" rel="noopener" aria-label="Facebook">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M14 8.5V7c0-1 .5-1.5 1.5-1.5H17V2.5h-2.5C12 2.5 10.5 4.2 10.5 6.8v1.7H8v3.3h2.5v9.7H14v-9.7h2.5l.5-3.3H14z"/></svg>
            </a>
          </div>
        </div>
      </div>
    </>
  );
}

function GridBg() {
  /* deformed / curved reticle */
  const lines = [];
  for (let i = 0; i <= 14; i++) {
    const y = i * 60;
    lines.push(<path key={"h" + i} d={`M0 ${y} Q 480 ${y + 42}, 960 ${y} T 1920 ${y}`} fill="none" stroke="rgba(255,255,255,.07)" strokeWidth="1"/>);
  }
  for (let i = 0; i <= 22; i++) {
    const x = i * 90;
    lines.push(<path key={"v" + i} d={`M${x} 0 Q ${x + 34} 420, ${x} 840`} fill="none" stroke="rgba(255,255,255,.05)" strokeWidth="1"/>);
  }
  return (
    <div className="hero-grid-bg" aria-hidden="true">
      <svg viewBox="0 0 1920 840" preserveAspectRatio="xMidYMid slice">{lines}</svg>
    </div>
  );
}

function HeroVideo() {
  const ref = useRef(null);
  useEffect(() => {
    const v = ref.current;
    if (!v) return;
    v.muted = true;
    v.defaultMuted = true;
    v.setAttribute("muted", "");
    const tryPlay = () => v.play().catch(() => {});
    tryPlay();
    // reintento al primer toque/scroll si el navegador lo bloqueó
    const kick = () => { tryPlay(); window.removeEventListener("touchstart", kick); window.removeEventListener("scroll", kick); };
    window.addEventListener("touchstart", kick, { passive: true, once: true });
    window.addEventListener("scroll", kick, { passive: true, once: true });
    return () => { window.removeEventListener("touchstart", kick); window.removeEventListener("scroll", kick); };
  }, []);
  return <video ref={ref} className="hero__carrusel" src="assets/carrusel-works.mp4" autoPlay muted loop playsInline preload="auto" aria-label="Piezas audiovisuales producidas por SISMO"></video>;
}

function Hero() {
  return (
    <div className="hero-wrap" id="inicio">
      <GridBg/>
      <section className="hero">
        <div className="rv">
          <span className="hero__tag">#ContenidoConImpacto</span>
          <h1 className="hero__title">
            Estrategia, identidad<br/>
            y contenido para marcas<br/>
            que quieren <em>moverse.</em>
          </h1>
          <p className="hero__sub">
            En SISMO combinamos estrategia, creatividad, diseño y producción audiovisual para construir marcas con una presencia clara, profesional y con personalidad.
          </p>
          <p className="hero__sub2">
            Desde Tierra del Fuego, acompañamos a negocios, profesionales e instituciones a dejar de improvisar y empezar a comunicar con intención.
          </p>
          <div className="hero__ctas">
            <a className="btn btn-grad" href="#contacto">
              Quiero mover mi marca
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
            <a className="btn btn-outline" href="#servicios">Ver servicios</a>
          </div>
        </div>
        <div className="hero__visual rv rv-d2">
          <img className="hero__mm" src="assets/decor-multimedia-pink.png" alt=""/>
          <img className="hero__gif-rocket" src="assets/gif-rocket.gif" alt=""/>
          <HeroVideo/>
          <img className="hero__gif-eye" src="assets/gif-view.gif" alt=""/>
          <img className="hero__arrows" src="assets/icon-arrows-fastforward.png" alt=""/>
        </div>
        <div className="hero__scroll">Scroll ↓</div>
      </section>
    </div>
  );
}

const WORDS = ["Estrategia", "Identidad", "Contenido", "Movimiento", "Resultados"];

function Manifiesto() {
  return (
    <section className="manifiesto">
      <div className="manifiesto__inner">
        <span className="eyebrow" style={{ color: "#0D0D0D", opacity: .65 }}>Manifiesto</span>
        <h2 className="rv">Tu marca no necesita hacer más ruido.<br/>Necesita tener algo claro para decir.</h2>
        <p className="rv rv-d1">No hacemos contenido por cumplir. Pensamos qué comunicar, cómo mostrarlo y cómo hacerlo llegar a las personas correctas.</p>
        <div className="manifiesto__words">
          {WORDS.map((w, i) => (
            <span key={w} className={"manifiesto__word rv rv-d" + Math.min(i + 1, 4)}>{w}</span>
          ))}
        </div>
        <div className="manifiesto__intent rv rv-d4">Todo tiene una intención detrás.</div>
      </div>
    </section>
  );
}

Object.assign(window, { useReveal, Nav, Hero, Manifiesto });
