'use client';

import { useEffect, useState } from 'react';
import { cn } from '@/lib/utils';

export interface WorkerProfileNavItem {
  id: string;
  label: string;
  /** Shorter label for narrow screens */
  shortLabel?: string;
}

interface WorkerProfileNavProps {
  items: WorkerProfileNavItem[];
  /** When set, nav acts as tabs (show/hide) instead of scroll anchors. */
  activeId?: string;
  onActiveChange?: (id: string) => void;
}

export function WorkerProfileNav({ items, activeId, onActiveChange }: WorkerProfileNavProps) {
  const isTabMode = onActiveChange != null;
  const [scrollActiveId, setScrollActiveId] = useState(items[0]?.id ?? '');
  const currentActiveId = isTabMode ? (activeId ?? items[0]?.id ?? '') : scrollActiveId;

  useEffect(() => {
    if (isTabMode || items.length === 0) return;

    const visible = new Map<string, number>();
    const observers: IntersectionObserver[] = [];

    for (const item of items) {
      const el = document.getElementById(item.id);
      if (!el) continue;

      const observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            visible.set(item.id, entry.intersectionRatio);
          } else {
            visible.delete(item.id);
          }

          const next =
            [...visible.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? items[0].id;
          setScrollActiveId(next);
        },
        { rootMargin: '-25% 0px -55% 0px', threshold: [0, 0.25, 0.5, 1] }
      );

      observer.observe(el);
      observers.push(observer);
    }

    return () => observers.forEach((observer) => observer.disconnect());
  }, [items, isTabMode]);

  if (items.length === 0) return null;

  const tabClassName = (itemId: string) =>
    cn(
      'shrink-0 rounded-none px-3 py-2 text-xs font-semibold transition-colors whitespace-nowrap sm:px-3.5 sm:text-sm',
      currentActiveId === itemId
        ? 'worker-profile-nav-active'
        : 'text-slate-600 hover:bg-[var(--home-sand)] hover:text-slate-900'
    );

  return (
    <nav
      aria-label="Worker profile sections"
      className="sticky top-14 z-30 border-b border-[#e2ddd2] bg-[#fffdf9]/95 backdrop-blur supports-[backdrop-filter]:bg-[#fffdf9]/85 lg:top-0"
    >
      <div className="flex gap-1 overflow-x-auto py-2 scrollbar-none">
        {items.map((item) =>
          isTabMode ? (
            <button
              key={item.id}
              type="button"
              role="tab"
              aria-selected={currentActiveId === item.id}
              onClick={() => onActiveChange(item.id)}
              className={tabClassName(item.id)}
            >
              <span className="sm:hidden">{item.shortLabel ?? item.label}</span>
              <span className="hidden sm:inline">{item.label}</span>
            </button>
          ) : (
            <a key={item.id} href={`#${item.id}`} className={tabClassName(item.id)}>
              <span className="sm:hidden">{item.shortLabel ?? item.label}</span>
              <span className="hidden sm:inline">{item.label}</span>
            </a>
          )
        )}
      </div>
    </nav>
  );
}
