/* Reyes Montero — Nav + Hero */
const { useState: useStateTop, useEffect: useEffectTop, useRef: useRefTop } = React;

const NAV_LINKS = [
  { l: 'Inicio', h: 'inicio' },
  { l: 'Productos', h: 'productos' },
  { l: 'Cómo funciona', h: 'proceso' },
  { l: 'Equipo', h: 'equipo' },
  { l: 'Contacto', h: 'contacto' },
];

function Nav() {
  const [scrolled, setScrolled] = useStateTop(false);
  const [active, setActive] = useStateTop('inicio');
  const [open, setOpen] = useStateTop(false);

  useEffectTop(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 12);
      const ids = NAV_LINKS.map(n => n.h);
      let cur = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= 120) cur = id;
      }
      setActive(cur);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
      <div className="wrap nav-inner">
        <a className="nav-logo" href="#inicio" onClick={() => setOpen(false)}>
          <img src={resolveAsset(ASSETS + '/logo-grm-tile.png', 'logo_tile')} alt="Reyes Montero Agencia de Seguros" />
          <div>
            <div className="wordmark">Reyes Montero</div>
            <div className="sub">Agencia de Seguros</div>
          </div>
        </a>
        <div className="nav-links">
          {NAV_LINKS.map(x => (
            <a key={x.h} href={'#' + x.h} className={active === x.h ? 'active' : ''}>{x.l}</a>
          ))}
        </div>
        <a className="btn btn-gold nav-cta" href="#contacto"><Icon name="calculator" />Cotiza ahora</a>
        <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="Menú">
          <Icon name={open ? 'x' : 'menu'} />
        </button>
      </div>
      <div className={'mobile-menu' + (open ? ' open' : '')}>
        {NAV_LINKS.map(x => (
          <a key={x.h} href={'#' + x.h} onClick={() => setOpen(false)}>{x.l}</a>
        ))}
        <a className="btn btn-gold" href="#contacto" onClick={() => setOpen(false)} style={{ justifyContent: 'center' }}>
          <Icon name="calculator" />Cotiza ahora
        </a>
      </div>
    </nav>
  );
}

/* particle constellation canvas */
function HeroCanvas() {
  const ref = useRefTop(null);
  useEffectTop(() => {
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, w, h, pts = [];
    const DPR = Math.min(window.devicePixelRatio || 1, 2);
    function resize() {
      const r = canvas.parentElement.getBoundingClientRect();
      w = r.width; h = r.height;
      canvas.width = w * DPR; canvas.height = h * DPR;
      canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
      ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
      const count = Math.min(56, Math.floor(w / 26));
      pts = Array.from({ length: count }, () => ({
        x: Math.random() * w, y: Math.random() * h,
        vx: (Math.random() - .5) * .25, vy: (Math.random() - .5) * .25,
      }));
    }
    function tick() {
      ctx.clearRect(0, 0, w, h);
      for (const p of pts) {
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0 || p.x > w) p.vx *= -1;
        if (p.y < 0 || p.y > h) p.vy *= -1;
      }
      for (let i = 0; i < pts.length; i++) {
        for (let j = i + 1; j < pts.length; j++) {
          const a = pts[i], b = pts[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const dist = Math.hypot(dx, dy);
          if (dist < 132) {
            ctx.strokeStyle = 'rgba(255,255,255,' + (.16 * (1 - dist / 132)) + ')';
            ctx.lineWidth = 1;
            ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
          }
        }
      }
      for (const p of pts) {
        ctx.fillStyle = 'rgba(255,255,255,.5)';
        ctx.beginPath(); ctx.arc(p.x, p.y, 1.6, 0, Math.PI * 2); ctx.fill();
      }
      raf = requestAnimationFrame(tick);
    }
    resize(); tick();
    window.addEventListener('resize', resize);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);
  return <canvas ref={ref} className="hero-canvas"></canvas>;
}

function Hero() {
  const [linea, setLinea] = useStateTop('Seguro de Auto');
  const [nombre, setNombre] = useStateTop('');
  const [tel, setTel] = useStateTop('');

  const submit = (e) => {
    e.preventDefault();
    const msg = `Hola, soy ${nombre || '(sin nombre)'}. Quiero cotizar: ${linea}.` +
      (tel ? ` Mi teléfono es ${tel}.` : '') + ' ¿Me pueden asesorar?';
    window.open(waLink(msg), '_blank');
  };

  const words = 'Protegemos lo que más importa.'.split(' ');

  return (
    <header className="hero" id="inicio">
      <div className="hero-grid-bg"></div>
      <div className="hero-aurora"><span className="a1"></span><span className="a2"></span><span className="a3"></span></div>
      <HeroCanvas />
      <img className="hero-wmark" src={resolveAsset(ASSETS + '/logo-grm-white.png', 'logo_white')} alt="" />
      <div className="wrap hero-grid">
        <div>
          <span className="eyebrow hero-eyebrow"><span className="dot"></span>Reyes Montero · Agencia de Seguros</span>
          <h1>
            {words.map((w, i) => (
              <span key={i} className="reveal-word" style={{ animationDelay: (0.15 + i * 0.09) + 's' }}>
                {w === 'importa.' ? <span className="accent">{w}</span> : w}{i < words.length - 1 ? '\u00A0' : ''}
              </span>
            ))}
          </h1>
          <p className="lead-hero">Más de 42 años de asesoría profesional y cercana para las familias y empresas de Veracruz y todo México. Elige la protección que de verdad necesitas, con quien te conoce.</p>
          <div className="hero-cta">
            <a className="btn btn-gold" href="#productos"><Icon name="shield" />Conoce nuestros seguros</a>
            <a className="btn btn-ghost" href="#proceso">Cómo funciona<Icon name="arrow-down" /></a>
          </div>
          <div className="hero-trust">
            <div className="ti"><Icon name="award" /><div><div className="tnum"><CountUp target={42} /> años</div><div className="tlab">de experiencia</div></div></div>
            <div className="ti"><Icon name="users" /><div><div className="tnum"><CountUp target={500} suffix="+" /></div><div className="tlab">clientes protegidos</div></div></div>
            <div className="ti"><Icon name="building" /><div><div className="tnum">+<CountUp target={10} /></div><div className="tlab">aseguradoras</div></div></div>
          </div>
        </div>
        <div className="quote-card">
          <div className="qc-head">
            <div className="qc-badge"><Icon name="shield-check" /></div>
            <h4>Solicita tu cotización</h4>
          </div>
          <div className="qsub">Te contactamos por WhatsApp, sin compromiso.</div>
          <form onSubmit={submit}>
            <div className="qfield">
              <label>¿Qué quieres proteger?</label>
              <select value={linea} onChange={e => setLinea(e.target.value)}>
                {PRODUCTS.map(p => <option key={p.t}>{p.t}</option>)}
              </select>
            </div>
            <div className="qfield">
              <label>Tu nombre</label>
              <input value={nombre} onChange={e => setNombre(e.target.value)} placeholder="Ej. América Reyes" />
            </div>
            <div className="qfield">
              <label>Teléfono</label>
              <input value={tel} onChange={e => setTel(e.target.value)} placeholder="10 dígitos" inputMode="tel" />
            </div>
            <button className="btn btn-wa" type="submit" style={{ width: '100%', justifyContent: 'center', marginTop: '4px' }}>
              <Icon name="message-circle" />Quiero mi cotización
            </button>
          </form>
        </div>
      </div>
    </header>
  );
}

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