// ReservAI Landing — Navbar responsive (pill + hamburger mobile)
const { useState, useEffect } = React;

const BLUE = '#0983d6';

// Los links con `id` hacen scroll dentro de la home; los que tienen `href`
// llevan a otra página (van como <a> para que Google siga el enlace).
const LINKS = [
  { label: 'Beneficios',     id: 'beneficios' },
  { label: 'Cómo funciona',  id: 'como-funciona' },
  { label: 'Pruébalo',       id: 'pruebalo' },
  { label: 'Planes',         href: '/precios' },
  { label: 'Blog',           href: '/blog' },
  { label: 'FAQ',            id: 'faq' },
  { label: 'Contacto',       id: 'contacto' },
];

// Ancho mínimo para que quepan los 7 links + logo + CTA sin recortarse contra
// el overflow:hidden de la píldora. Por debajo se usa el menú hamburguesa.
// Ojo: NO reutilizar el useIsMobile global — Hero/Sections/Footer lo redefinen
// después y, al ser todos scripts globales, gana la última definición.
const NAV_COMPACT_BP = 1150;

function useNavCompact() {
  const [c, setC] = React.useState(window.innerWidth < NAV_COMPACT_BP);
  React.useEffect(() => {
    const h = () => setC(window.innerWidth < NAV_COMPACT_BP);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return c;
}

function Navbar({ onNav }) {
  const [scrolled, setScrolled] = useState(false);
  const [scrollPct, setScrollPct] = useState(0);
  const [hov, setHov] = useState(null);
  const [active, setActive] = useState(null);
  const [menuOpen, setMenuOpen] = useState(false);
  const compact = useNavCompact();

  useEffect(() => {
    const el = document.querySelector('#landing-scroll') || window;
    const onScroll = () => {
      const top = el === window ? window.scrollY : el.scrollTop;
      const max = el === window
        ? document.documentElement.scrollHeight - window.innerHeight
        : el.scrollHeight - el.clientHeight;
      setScrolled(top > 30);
      setScrollPct(max > 0 ? (top / max) * 100 : 0);
    };
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    if (!compact) setMenuOpen(false);
  }, [compact]);

  // Llegando desde otra página (/#beneficios, /#faq...) el enlace correspondiente
  // debe salir ya marcado. Sin esto el punto azul no aparece hasta que vuelves a
  // picarle, porque `active` solo se llenaba al hacer clic.
  useEffect(() => {
    const sincronizar = () => {
      const id = decodeURIComponent(window.location.hash.slice(1));
      const link = id && LINKS.find(l => l.id === id);
      setActive(link ? link.label : null);
    };
    sincronizar();
    window.addEventListener('hashchange', sincronizar);
    return () => window.removeEventListener('hashchange', sincronizar);
  }, []);

  const handleNav = (link) => {
    setMenuOpen(false);
    if (link.href) return;              // el <a> navega solo
    setActive(link.label);
    onNav && onNav(link.id);
  };

  // El logo es un <a href="/"> para que funcione y se indexe como enlace normal,
  // pero estando ya en la home no tiene sentido recargar: sube al inicio.
  const handleLogo = (e) => {
    setMenuOpen(false);
    const el = document.querySelector('#landing-scroll');
    if (!el) return;                    // sin contenedor, que navegue a "/"
    e.preventDefault();
    setActive(null);
    el.scrollTop = 0;
  };

  return (
    <div id="site-nav" style={{
      position: 'sticky', top: 0, zIndex: 100,
      padding: compact ? '10px 16px' : (scrolled ? '12px 20px' : '20px 20px'),
      transition: 'padding .35s ease',
      pointerEvents: 'none',
    }}>
      {/* Main pill */}
      <div style={{
        maxWidth: compact ? '100%' : (scrolled ? 1100 : 1240),
        margin: '0 auto',
        pointerEvents: 'auto',
        background: scrolled || compact ? 'rgba(0,0,0,.95)' : 'rgba(0,0,0,.45)',
        backdropFilter: 'blur(18px)',
        border: `1px solid ${scrolled || compact ? 'rgba(9,131,214,.3)' : 'rgba(255,255,255,.09)'}`,
        borderRadius: compact ? 18 : (scrolled ? 56 : 22),
        padding: compact ? '12px 18px' : (scrolled ? '12px 20px' : '18px 26px'),
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        transition: 'all .4s cubic-bezier(.4,0,.2,1)',
        boxShadow: scrolled || compact ? '0 8px 32px rgba(0,0,0,.55), 0 0 0 1px rgba(9,131,214,.08)' : 'none',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Progress bar */}
        <div style={{ position:'absolute', bottom:0, left:0, height:2, width:`${scrollPct}%`, background:`linear-gradient(90deg,${BLUE},#00AEEF)`, transition:'width .1s', borderRadius:'0 1px 0 0', pointerEvents:'none' }} />

        {/* Logo — enlace al inicio */}
        <a href="/" onClick={handleLogo} aria-label="ReservAI — ir al inicio"
          style={{ display: 'flex', alignItems: 'center', flexShrink: 0, cursor: 'pointer', textDecoration: 'none' }}>
          <img src="/assets/ReservAI-wordmark.png" alt="ReservAI"
            style={{ height: compact ? 30 : (scrolled ? 34 : 42), width: 'auto', transition: 'height .35s ease', display: 'block' }} />
        </a>

        {compact ? (
          /* Hamburger button */
          <button
            onClick={() => setMenuOpen(o => !o)}
            aria-label="Menú"
            aria-expanded={menuOpen}
            style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: 6, display: 'flex', flexDirection: 'column',
              gap: 4, alignItems: 'center', justifyContent: 'center',
            }}
          >
            <span style={{ display:'block', width:20, height:2, background:'#fff', borderRadius:1, transition:'all .25s', transform: menuOpen ? 'translateY(6px) rotate(45deg)' : 'none' }} />
            <span style={{ display:'block', width:20, height:2, background:'#fff', borderRadius:1, transition:'opacity .25s', opacity: menuOpen ? 0 : 1 }} />
            <span style={{ display:'block', width:20, height:2, background:'#fff', borderRadius:1, transition:'all .25s', transform: menuOpen ? 'translateY(-6px) rotate(-45deg)' : 'none' }} />
          </button>
        ) : (
          <>
            {/* Desktop Links */}
            <div style={{ display: 'flex', alignItems: 'center', gap: scrolled ? 2 : 4, flexShrink: 0 }}>
              {LINKS.map(link => {
                const l = link.label;
                const style = {
                  background: active === l ? 'rgba(9,131,214,.14)' : hov === l ? 'rgba(255,255,255,.05)' : 'transparent',
                  border: 'none',
                  color: active === l ? '#fff' : hov === l ? '#fff' : 'rgba(255,255,255,.62)',
                  padding: scrolled ? '8px 12px' : '10px 13px',
                  borderRadius: 40,
                  fontWeight: active === l ? 600 : 400,
                  fontSize: scrolled ? '.88rem' : '.95rem',
                  cursor: 'pointer', fontFamily: 'inherit',
                  transition: 'all .2s ease',
                  position: 'relative',
                  display: 'flex', alignItems: 'center', gap: 5,
                  textDecoration: 'none', whiteSpace: 'nowrap',
                };
                const inner = (
                  <React.Fragment>
                    <div style={{
                      width: 5, height: 5, borderRadius: '50%', background: BLUE, flexShrink: 0,
                      opacity: active === l ? 1 : 0,
                      transform: active === l ? 'scale(1)' : 'scale(0)',
                      transition: 'all .25s ease',
                    }} />
                    {l}
                    <div style={{
                      position: 'absolute', bottom: 3, left: 12, right: 12, height: 1.5,
                      background: `linear-gradient(90deg, ${BLUE}, #00AEEF)`,
                      borderRadius: 1,
                      transform: `scaleX(${hov === l && active !== l ? 1 : 0})`,
                      transformOrigin: 'left',
                      transition: 'transform .25s ease',
                    }} />
                  </React.Fragment>
                );
                const shared = {
                  onClick: () => handleNav(link),
                  onMouseEnter: () => setHov(l),
                  onMouseLeave: () => setHov(null),
                  style: style,
                };
                return link.href
                  ? <a key={l} href={link.href} {...shared}>{inner}</a>
                  : <button key={l} {...shared}>{inner}</button>;
              })}
            </div>

            {/* Desktop CTA */}
            <button onClick={() => handleNav({ label: 'Contacto', id: 'contacto' })} style={{
              background: BLUE, color: '#fff', border: 'none',
              padding: scrolled ? '11px 20px' : '13px 24px',
              borderRadius: 40, fontWeight: 700,
              fontSize: scrolled ? '.88rem' : '.95rem',
              cursor: 'pointer', transition: 'all .35s ease', fontFamily: 'inherit', flexShrink: 0,
              boxShadow: '0 4px 14px rgba(9,131,214,.35)',
              whiteSpace: 'nowrap',
            }}>Obtener ReservAI</button>
          </>
        )}
      </div>

      {/* Mobile dropdown */}
      {compact && menuOpen && (
        <div style={{
          pointerEvents: 'auto',
          background: 'rgba(5,5,5,.98)',
          backdropFilter: 'blur(18px)',
          border: '1px solid rgba(9,131,214,.25)',
          borderRadius: 18,
          padding: '10px 10px 14px',
          marginTop: 8,
        }}>
          {LINKS.map(link => {
            const style = {
              display: 'block', width: '100%', textAlign: 'left',
              background: 'transparent', border: 'none',
              color: active === link.label ? '#fff' : 'rgba(255,255,255,.75)',
              padding: '13px 16px', borderRadius: 10,
              fontSize: '.95rem', fontWeight: active === link.label ? 600 : 400,
              cursor: 'pointer', fontFamily: 'inherit', textDecoration: 'none',
            };
            return link.href
              ? <a key={link.label} href={link.href} onClick={() => handleNav(link)} style={style}>{link.label}</a>
              : <button key={link.label} onClick={() => handleNav(link)} style={style}>{link.label}</button>;
          })}
          <div style={{ padding: '6px 6px 0' }}>
            <button
              onClick={() => handleNav({ label: 'Contacto', id: 'contacto' })}
              style={{
                display: 'block', width: '100%', background: BLUE, color: '#fff',
                border: 'none', padding: '14px 16px', borderRadius: 12,
                fontWeight: 700, fontSize: '1rem', cursor: 'pointer', fontFamily: 'inherit',
              }}
            >
              Obtener ReservAI →
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Navbar });
