'use client';

/**
 * Table of Contents - Production Version
 *
 * Based on Variant A: Clean & Minimal (no changes needed)
 *
 * Features:
 * - Small indicator dots for section levels
 * - Smooth scroll to section
 * - Active section highlighting (purple text)
 * - Sticky positioning
 * - Minimal visual weight
 *
 * Behavior:
 * - Extracts H2 and H3 headings from content
 * - Tracks scroll position to highlight active section
 * - Click to smooth scroll to section
 */

import { useEffect, useState } from 'react';

interface TocItem {
  id: string;
  text: string;
  level: number;
}

interface DocsTOCProps {
  items: TocItem[];
}

export const DocsTOC = ({ items }: DocsTOCProps) => {
  const [activeId, setActiveId] = useState<string>('');

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      { rootMargin: '-20% 0px -35% 0px' }
    );

    items.forEach((item) => {
      const element = document.getElementById(item.id);
      if (element) observer.observe(element);
    });

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

  const scrollToSection = (id: string) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

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

  return (
    <nav className="p-6 sticky top-6" aria-label="Table of contents">
      <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">
        On This Page
      </h3>

      <ul className="space-y-2.5 text-sm">
        {items.map((item) => {
          const isActive = activeId === item.id;
          const isH3 = item.level === 3;

          return (
            <li key={item.id} className={isH3 ? 'ml-4' : ''}>
              <button
                onClick={() => scrollToSection(item.id)}
                className={`
                  flex items-start gap-2 text-left w-full transition-colors group
                  ${isActive ? 'text-purple-400' : 'text-gray-500 hover:text-gray-300'}
                `}
              >
                {/* Indicator dot */}
                <span
                  className={`
                    flex-shrink-0 w-1 h-1 rounded-full mt-2 transition-colors
                    ${isActive ? 'bg-purple-400' : 'bg-gray-600 group-hover:bg-gray-400'}
                  `}
                ></span>
                <span className="line-clamp-2">{item.text}</span>
              </button>
            </li>
          );
        })}
      </ul>
    </nav>
  );
};
