// nav-hero.jsx — Navbar, Hero, LogoStrip, Tension, Reframe (ADAPTIVE THEME)

function Navbar() {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [isDark, setIsDark] = React.useState(false);

  const links = [
    { label: 'Producto', href: '#producto' },
    { label: 'Industrias', href: '#industrias' },
    { label: 'Precios', href: '#precios' },
    { label: 'FAQ', href: '#faq' },
  ];

  // Detect if navbar overlaps a dark section
  React.useEffect(() => {
    function checkDark() {
      const navY = 60; // approx center of navbar
      const darkSections = document.querySelectorAll('[data-dark-section]');
      let overDark = false;
      darkSections.forEach(sec => {
        const rect = sec.getBoundingClientRect();
        if (rect.top <= navY && rect.bottom >= navY) overDark = true;
      });
      setIsDark(overDark);
    }
    window.addEventListener('scroll', checkDark, { passive: true });
    checkDark();
    return () => window.removeEventListener('scroll', checkDark);
  }, []);

  const fg = isDark ? 'rgba(255,255,255,' : 'rgba(10,10,15,';
  const fgFull = isDark ? '#fff' : '#0A0A0F';

  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      display: 'flex', justifyContent: 'center',
      padding: '12px 20px 0',
      pointerEvents: 'none',
    }}>
      <nav style={{
        pointerEvents: 'auto',
        background: isDark ? 'rgba(255,255,255,0.06)' : 'rgba(10,10,15,0.045)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        borderRadius: 16,
        padding: '0 10px 0 28px',
        display: 'flex', alignItems: 'center', gap: 8,
        maxWidth: 1200, width: '100%',
        height: 72,
        border: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(10,10,15,0.06)'}`,
        transition: 'background 0.35s ease, border-color 0.35s ease',
      }}>
        {/* Logo */}
        <a href="#" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', marginRight: 'auto' }}>
          <img src="/v2/assets/alvex-wordmark-nobg.png" style={{
            height: 34,
            filter: isDark ? 'brightness(10)' : 'none',
            transition: 'filter 0.35s ease',
          }} alt="ALVEX" />
        </a>

        {/* Desktop links — centered */}
        <div className="nav-desktop" style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'center', gap: 6 }}>
          {links.map((l) =>
            <a key={l.label} href={l.href} style={{
              color: `${fg}0.50)`, fontSize: 16, fontWeight: 500,
              textDecoration: 'none', padding: '10px 22px', borderRadius: 10,
              transition: 'color 150ms, background 150ms',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.color = fgFull; e.currentTarget.style.background = `${fg}0.06)`; }}
            onMouseLeave={(e) => { e.currentTarget.style.color = `${fg}0.50)`; e.currentTarget.style.background = 'transparent'; }}>
              {l.label}
            </a>
          )}
        </div>

        {/* Desktop CTAs */}
        <div className="nav-desktop" style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 16 }}>
          <a href="/login" style={{
            color: `${fg}0.65)`, fontSize: 14.5, fontWeight: 500,
            textDecoration: 'none',
            padding: '10px 22px', borderRadius: 999,
            background: `${fg}0.05)`,
            border: `1px solid ${fg}0.10)`,
            transition: 'all 150ms',
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = `${fg}0.10)`; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = `${fg}0.05)`; }}>
            Iniciar sesión
          </a>
          <a href="/register" className="btn-primary" style={{
            padding: '10px 22px', fontSize: 14.5,
          }}>Probar gratis</a>
        </div>

        {/* Mobile hamburger */}
        <button className="nav-mobile-btn" onClick={() => setMobileOpen(!mobileOpen)} style={{
          display: 'none', background: 'none', border: 'none',
          color: fgFull, cursor: 'pointer', padding: 8,
          transition: 'color 0.35s ease',
        }}>
          {mobileOpen
            ? <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
            : <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 6h16M4 12h16M4 18h16" /></svg>
          }
        </button>
      </nav>

      {/* Mobile menu */}
      {mobileOpen && (
        <div style={{
          pointerEvents: 'auto', position: 'absolute', top: 80, left: 20, right: 20,
          padding: '16px 24px 24px',
          background: isDark ? 'rgba(10,10,15,0.92)' : 'rgba(255,255,255,0.95)',
          backdropFilter: 'blur(16px)',
          borderRadius: 16,
          boxShadow: isDark ? '0 12px 40px rgba(0,0,0,0.30)' : '0 12px 40px rgba(10,10,15,0.10)',
          border: `1px solid ${isDark ? 'rgba(255,255,255,0.08)' : 'rgba(10,10,15,0.06)'}`,
          display: 'flex', flexDirection: 'column', gap: 0,
        }}>
          {links.map((l) =>
            <a key={l.label} href={l.href} onClick={() => setMobileOpen(false)} style={{
              color: `${fg}0.60)`, fontSize: 16, fontWeight: 500,
              textDecoration: 'none', padding: '14px 0',
              borderBottom: `1px solid ${fg}0.06)`,
            }}>{l.label}</a>
          )}
          <div style={{ display: 'flex', gap: 8, marginTop: 20 }}>
            <a href="/login" style={{
              flex: 1, textAlign: 'center', color: `${fg}0.65)`, fontSize: 14, fontWeight: 500,
              textDecoration: 'none', padding: '12px 0', borderRadius: 999,
              background: `${fg}0.05)`, border: `1px solid ${fg}0.08)`,
            }}>Iniciar sesión</a>
            <a href="/register" className="btn-primary" style={{
              flex: 1, textAlign: 'center', justifyContent: 'center', fontSize: 14,
            }}>Probar gratis</a>
          </div>
        </div>
      )}
    </div>
  );
}

