// Landing — nav, hero, logos, statement, bento
const { PROFILE: LP, PROJECTS: LPROJ, INFRA_PHOTOS: LPH } = window.PORTFOLIO_DATA;
const { Dither, Magnetic, Tilt, CountUp, canHover } = window;
// Los CTAs que llevan a #contacto avisan con qué origen llega el formulario (lo escucha LEnd).
const ynContact = (origen) => window.dispatchEvent(new CustomEvent("yn-contact", { detail: origen }));
const LLINKS = [["#servicios", "Servicios"], ["#proyectos", "Proyectos"], ["#proceso", "Proceso"], ["#productos", "Productos"], ["#faq", "FAQ"]];
const LI = {
  arrow: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 7l10 10M17 7v10H7"/></svg>,
  right: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  chev: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"/></svg>,
  menu: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  close: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>,
  check: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7"/></svg>,
  star: <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12 2 3 6.6 7 .8-5.2 4.8L18.2 21 12 17.4 5.8 21l1.4-6.8L2 9.4l7-.8z"/></svg>,
  mail: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>,
  sun: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4 1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>,
  moon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>,
  cal: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M9 15l2 2 4-4"/></svg>,
  users: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0"/><circle cx="17" cy="9" r="2.5"/><path d="M15.5 14.5a5 5 0 0 1 6 5"/></svg>,
  rocket: <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 15c-1.5 1.5-2 5-2 5s3.5-.5 5-2M14 4c3 0 6 3 6 6l-8 8-6-6 8-8z"/><circle cx="15" cy="9" r="1.5"/></svg>,
  bolt: <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8z"/></svg>,
  box: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinejoin="round"><path d="m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/></svg>,
};

const LSERV_ITEMS = [["Infraestructura", "Servidores, redes y virtualización"], ["Automatización", "n8n, Python, WhatsApp Cloud API"], ["Plataformas a medida", "Laravel, Next.js, PostgreSQL"], ["DevOps y operación", "Docker, Grafana, Zabbix, backups"]];
function LNav({ onChat }) {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => { const on = () => setScrolled(window.scrollY > 24); on(); window.addEventListener("scroll", on, { passive: true }); return () => window.removeEventListener("scroll", on); }, []);
  return (
    <>
      <nav className={`nav${scrolled ? " scrolled" : ""}`}>
        <a className="logo" href="#top">Yeiko Nova</a>
        <div className="menu">
          <div><button type="button">Servicios {LI.chev}</button><div className="drop"><div>{LSERV_ITEMS.map(([t, d]) => <a key={t} href="#servicios">{t}<small>{d}</small></a>)}</div></div></div>
          <div><button type="button">Proyectos {LI.chev}</button><div className="drop"><div>{LPROJ.map(p => <a key={p.slug} href="#proyectos">{p.title}<small>{p.tag}</small></a>)}</div></div></div>
          <a href="#productos">Productos</a>
        </div>
        <div className="right">
          <a href="#contacto" onClick={() => ynContact("contacto")}>Contacto</a>
          <button className="split sm" onClick={onChat}><b>Hablar con Leadko AI</b><i>{LI.arrow}</i></button>
          <button className="burger" aria-label="Menú" onClick={() => setOpen(o => !o)}>{open ? LI.close : LI.menu}</button>
        </div>
      </nav>
      {open && <div className="sheet" onClick={() => setOpen(false)}>{LLINKS.map(([h, l]) => <a key={h} href={h}>{l}</a>)}<a href="#contacto" onClick={() => ynContact("contacto")}>Contacto</a><button onClick={onChat}>Hablar con Leadko AI</button></div>}
    </>
  );
}

const LOGOS = ["Kopel Sánchez", "Nivelex", "Leadko AI", "Dialer Hub", "VelIA", "Multiline"];
const Words = ({ text, from = 0 }) => text.split(" ").map((w, i) => <React.Fragment key={i}><span className="wd" style={{ "--d": `${from + i * .06}s` }}>{w}</span>{" "}</React.Fragment>);
const HROT = ["dialer", "leadko", "posventa"].map(k => LPROJ.find(p => p.slug === k)).filter(Boolean);
const HeroRotator = React.forwardRef(function HeroRotator(_, ref) {
  const n = HROT.length;
  const [i, setI] = React.useState(0);
  const reduced = React.useMemo(() => matchMedia("(prefers-reduced-motion: reduce)").matches, []);
  React.useEffect(() => { if (reduced || n < 2) return; const id = setInterval(() => setI(k => (k + 1) % n), 6000); return () => clearInterval(id); }, []);
  return (
    <div className="frame" ref={ref}>
      <div className="rot">{HROT.map((p, k) => <img key={p.slug} src={p.image} alt={p.title} data-on={k === i ? "" : undefined} loading={k ? "lazy" : "eager"} />)}</div>
      <div className="rtabs" aria-hidden="true">{HROT.map((p, k) => <span key={p.slug} data-on={k === i ? "" : undefined}>{p.title}</span>)}</div>
    </div>
  );
});

