'use client';

import { useEffect, useState } from 'react';
import { ChevronDown } from 'lucide-react';
import type { TocItem } from '../types';

interface BlogTOCProps {
  items: TocItem[];
}

export const BlogTOC = ({ items }: BlogTOCProps) => {
  const [activeId, setActiveId] = useState<string>('');
  const [isExpanded, setIsExpanded] = useState(true);

  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 (
    <div className="rounded-xl bg-gray-50 border border-gray-200 p-5 shadow-sm">
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full flex items-center justify-between text-xs font-bold text-gray-500 uppercase tracking-wider border-b border-gray-200 pb-2 hover:text-gray-700 transition-colors"
      >
        <span>On This Page</span>
        <ChevronDown
          className={`w-4 h-4 transition-transform duration-200 ${
            isExpanded ? '' : '-rotate-90'
          }`}
        />
      </button>
      <div
        className={`overflow-hidden transition-all duration-300 ${
          isExpanded ? 'max-h-[2000px] opacity-100 mt-4' : 'max-h-0 opacity-0 mt-0'
        }`}
      >
        <nav className="flex flex-col space-y-3 text-sm" aria-label="Table of contents">
          {items.map((item) => {
            const isActive = activeId === item.id;
            const isH3 = item.level === 3;

            return (
              <button
                key={item.id}
                onClick={() => scrollToSection(item.id)}
                className={`
                  text-left pl-2 border-l-2 transition-colors
                  ${isH3 ? 'ml-3' : ''}
                  ${
                    isActive
                      ? 'text-gray-900 font-medium border-violet-500'
                      : 'text-gray-500 border-transparent hover:text-gray-900'
                  }
                `}
              >
                {item.text}
              </button>
            );
          })}
        </nav>
      </div>
    </div>
  );
};