// Aceternity BackgroundGradientAnimation port — ALVEX colors, vanilla CSS + JSX
function BackgroundGradientAnimation({ interactive = true }) {
  const interactiveRef = React.useRef(null);
  const curRef = React.useRef({ x: 0, y: 0 });
  const tgRef = React.useRef({ x: 0, y: 0 });
  const [isSafari, setIsSafari] = React.useState(false);
  const reduced = React.useRef(false);

  React.useEffect(() => {
    setIsSafari(/^((?!chrome|android).)*safari/i.test(navigator.userAgent));
    reduced.current = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  }, []);

  React.useEffect(() => {
    if (!interactive || reduced.current) return;
    let raf;
    const step = () => {
      const el = interactiveRef.current;
      if (el) {
        curRef.current.x += (tgRef.current.x - curRef.current.x) / 20;
        curRef.current.y += (tgRef.current.y - curRef.current.y) / 20;
        el.style.transform = `translate(${Math.round(curRef.current.x)}px, ${Math.round(curRef.current.y)}px)`;
      }
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [interactive]);

  const handleMouseMove = (event) => {
    if (interactiveRef.current) {
      const rect = interactiveRef.current.getBoundingClientRect();
      tgRef.current.x = event.clientX - rect.left;
      tgRef.current.y = event.clientY - rect.top;
    }
  };

  return (
    <div className="bg-gradient-anim" style={{ pointerEvents: 'none' }}>
      <svg style={{ position: 'absolute', width: 0, height: 0 }} aria-hidden>
        <defs>
          <filter id="bg-goo">
            <feGaussianBlur in="SourceGraphic" stdDeviation="10" result="blur" />
            <feColorMatrix in="blur" mode="matrix"
              values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -8" result="goo" />
            <feBlend in="SourceGraphic" in2="goo" />
          </filter>
        </defs>
      </svg>
      <div className={`bg-gradients-container${isSafari ? ' safari' : ''}`}>
        <div className="bg-blob bg-blob-1" />
        <div className="bg-blob bg-blob-2" />
        <div className="bg-blob bg-blob-3" />
        <div className="bg-blob bg-blob-4" />
        <div className="bg-blob bg-blob-5" />
        {interactive && (
          <div
            ref={interactiveRef}
            onMouseMove={handleMouseMove}
            className="bg-blob bg-blob-pointer"
            style={{ pointerEvents: 'auto' }}
          />
        )}
      </div>
    </div>
  );
}

function HeroSection({ showAurora }) {
  const words = ['Negocios', 'Inmobiliarias', 'Consultorios', 'E-commerce', 'Restaurantes', 'Coaches', 'Profesionales', 'Empresas', 'Marcas'];

  function RotatingWord() {
    const [index, setIndex] = React.useState(0);
    const [animClass, setAnimClass] = React.useState('rot-in');

    React.useEffect(() => {
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
      const interval = setInterval(() => {
        setAnimClass('rot-out');
        setTimeout(() => {
          setIndex((prev) => (prev + 1) % words.length);
          setAnimClass('rot-in');
        }, 350);
      }, 2400);
      return () => clearInterval(interval);
    }, []);

    return (
      <div style={{
        overflow: 'hidden',
        height: '1.08em',
        fontSize: 'clamp(46px, 7.8vw, 96px)',
        lineHeight: 1.08,
        marginTop: '-0.04em',
        display: 'flex', justifyContent: 'center', alignItems: 'flex-start',
      }}>
        <div className={`heading-display rotating-word ${animClass}`} style={{
          color: 'var(--accent)',
          letterSpacing: '-0.035em',
          lineHeight: 1.08,
          display: 'inline-block',
        }}>
          {words[index]}
        </div>
      </div>
    );
  }

  return (
    <section style={{
      position: 'relative', minHeight: '100vh',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: '140px 24px 160px', overflow: 'hidden',
    }}>
      {showAurora && <BackgroundGradientAnimation interactive={true} />}

      <div style={{ position: 'relative', textAlign: 'center', maxWidth: 1100 }}>
        <h1 className="heading-display hero-enter" style={{
          animationDelay: '0.08s',
          fontSize: 'clamp(46px, 7.8vw, 96px)',
          color: '#0A0A0F', lineHeight: 1.08,
          letterSpacing: '-0.035em',
        }}>
          Construye <span style={{ color: 'var(--accent)' }}>Un Sistema</span>
          <br />De IA Hecho Para
        </h1>

        <div className="hero-enter" style={{ animationDelay: '0.18s', textAlign: 'center' }}>
          <RotatingWord />
        </div>

        <div className="hero-enter" style={{ animationDelay: '0.28s' }}>
          <p style={{
            fontSize: 'clamp(17px, 2.2vw, 22px)', color: 'rgba(10,10,15,0.50)',
            lineHeight: 1.6, maxWidth: 680, margin: '40px auto 0', textWrap: 'pretty',
            fontWeight: 400,
          }}>Vende mientras duermes y deja que la IA atienda cada cliente, en cualquier idioma, sin contratar una sola persona más</p>
        </div>

        <div className="hero-enter" style={{ animationDelay: '0.42s' }}>
          <div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 48, flexWrap: 'wrap' }}>
            <a href="/register" className="btn-primary" style={{ padding: '18px 38px', fontSize: 17 }}>
              Probar gratis 14 días
            </a>
            <a href="#producto" className="btn-outline-light" style={{ padding: '18px 32px', fontSize: 17 }}>
              Ver cómo funciona
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}

function LogoStrip() { return null; }

function TensionSection() {
  return (
    <section style={{ padding: 'clamp(72px, 10vw, 128px) 24px' }}>
      <div style={{ maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
        <RevealOnScroll>
          <h2 className="heading-display" style={{
            fontSize: 'clamp(26px, 4.5vw, 50px)', color: '#0A0A0F',
            textWrap: 'balance',
          }}>
            Cada llamada perdida es un cliente que se va con tu competencia
          </h2>
        </RevealOnScroll>
        <RevealOnScroll delay={200}>
          <p style={{
            fontSize: 'clamp(15px, 1.6vw, 18px)', color: 'rgba(10,10,15,0.42)',
            lineHeight: 1.65, marginTop: 24, textWrap: 'pretty',
          }}>
            Mientras lees esto, alguien intentó contactarte fuera de horario, en otro idioma, o por un canal que no atiendes. No vuelven dos veces.
          </p>
        </RevealOnScroll>
      </div>
    </section>
  );
}

function ReframeSection() {
  return (
    <section style={{
      position: 'relative', padding: 'clamp(80px, 10vw, 140px) 24px', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: '50%', left: '-100%', width: '300%', height: 1,
        background: 'linear-gradient(90deg, transparent 20%, var(--accent-a25) 50%, transparent 80%)',
        animation: 'beam-sweep 6s ease-in-out infinite', pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        width: 500, height: 500,
        background: 'radial-gradient(circle, var(--accent-a08), transparent 65%)',
        pointerEvents: 'none',
      }} />
      <div style={{ position: 'relative', maxWidth: 780, margin: '0 auto', textAlign: 'center' }}>
        <RevealOnScroll><Pill accent>La nueva norma</Pill></RevealOnScroll>
        <RevealOnScroll delay={100}>
          <h2 className="heading-display" style={{
            fontSize: 'clamp(26px, 4.5vw, 50px)', color: '#0A0A0F',
            marginTop: 24, textWrap: 'balance',
          }}>
            Un sistema que trabaja por ti.{' '}
            <span style={{ color: 'rgba(10,10,15,0.25)' }}>No contra ti</span>
          </h2>
        </RevealOnScroll>
        <RevealOnScroll delay={200}>
          <p style={{
            fontSize: 'clamp(15px, 1.6vw, 18px)', color: 'rgba(10,10,15,0.45)',
            lineHeight: 1.65, marginTop: 24, textWrap: 'pretty',
          }}>
            Agentes de IA que toman cada conversación, la entienden y actúan. Tu equipo se enfoca en lo único que solo humanos pueden hacer.
          </p>
        </RevealOnScroll>
      </div>
    </section>
  );
}

Object.assign(window, { Navbar, HeroSection, LogoStrip, TensionSection, ReframeSection });
