import { useEffect, useRef, useState } from 'react';

interface ReportNavProps {
  sections: { id: string; label: string }[];
}

export function ReportNav({ sections }: ReportNavProps) {
  const [activeId, setActiveId] = useState(sections[0]?.id ?? '');
  const navRef = useRef<HTMLDivElement>(null);
  const tabRefs = useRef<Map<string, HTMLButtonElement>>(new Map());

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);

        if (visible.length > 0) {
          setActiveId(visible[0].target.id);
        }
      },
      { rootMargin: '-100px 0px -60% 0px', threshold: 0 }
    );

    sections.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

    return () => observer.disconnect();
  }, [sections]);

  useEffect(() => {
    const activeTab = tabRefs.current.get(activeId);
    if (activeTab && navRef.current) {
      activeTab.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center',
      });
    }
  }, [activeId]);

  const handleClick = (id: string) => {
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <nav data-report-nav className="sticky top-20 z-40 bg-white/80 backdrop-blur-lg border-b border-slate-100">
      <div
        ref={navRef}
        className="max-w-7xl mx-auto flex overflow-x-auto scrollbar-hide"
        style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
      >
        {sections.map(({ id, label }) => (
          <button
            key={id}
            ref={(el) => {
              if (el) tabRefs.current.set(id, el);
            }}
            onClick={() => handleClick(id)}
            className={`
              shrink-0 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap
              border-b-2
              ${activeId === id
                ? 'border-[#6C5CE7] text-[#0A1128]'
                : 'border-transparent text-slate-500 hover:text-slate-700'
              }
            `}
          >
            {label}
          </button>
        ))}
      </div>
    </nav>
  );
}
