/* Sticky top nav with scroll progress, theme toggle, smooth scroll. */

const NAV_LINKS = [
  { href: '#work', label: 'Work' },
  { href: '#about', label: 'About' },
  { href: '#process', label: 'Process' },
  { href: '#stack', label: 'Stack' },
  { href: '#contact', label: 'Contact' },
];

// Scroll progress bar — pinned to top of viewport
const ScrollProgress = () => {
  const { scrollYProgress } = useScroll();
  const scaleX = useSpring(scrollYProgress, { stiffness: 120, damping: 22, mass: 0.4 });
  return (
    <motion.div
      className="fixed top-0 left-0 right-0 h-[2px] origin-left z-50"
      style={{ scaleX, background: 'var(--accent)' }}
    />
  );
};

// Theme toggle button — animated sun/moon swap
const ThemeToggle = ({ theme, onToggle }) => {
  const isDark = theme === 'dark';
  return (
    <button
      onClick={onToggle}
      className="relative grid place-items-center w-10 h-10 rounded-full overflow-hidden transition-colors"
      style={{ border: '1px solid var(--line-strong)', color: 'var(--fg)' }}
      aria-label={`Switch to ${isDark ? 'light' : 'dark'} mode`}
      title={`Switch to ${isDark ? 'light' : 'dark'} mode`}
    >
      <AnimatePresence mode="wait" initial={false}>
        <motion.span
          key={isDark ? 'moon' : 'sun'}
          initial={{ y: -20, opacity: 0, rotate: -90 }}
          animate={{ y: 0, opacity: 1, rotate: 0 }}
          exit={{ y: 20, opacity: 0, rotate: 90 }}
          transition={{ duration: 0.35, ease: [0.2, 0.7, 0.2, 1] }}
          className="absolute inset-0 grid place-items-center"
        >
          {isDark ? <I.Moon size={16} /> : <I.Sun size={16} />}
        </motion.span>
      </AnimatePresence>
    </button>
  );
};

const Nav = ({ theme, onThemeToggle }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const [active, setActive] = React.useState('');

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    const ids = NAV_LINKS.map(l => l.href.slice(1));
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: '-40% 0px -55% 0px', threshold: 0 });
    els.forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);

  return (
    <>
      <ScrollProgress />
      <motion.header
        initial={{ y: -32, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.7, delay: 0.1, ease: [0.2, 0.7, 0.2, 1] }}
        className={`fixed top-0 left-0 right-0 z-40 transition-all duration-300 ${scrolled ? 'nav-blur' : ''}`}
      >
        <div className={`mx-auto max-w-[1280px] px-6 md:px-10 flex items-center justify-between transition-all duration-300 ${scrolled ? 'h-14' : 'h-20'}`}>
          {/* Logo */}
          <a href="#top" className="flex items-center gap-2.5 group">
            <motion.span
              whileHover={{ rotate: 90 }}
              transition={{ duration: 0.4, ease: [0.2, 0.7, 0.2, 1] }}
              className="relative grid place-items-center w-8 h-8 rounded-lg"
              style={{ background: 'var(--accent)' }}
            >
              <span className="font-mono text-xs font-semibold text-white">A</span>
              <span className="absolute -inset-0.5 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity blur-md" style={{ background: 'var(--accent)' }} aria-hidden></span>
            </motion.span>
            <div className="leading-tight">
              <div className="text-sm font-medium tracking-tight">MagnAgency</div>
              <div className="font-mono text-[10px] uppercase tracking-[0.18em]" style={{ color: 'var(--fg-dim)' }}>Engineer</div>
            </div>
          </a>

          {/* Desktop nav */}
          <nav className="hidden md:flex items-center gap-1 p-1 rounded-full" style={{ border: '1px solid var(--line)', background: 'color-mix(in oklab, var(--bg-elev) 60%, transparent)' }}>
            {NAV_LINKS.map(link => (
              <a
                key={link.href}
                href={link.href}
                className="relative px-4 py-1.5 text-[13px] rounded-full transition-colors"
                style={{ color: active === link.href.slice(1) ? 'var(--fg)' : 'var(--fg-muted)' }}
              >
                {active === link.href.slice(1) && (
                  <motion.span
                    layoutId="nav-active"
                    className="absolute inset-0 rounded-full -z-0"
                    style={{ background: 'var(--accent-soft)' }}
                    transition={{ type: 'spring', stiffness: 380, damping: 30 }}
                    aria-hidden
                  />
                )}
                <span className="relative z-10">{link.label}</span>
              </a>
            ))}
          </nav>

          {/* Right side */}
          <div className="hidden md:flex items-center gap-3">
            <span className="flex items-center gap-2 px-3 py-1.5 rounded-full font-mono text-[11px]" style={{ border: '1px solid var(--line)', color: 'var(--fg-muted)' }}>
              <span className="relative flex h-2 w-2">
                <span className="absolute inset-0 rounded-full animate-ping opacity-60" style={{ background: '#10b981' }}></span>
                <span className="relative rounded-full h-2 w-2" style={{ background: '#10b981' }}></span>
              </span>
              Available
            </span>
            <ThemeToggle theme={theme} onToggle={onThemeToggle} />
            <Btn href="#contact" variant="primary" className="!h-9 !px-4 !text-[13px]">Get in touch</Btn>
          </div>

          {/* Mobile right */}
          <div className="md:hidden flex items-center gap-2">
            <ThemeToggle theme={theme} onToggle={onThemeToggle} />
            <button onClick={() => setOpen(o => !o)} className="grid place-items-center w-10 h-10 rounded-lg" style={{ border: '1px solid var(--line)' }} aria-label="Menu">
              {open ? <I.Close size={18} /> : <I.Menu size={18} />}
            </button>
          </div>
        </div>

        <AnimatePresence>
          {open && (
            <motion.div
              initial={{ opacity: 0, y: -8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              className="md:hidden mx-6 mb-3 rounded-xl p-2 nav-blur"
              style={{ border: '1px solid var(--line)' }}
            >
              {NAV_LINKS.map(l => (
                <a key={l.href} href={l.href} onClick={() => setOpen(false)} className="block px-4 py-3 rounded-lg text-sm" style={{ color: 'var(--fg-muted)' }}>{l.label}</a>
              ))}
              <a href="#contact" onClick={() => setOpen(false)} className="block px-4 py-3 mt-1 rounded-lg text-sm font-medium text-white text-center" style={{ background: 'var(--accent)' }}>Get in touch</a>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.header>
    </>
  );
};

window.Nav = Nav;