function LHero() {
  const items = [...LOGOS, ...LOGOS];
  const hero = React.useRef(null), frame = React.useRef(null);
  React.useEffect(() => {
    const el = frame.current, host = hero.current; if (!el || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0, mx = 0, my = 0;
    const apply = () => { raf = 0; const p = Math.min(1, window.scrollY / (window.innerHeight * .9)); el.style.transform = `perspective(1400px) rotateX(${((1 - p) * 9).toFixed(2)}deg) translate3d(${(mx * -16).toFixed(1)}px,${(my * -10 - p * 24).toFixed(1)}px,0)`; };
    const on = () => { if (!raf) raf = requestAnimationFrame(apply); };
    const move = e => { mx = e.clientX / window.innerWidth - .5; my = e.clientY / window.innerHeight - .5; on(); };
    window.addEventListener("scroll", on, { passive: true }); if (canHover()) host.addEventListener("pointermove", move); apply();
    return () => { window.removeEventListener("scroll", on); host.removeEventListener("pointermove", move); cancelAnimationFrame(raf); };
  }, []);
  return (
    <header className="hero" id="top" ref={hero}>
      <Dither sky />
      <div className="wrap">
        <h1><Words text="Probado en más de 50 empresas." from={.1} /><br /><Words text="Listo para la" from={.45} /><em className="wd" style={{ "--d": ".6s" }}>tuya.</em></h1>
        <p className="sub rise" style={{ "--d": ".5s" }}>Dialer, Leadko AI y VelIA: software en producción que se instala en días, con un único responsable técnico detrás.</p>
        <div className="rise" style={{ "--d": ".6s" }}><Magnetic className="split" href="#proyectos"><b>Ver proyectos</b><i>{LI.arrow}</i></Magnetic></div>
        <div className="dash rise" style={{ "--d": ".75s" }}><HeroRotator ref={frame} /></div>
      </div>
      <div className="logos" aria-hidden="true"><div className="track">{items.map((n, k) => <span key={k}><i>{n[0]}</i>{n}</span>)}</div></div>
    </header>
  );
}

function LStatement() {
  const words = React.useMemo(() => "Mi trabajo empieza por entender el problema, no por ofrecer un producto. Si con algo simple alcanza, hacemos eso.".split(" "), []);
  const ref = React.useRef(null);
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    let raf = 0;
    const f = () => { raf = 0; const el = ref.current; if (!el) return; const r = el.getBoundingClientRect(), vh = window.innerHeight; const p = Math.min(1, Math.max(0, (vh * .85 - r.top) / (vh * .5 + r.height * .4))); setN(Math.round(p * words.length)); };
    const on = () => { if (!raf) raf = requestAnimationFrame(f); };
    f(); window.addEventListener("scroll", on, { passive: true }); window.addEventListener("resize", on);
    return () => { window.removeEventListener("scroll", on); window.removeEventListener("resize", on); cancelAnimationFrame(raf); };
  }, []);
  return <section className="statement"><div className="wrap"><p ref={ref}>{words.map((w, i) => <React.Fragment key={i}><span className="w" data-on={i < n ? "" : undefined}>{w}</span>{" "}</React.Fragment>)}</p></div></section>;
}

function LBento() {
  return (
    <section className="bento" id="servicios">
      <div className="wrap bgrid">
        <Tilt className="b lime center reveal" max={3}>
          <h3>Infraestructura que no depende de nadie</h3>
          <p>Servidores, redes y virtualización listos desde el primer día, monitoreados las 24 horas.</p>
          <div className="phone"><MonScreen /></div>
        </Tilt>
        <div className="bright">
          <Tilt className="b pale wide reveal" style={{ "--d": ".08s" }} max={3}>
            <div><h3>Tus datos, en tu servidor</h3><p>Cada plataforma corre en infraestructura propia, con backups diarios y acceso por VPN. Sin depender de terceros.</p></div>
            <div className="rings"><div className="mini"><div className="scr">
              <div className="search">kopel-prod · Hetzner</div>
              <small>Último backup</small><b>hace <CountUp to={2} /> h · verificado</b>
              <div className="seg"><span className="on">Proxmox</span><span>WireGuard</span><span>2FA</span></div>
              <div className="status"><small>Estado del servidor ⓘ</small><b>Todo en verde <span className="chip">✓ 99,9%</span></b></div>
            </div></div></div>
          </Tilt>
          <div className="two">
            <Tilt className="b pale reveal" style={{ "--d": ".12s" }} max={5}>
              <h3>Listo en días,<br />no en meses</h3>
              <p>Lo que un desarrollo tradicional tarda meses, acá se instala en semanas.</p>
              <div className="tline">
                <div className="track"><i></i></div>
                <div className="pin" style={{ "--x": "3%" }}><b>1 día</b><small>Leadko AI</small></div>
                <div className="pin up" style={{ "--x": "26%" }}><b>2 sem</b><small>VelIA</small></div>
                <div className="pin" style={{ "--x": "52%" }}><b>6 sem</b><small>Dialer</small></div>
                <div className="pin ghost up" style={{ "--x": "100%" }}><b>6+ meses</b><small>a medida</small></div>
              </div>
            </Tilt>
            <Tilt className="b dark live reveal" style={{ "--d": ".16s" }} max={5}>
              <h3>Software que ya trabaja</h3>
              <ul className="live-rows">
                <li style={{ "--w": "72%" }}><div><b><CountUp to={40} suffix="+" /></b><span>personas trabajan sobre Dialer cada día</span></div><em>Dialer</em><i></i></li>
                <li style={{ "--w": "100%" }}><div><b><CountUp to={2000} /></b><span>mensajes atendidos por día</span></div><em>Leadko AI</em><i></i></li>
                <li style={{ "--w": "38%" }}><div><b><CountUp to={10} /></b><span>usuarios · reportes y seguimiento de reclamos</span></div><em>VelIA</em><i></i></li>
              </ul>
            </Tilt>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { LNav, LHero, LStatement, LBento, LLINKS, LI, ynContact });
