import { ListTree } from 'lucide-react';
import { cn } from '@/lib/utils';
import { TocItem } from './SkillViewer';
import { ScrollArea } from '@/components/ui/scroll-area';

interface TableOfContentsProps {
  toc: TocItem[];
}

export function TableOfContents({ toc }: TableOfContentsProps) {
  if (toc.length === 0) {
    return null;
  }

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, id: string) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  return (
    <div className="flex h-full flex-col">
      <div className="shrink-0 border-b border-border/40 px-4 py-3">
        <h3 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-widest text-muted-foreground">
          <ListTree className="h-3.5 w-3.5" />
          On this page
        </h3>
      </div>
      <ScrollArea className="min-h-0 flex-1">
        <nav className="space-y-0.5 p-3">
          {toc.map((item) => (
            <a
              key={item.id}
              href={`#${item.id}`}
              onClick={(e) => handleClick(e, item.id)}
              className={cn(
                'block rounded-md px-2 py-1.5 text-[13px] leading-snug cursor-pointer transition-colors duration-150',
                'text-muted-foreground hover:bg-accent/60 hover:text-foreground',
                item.level === 1 && 'font-medium text-foreground/90',
                item.level === 2 && 'pl-4',
                item.level > 2 && 'pl-6 text-[12px] opacity-80'
              )}
            >
              <span className="line-clamp-2">{item.text}</span>
            </a>
          ))}
        </nav>
      </ScrollArea>
    </div>
  );
}
