const navStyles = {
  nav: {
    position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '1.25rem 4rem',
  },
  logo: { display: 'inline-flex', alignItems: 'center', textDecoration: 'none' },
  logoImg: { height: 28, width: 'auto', display: 'block', transition: 'filter .3s' },
  cta: {
    fontSize: '0.8rem', letterSpacing: '.12em', textTransform: 'uppercase',
    padding: '.55rem 1.6rem', textDecoration: 'none',
    transition: 'background .25s, color .25s, border-color .25s',
    background: 'transparent', cursor: 'pointer', border: '1px solid',
  },
};

function Nav() {
  const navRef = React.useRef(null);
  const [hover, setHover] = React.useState(false);
  const [light, setLight] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => {
      if (!navRef.current) return;
      const p = Math.min(1, Math.max(0, window.scrollY / (window.innerHeight * 0.45)));
      navRef.current.style.setProperty('--glass-opacity', p);
      const r = `${p * 24}px`;
      navRef.current.style.borderBottomLeftRadius = r;
      navRef.current.style.borderBottomRightRadius = r;

      const headerH = navRef.current.offsetHeight;
      let isLight = false;
      document.querySelectorAll('[data-cream]').forEach(el => {
        const rect = el.getBoundingClientRect();
        if (rect.top <= headerH && rect.bottom >= headerH) isLight = true;
      });
      setLight(isLight);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const logoFilter = light ? 'brightness(0)' : 'brightness(0) invert(1)';
  const ctaColor = hover ? (light ? 'var(--cream)' : 'var(--bg)') : (light ? 'var(--ink)' : 'var(--gold)');
  const ctaBg = hover ? (light ? 'var(--ink)' : 'var(--gold)') : 'transparent';
  const ctaBorder = hover ? (light ? 'var(--ink)' : 'var(--gold)') : (light ? 'rgba(26,24,21,0.35)' : 'var(--border)');

  return (
    <nav ref={navRef} className="nav-glass nav-bar" style={navStyles.nav}>
      <a href="#" style={navStyles.logo} aria-label="REnderia">
        <img src="../../assets/renderia-logo.svg" alt="REnderia" style={{ ...navStyles.logoImg, filter: logoFilter }} />
      </a>
      <a href="#registrati"
        onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ ...navStyles.cta, background: ctaBg, color: ctaColor, borderColor: ctaBorder }}>
        Registrati
      </a>
    </nav>
  );
}

window.Nav = Nav;
