import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Button } from '@/shared/ui/button';
import { PageContainer } from '@/shared/ui/page-container';

interface ReportNavProps {
  sections: { id: string; label: string }[];
  /** 좌측 슬롯 — 보통 "워크스페이스로" 같은 뒤로가기 링크 */
  leftSlot?: ReactNode;
  /** 우측 슬롯 — 보통 리포트↔플랜 점프 버튼 등 보조 액션 */
  rightSlot?: ReactNode;
}

export function ReportNav({ sections, leftSlot, rightSlot }: 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);
    const navEl = navRef.current;
    if (!activeTab || !navEl) return;

    // scrollIntoView 는 sticky 컨테이너에서 세로 스크롤까지 트리거하는 부작용이 있어
    // (초기 마운트 시 sticky 위치 계산 전 탭의 실제 y 로 페이지를 끌어내림 → 첫 섹션 점프)
    // 가로 스크롤만 직접 제어합니다.
    const targetLeft = activeTab.offsetLeft - (navEl.clientWidth - activeTab.offsetWidth) / 2;
    navEl.scrollTo({ left: targetLeft, behavior: 'smooth' });
  }, [activeId]);

  const handleClick = (id: string) => {
    const el = document.getElementById(id);
    if (!el) return;
    // sticky Navbar (80px) + ReportNav (~48px) 오프셋으로 섹션 상단 가려짐 방지
    const STICKY_OFFSET = 128;
    const y = el.getBoundingClientRect().top + window.scrollY - STICKY_OFFSET;
    window.scrollTo({ top: y, behavior: 'smooth' });
  };

  return (
    <nav data-report-nav className="sticky top-20 z-40 bg-white/95 border-b border-slate-100">
      <PageContainer className="px-0 flex items-center gap-3">
        {leftSlot && (
          <div className="shrink-0 pl-4 md:pl-6 pt-2" data-no-print>
            {leftSlot}
          </div>
        )}
        <div
          ref={navRef}
          className="flex-1 min-w-0 flex overflow-x-auto scrollbar-hide"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          {sections.map(({ id, label }) => (
            <Button
              type="button"
              variant="ghost"
              key={id}
              ref={(el) => {
                if (el) tabRefs.current.set(id, el);
              }}
              onClick={() => handleClick(id)}
              className={`
                shrink-0 px-4 py-3 h-auto text-sm font-medium whitespace-nowrap
                border-b-2 rounded-none hover:bg-transparent
                ${activeId === id
                  ? 'border-brand-purple-vivid text-brand-navy hover:text-brand-navy'
                  : 'border-transparent text-slate-500 hover:text-slate-700'
                }
              `}
            >
              {label}
            </Button>
          ))}
        </div>
        {rightSlot && (
          <div className="shrink-0 pr-4 md:pr-6" data-no-print>
            {rightSlot}
          </div>
        )}
      </PageContainer>
    </nav>
  );
}
