const Nav = () => {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive] = React.useState('top');
  const scrollRef = React.useRef(null);

  const links = [
    { href: '#models', label: '獲利方案' },
    { href: '#spokesperson', label: '品牌代言' },
    { href: '#support', label: '優質服務' },
    { href: '#process', label: '合作流程' },
    { href: '#faq', label: '常見問題' },
    { href: '#apply', label: '立即申請' },
  ];

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

  // Scrollspy: find section crossing viewport anchor line
  React.useEffect(() => {
    const ids = ['top', ...links.map(l => l.href.slice(1))];

    const compute = () => {
      // Anchor = 30% from top of viewport (feels natural — section
      // becomes "active" shortly after its top enters the upper third)
      const anchor = window.innerHeight * 0.3;
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        const rect = el.getBoundingClientRect();
        if (rect.top <= anchor) {
          current = id;
        } else {
          break;
        }
      }
      // Snap to last section when near bottom of page
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 80) {
        current = ids[ids.length - 1];
      }
      setActive(prev => (prev === current ? prev : current));
    };

    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      window.requestAnimationFrame(() => {
        compute();
        ticking = false;
      });
    };

    compute();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', compute);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', compute);
    };
  }, []);

  // Scroll the active chip into view on mobile nav
  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const activeEl = el.querySelector(`[data-nav="${active}"]`);
    if (activeEl && typeof activeEl.scrollIntoView !== 'undefined') {
      const elRect = el.getBoundingClientRect();
      const targetRect = activeEl.getBoundingClientRect();
      const offset = targetRect.left - elRect.left - (elRect.width / 2) + (targetRect.width / 2);
      el.scrollTo({ left: el.scrollLeft + offset, behavior: 'smooth' });
    }
  }, [active]);

  return (
    <nav className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${scrolled ? 'nav-glass' : ''}`}>
      <div className="max-w-[1440px] mx-auto">
        {/* Top row: brand + CTA */}
        <div className="flex items-center justify-between h-16 lg:h-20 px-5 lg:px-10">
          <a href="#top" className="flex items-center gap-3 shrink-0">
            <img src="assets/logo.png" alt="WEDAR" className="h-6 lg:h-7 w-auto"/>
          </a>

          {/* Desktop links inline */}
          <div className="hidden lg:flex items-center gap-8">
            {links.slice(0, -1).map(l => (
              <a
                key={l.href}
                href={l.href}
                data-nav={l.href.slice(1)}
                className={`relative text-[13px] font-bold transition-colors ${
                  active === l.href.slice(1)
                    ? 'text-wedar-green'
                    : 'text-wedar-primary/80 hover:text-wedar-primary'
                }`}
              >
                {l.label}
                {active === l.href.slice(1) && (
                  <span className="absolute -bottom-1 left-0 right-0 h-[2px] bg-wedar-green"/>
                )}
              </a>
            ))}
          </div>

          <a
            href="#apply"
            className="group inline-flex items-center gap-2 lg:gap-3 rounded-full bg-wedar-primary pl-4 lg:pl-5 pr-1.5 lg:pr-2 py-1.5 lg:py-2 text-wedar-bone font-bold text-[12px] lg:text-[13px] tracking-wide hover:bg-wedar-deep transition-colors shrink-0"
          >
            <span className="hidden sm:inline">立即申請合作</span>
            <span className="sm:hidden">申請</span>
            <span className="flex h-7 w-7 lg:h-8 lg:w-8 items-center justify-center rounded-full bg-wedar-lime text-wedar-primary">
              <svg className="btn-arrow" width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </span>
          </a>
        </div>

        {/* Mobile horizontal scroll nav */}
        <div className="lg:hidden border-t border-wedar-primary/10">
          <div
            ref={scrollRef}
            className="flex gap-1 overflow-x-auto no-scrollbar px-4 py-2"
            style={{ scrollbarWidth: 'none' }}
          >
            {links.map(l => {
              const isActive = active === l.href.slice(1);
              return (
                <a
                  key={l.href}
                  href={l.href}
                  data-nav={l.href.slice(1)}
                  className={`shrink-0 px-3.5 py-2 rounded-full text-[12.5px] font-bold whitespace-nowrap transition-colors ${
                    isActive
                      ? 'bg-wedar-primary text-wedar-lime'
                      : 'text-wedar-primary/70 hover:text-wedar-primary'
                  }`}
                >
                  {l.label}
                </a>
              );
            })}
          </div>
        </div>
      </div>
    </nav>
  );
};

Object.assign(window, { Nav });
