// Nav.jsx — PROYECTO Site Navigation

const Nav = ({ currentPage, onNavigate }) => {
  const [isMobile, setIsMobile] = React.useState(!!window.__IS_MOBILE);
  const [isNarrow, setIsNarrow] = React.useState(() => window.innerWidth < 520);

  React.useEffect(() => {
    const unsub = (typeof window.__onMobileChange === 'function')
      ? window.__onMobileChange(setIsMobile) : null;
    const onResize = () => setIsNarrow(window.innerWidth < 520);
    window.addEventListener('resize', onResize);
    window.addEventListener('orientationchange', onResize);
    return () => {
      if (unsub) unsub();
      window.removeEventListener('resize', onResize);
      window.removeEventListener('orientationchange', onResize);
    };
  }, []);

  // Full labels for wider screens (including tablets/iPad landscape).
  // Short labels only when the viewport can't fit the full row.
  const links = [
    { id: 'studio01', label: isNarrow ? '01' : '01 — PREMIUM' },
    { id: 'studio02', label: isNarrow ? '02' : '02 — STANDARD' },
    { id: 'studio03', label: isNarrow ? '03' : '03 — REHEARSAL' },
    { id: 'events',   label: 'EVENTS' },
    { id: 'contact',  label: 'CONTACT' },
  ];

  return (
    <nav style={{
      ...navStyles.nav,
      ...(isMobile ? { padding: '0 12px', cursor: 'auto' } : {}),
    }}>
      <div
        style={{
          ...navStyles.logo,
          ...(isMobile ? { fontSize: 11, letterSpacing: '0.06em', cursor: 'pointer' } : {}),
        }}
        onClick={() => onNavigate('landing')}
      >
        PROYECTO
      </div>
      <div style={{
        ...navStyles.links,
        ...(isNarrow ? { gap: 10 } : isMobile ? { gap: 22 } : {}),
      }}>
        {links.map((link) => (
          <NavLink
            key={link.id}
            link={link}
            active={currentPage === link.id}
            onNavigate={onNavigate}
            isMobile={isMobile}
            isNarrow={isNarrow}
          />
        ))}
      </div>
    </nav>
  );
};

const NavLink = ({ link, active, onNavigate, isMobile, isNarrow }) => {
  const [display, setDisplay] = React.useState(link.label);
  const animRef = React.useRef(null);
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

  // Keep display text in sync if label changes (e.g. on viewport resize mobile ↔ desktop)
  React.useEffect(() => { setDisplay(link.label); }, [link.label]);

  const scramble = () => {
    if (isMobile) return; // no scramble on touch — it only fires on tap, not hover
    if (animRef.current) clearInterval(animRef.current);
    let step = 0; const steps = 6;
    const target = link.label;
    animRef.current = setInterval(() => {
      step++;
      const out = target.split('').map((ch, i) => {
        if (ch === ' ' || ch === '—') return ch;
        const locked = step >= (i + 1) * (steps / target.length);
        return locked ? ch : chars[Math.floor(Math.random() * chars.length)];
      }).join('');
      setDisplay(out);
      if (step >= steps + 2) { clearInterval(animRef.current); setDisplay(target); }
    }, 35);
  };

  return (
    <button
      onClick={() => onNavigate(link.id)}
      onMouseEnter={scramble}
      style={{
        ...navStyles.link,
        color: active ? '#fff' : (isMobile ? '#777' : '#444'),
        ...(isNarrow ? { fontSize: 9.5, letterSpacing: '0.08em' } : {}),
        ...(isMobile ? {
          cursor: 'pointer',
          padding: '4px 0',
          borderBottom: active ? '1px solid var(--accent, #e6351e)' : '1px solid #2a2a2a',
        } : {}),
      }}
    >
      {!isMobile && (
        <span style={{
          ...navStyles.linkBracket,
          opacity: active ? 1 : 0,
          ...(isNarrow ? { width: 10, fontSize: 10 } : {}),
        }}>▸ </span>
      )}
      {display}
    </button>
  );
};

const navStyles = {
  nav: {
    position: 'fixed', top: 0, left: 0, right: 0,
    height: 48, background: 'rgba(0,0,0,0.95)',
    borderBottom: '1px solid #0e0e0e',
    display: 'flex', alignItems: 'center',
    padding: '0 48px', zIndex: 100,
    fontFamily: "'Share Tech Mono', monospace",
    backdropFilter: 'blur(8px)',
    cursor: 'none',
  },
  logo: {
    fontFamily: "'Cindie2', sans-serif",
    fontSize: 19, fontWeight: 700,
    letterSpacing: '0.12em', textTransform: 'uppercase',
    color: '#fff', cursor: 'none',
    marginRight: 'auto',
  },
  links: { display: 'flex', gap: 36 },
  link: {
    background: 'transparent', border: 'none',
    fontFamily: "'Share Tech Mono', monospace",
    fontSize: 12, letterSpacing: '0.14em',
    cursor: 'none', padding: 0,
    transition: 'color 120ms linear',
    display: 'inline-flex', alignItems: 'center',
    textTransform: 'uppercase',
  },
  linkBracket: {
    width: 14, display: 'inline-block', color: 'var(--accent, #e6351e)',
    transition: 'opacity 120ms linear',
  },
};

Object.assign(window, { Nav });
