// Nav v4. Floating glass capsule, magnetic active indicator, Space Grotesk wordmark
const { useState: useNavState, useEffect: useNavEffect, useRef: useNavRef } = React;

function Nav({ theme, toggleTheme }) {
  const [scrolled,   setScrolled]   = useNavState(false);
  const [activeId,   setActiveId]   = useNavState(null);
  const [mobileOpen, setMobileOpen] = useNavState(false);
  const indicatorRef = useNavRef(null);
  const linksWrapRef = useNavRef(null);
  const isDark = theme === 'dark';

  const navLinks = [
    { label: 'Work',       href: '#work',       id: 'work'       },
    { label: 'Industries', href: '#industries', id: 'industries' },
    { label: 'Services',   href: '#services',   id: 'services'   },
    { label: 'Process',    href: '#process',    id: 'process'    },
    { label: 'Pricing',    href: '#pricing',    id: 'pricing'    },
  ];

  useNavEffect(() => {
    const h = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', h, { passive: true });
    return () => window.removeEventListener('scroll', h);
  }, []);

  // Track which section is in view, moves the magnetic indicator
  useNavEffect(() => {
    const sections = navLinks
      .map(l => document.getElementById(l.id))
      .filter(Boolean);
    if (!sections.length) return;
    const obs = new IntersectionObserver(entries => {
      const visible = entries
        .filter(e => e.isIntersecting)
        .sort((a,b) => b.intersectionRatio - a.intersectionRatio);
      if (visible.length) setActiveId(visible[0].target.id);
    }, {
      rootMargin: '-30% 0px -55% 0px',
      threshold: [0, 0.25, 0.5, 0.75, 1],
    });
    sections.forEach(s => obs.observe(s));
    return () => obs.disconnect();
  }, []);

  // Slide the magnetic indicator under the active link
  useNavEffect(() => {
    if (!indicatorRef.current || !linksWrapRef.current || !activeId) return;
    const activeLink = linksWrapRef.current.querySelector(`[data-link="${activeId}"]`);
    if (!activeLink) return;
    const rect = activeLink.getBoundingClientRect();
    const wrapRect = linksWrapRef.current.getBoundingClientRect();
    // Position offset relative to the capsule's content box
    const offsetX = rect.left - wrapRect.left;
    indicatorRef.current.style.width = `${rect.width}px`;
    indicatorRef.current.style.height = `${rect.height}px`;
    indicatorRef.current.style.transform = `translate(${offsetX}px, -50%)`;
    indicatorRef.current.style.opacity = '1';
  }, [activeId]);

  const glassBg     = isDark ? 'rgba(20,20,26,0.62)' : 'rgba(255,255,255,0.72)';
  const glassBgSoft = isDark ? 'rgba(20,20,26,0.42)' : 'rgba(255,255,255,0.55)';
  const glassBdr    = isDark ? 'rgba(255,255,255,0.08)' : 'rgba(10,10,18,0.08)';
  const linkColor   = isDark ? 'rgba(255,255,255,0.72)' : 'rgba(10,10,18,0.65)';
  const linkHover   = isDark ? 'rgba(255,255,255,0.95)' : 'rgba(10,10,18,0.95)';

  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      padding: scrolled ? '14px 32px' : '22px 32px',
      transition: 'padding 0.45s cubic-bezier(0.16,1,0.3,1)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16,
    }}>
      {/* ── LEFT: Logo + Wordmark ──────────────────────────────────────── */}
      <a href="#" style={{
        textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 11,
        padding: scrolled ? '8px 14px' : '8px 16px',
        background: scrolled ? glassBg : 'transparent',
        backdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
        WebkitBackdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
        border: `1px solid ${scrolled ? glassBdr : 'transparent'}`,
        borderRadius: 14,
        transition: 'all 0.45s cubic-bezier(0.16,1,0.3,1)',
      }}>
        <img src="assets/logo.png" alt="Quantaeight" style={{
          width: 30, height: 30, objectFit: 'contain',
          filter: isDark ? 'invert(1) brightness(10)' : 'none',
          transition: 'filter 0.3s ease',
        }} />
        <span style={{
          fontFamily: '"Plus Jakarta Sans", sans-serif',
          fontSize: 16, fontWeight: 600,
          color: 'var(--text-primary)',
          letterSpacing: '0.005em',
          transition: 'color 0.3s ease',
        }}>Quantaeight</span>
      </a>

      {/* ── CENTER: Floating glass capsule ─────────────────────────────── */}
      <div style={{
        position: 'absolute', left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)',
        display: 'flex', alignItems: 'center',
        background: scrolled ? glassBg : glassBgSoft,
        backdropFilter: 'blur(22px) saturate(180%)',
        WebkitBackdropFilter: 'blur(22px) saturate(180%)',
        border: `1px solid ${glassBdr}`,
        borderRadius: 100,
        padding: '4px 6px',
        gap: 2,
        boxShadow: scrolled
          ? '0 8px 32px rgba(0,0,0,0.25), inset 0 1px 0 rgba(255,255,255,0.05)'
          : '0 4px 20px rgba(0,0,0,0.15), inset 0 1px 0 rgba(255,255,255,0.04)',
        transition: 'all 0.45s cubic-bezier(0.16,1,0.3,1)',
      }} className="nav-capsule" ref={linksWrapRef}>
        {/* Magnetic indicator behind active link, white-frost (not mint) for max readability */}
        <span ref={indicatorRef} style={{
          position: 'absolute', left: 0, top: '50%',
          transform: 'translate(0, -50%)',
          height: 0, width: 0,
          background: isDark ? 'rgba(255,255,255,0.10)' : 'rgba(10,10,18,0.07)',
          border: `1px solid ${isDark ? 'rgba(255,255,255,0.14)' : 'rgba(10,10,18,0.10)'}`,
          borderRadius: 100,
          opacity: 0,
          transition: 'transform 0.55s cubic-bezier(0.34,1.56,0.64,1), width 0.55s cubic-bezier(0.34,1.56,0.64,1), opacity 0.3s ease',
          pointerEvents: 'none',
          boxShadow: isDark ? 'inset 0 1px 0 rgba(255,255,255,0.05)' : 'inset 0 1px 0 rgba(255,255,255,0.5)',
        }} />
        {navLinks.map(link => {
          const isActive = activeId === link.id;
          return (
            <a key={link.id} href={link.href} data-link={link.id}
              style={{
                fontFamily: '"Plus Jakarta Sans", sans-serif',
                fontSize: 14, fontWeight: 500,
                color: isActive ? 'var(--text-primary)' : linkColor,
                textDecoration: 'none',
                padding: '6px 22px', borderRadius: 100,
                transition: 'color 0.3s ease',
                letterSpacing: '0.005em',
                position: 'relative', zIndex: 1,
                whiteSpace: 'nowrap',
                fontWeight: isActive ? 600 : 500,
              }}
              onMouseEnter={e => { if (!isActive) e.target.style.color = linkHover; }}
              onMouseLeave={e => { if (!isActive) e.target.style.color = linkColor; }}
            >{link.label}</a>
          );
        })}
      </div>

      {/* ── RIGHT: Theme toggle + CTA ──────────────────────────────────── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <button onClick={toggleTheme}
          title={isDark ? 'Switch to light' : 'Switch to dark'}
          aria-label="Toggle theme"
          style={{
            width: 38, height: 38, borderRadius: '50%',
            border: `1px solid ${glassBdr}`,
            background: glassBg,
            backdropFilter: 'blur(18px) saturate(180%)',
            WebkitBackdropFilter: 'blur(18px) saturate(180%)',
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.25s ease', color: 'var(--text-secondary)',
          }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'rgba(0,217,160,0.5)'; e.currentTarget.style.color = 'var(--accent-mint)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = glassBdr; e.currentTarget.style.color = 'var(--text-secondary)'; }}
        >
          {isDark ? (
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <circle cx="12" cy="12" r="5"/>
              <line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/>
              <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
              <line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/>
              <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
            </svg>
          ) : (
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
            </svg>
          )}
        </button>

        <a href="https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight"
          target="_blank" rel="noopener"
          className="nav-cta"
          style={{
            fontFamily: '"Plus Jakarta Sans", sans-serif', fontSize: 13.5, fontWeight: 600,
            color: '#0A0A0B', background: 'var(--accent-mint)',
            padding: '9px 18px', borderRadius: 100, textDecoration: 'none',
            transition: 'all 0.22s ease',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            whiteSpace: 'nowrap', letterSpacing: '0.01em',
            boxShadow: '0 4px 16px rgba(0,217,160,0.28)',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = '#00F0B4'; e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,217,160,0.4)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = '#00D9A0'; e.currentTarget.style.transform = 'translateY(0)';    e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,217,160,0.28)'; }}
        >
          Book a call
          <span style={{ fontSize: 12, opacity: 0.7 }}>→</span>
        </a>

        <button onClick={() => setMobileOpen(o => !o)}
          aria-label="Menu"
          className="nav-mobile-trigger"
          style={{
            display: 'none',
            width: 38, height: 38, borderRadius: '50%',
            border: `1px solid ${glassBdr}`,
            background: glassBg,
            backdropFilter: 'blur(18px) saturate(180%)',
            WebkitBackdropFilter: 'blur(18px) saturate(180%)',
            cursor: 'pointer',
            alignItems: 'center', justifyContent: 'center',
            color: 'var(--text-secondary)',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            {mobileOpen
              ? (<><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>)
              : (<><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></>)
            }
          </svg>
        </button>
      </div>

      {/* Mobile dropdown */}
      {mobileOpen && (
        <div className="nav-mobile-menu" style={{
          position: 'absolute', top: 'calc(100% + 8px)', left: 16, right: 16,
          background: isDark ? 'rgba(14,16,24,0.94)' : 'rgba(255,255,255,0.96)',
          backdropFilter: 'blur(24px) saturate(180%)',
          WebkitBackdropFilter: 'blur(24px) saturate(180%)',
          border: `1px solid ${glassBdr}`,
          borderRadius: 16, padding: '12px',
          display: 'none', flexDirection: 'column', gap: 4,
          boxShadow: '0 16px 48px rgba(0,0,0,0.4)',
        }}>
          {navLinks.map(link => (
            <a key={link.id} href={link.href}
              onClick={() => setMobileOpen(false)}
              style={{
                fontFamily: '"Plus Jakarta Sans", sans-serif', fontSize: 15, fontWeight: 500,
                color: activeId === link.id ? 'var(--accent-mint)' : 'var(--text-primary)',
                textDecoration: 'none', padding: '12px 16px', borderRadius: 10,
                transition: 'background 0.2s ease',
                background: activeId === link.id ? 'rgba(0,217,160,0.08)' : 'transparent',
              }}
            >{link.label}</a>
          ))}
          <div style={{ height: 1, background: 'var(--border-subtle)', margin: '4px 0' }} />
          <a href="https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight"
            target="_blank" rel="noopener"
            onClick={() => setMobileOpen(false)}
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              margin: '4px 0', padding: '13px 16px', borderRadius: 10,
              background: 'var(--accent-mint)', color: '#0A0A0B',
              fontFamily: '"Plus Jakarta Sans", sans-serif', fontSize: 14, fontWeight: 700,
              textDecoration: 'none',
            }}
          >Book a call →</a>
        </div>
      )}

      <style>{`
        @media (max-width: 920px) {
          .nav-capsule { display: none !important; }
          .nav-mobile-trigger { display: flex !important; }
          .nav-mobile-menu { display: flex !important; }
          .nav-cta { display: none !important; }
        }
        @media (max-width: 540px) {
          .nav-cta { display: none !important; }
        }
        @media (max-width: 920px) {
          .nav-mobile-menu {
            position: fixed !important;
            top: 64px !important;
            left: 12px !important;
            right: 12px !important;
            z-index: 200;
          }
        }
      `}</style>
    </nav>
  );
}

Object.assign(window, { Nav });
