'use client';

import { useEffect, useState } from 'react';
import { useTranslation } from '@/lib/i18n';

export type Heading = {
  level: 2 | 3;
  slug: string;
  text: string;
};

interface DocsTOCProps {
  headings: Heading[];
}

export default function DocsTOC({ headings }: DocsTOCProps) {
  const { t } = useTranslation();
  const [activeSlug, setActiveSlug] = useState<string>(headings[0]?.slug ?? '');

  useEffect(() => {
    if (headings.length === 0) return;

    const observer = new IntersectionObserver(
      entries => {
        const visible = entries
          .filter(entry => entry.isIntersecting)
          .map(entry => entry.target as HTMLElement)
          .sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top);

        if (visible.length > 0 && visible[0].id) {
          setActiveSlug(visible[0].id);
        }
      },
      { rootMargin: '-80px 0px -60% 0px', threshold: 0 },
    );

    const elements: HTMLElement[] = [];
    for (const h of headings) {
      const el = document.getElementById(h.slug);
      if (el) {
        observer.observe(el);
        elements.push(el);
      }
    }

    return () => {
      for (const el of elements) observer.unobserve(el);
      observer.disconnect();
    };
  }, [headings]);

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

  return (
    <aside style={{
      position: 'sticky',
      top: '52px',
      alignSelf: 'flex-start',
      maxHeight: 'calc(100vh - 52px)',
      overflowY: 'auto',
      padding: '24px 0 32px 20px',
      borderLeft: '1px solid #ececf0',
    }}>
      <div style={{
        fontSize: '11.5px',
        fontWeight: 700,
        color: '#6b7280',
        textTransform: 'uppercase',
        letterSpacing: '0.6px',
        marginBottom: '12px',
        paddingLeft: '10px',
      }}>
        {t('docs.tableOfContents')}
      </div>
      <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
        {headings.map(h => {
          const isActive = h.slug === activeSlug;
          return (
            <li key={h.slug}>
              <a
                href={`#${h.slug}`}
                style={{
                  display: 'block',
                  padding: '5px 10px',
                  paddingLeft: h.level === 3 ? '22px' : '10px',
                  fontSize: '13px',
                  fontWeight: isActive ? 600 : 500,
                  color: isActive ? '#5c5fbc' : '#6b7280',
                  textDecoration: 'none',
                  borderLeft: isActive ? '2px solid #5c5fbc' : '2px solid transparent',
                  lineHeight: 1.45,
                  transition: 'color 0.15s',
                }}
                onMouseEnter={e => {
                  if (!isActive) e.currentTarget.style.color = '#1a1a2e';
                }}
                onMouseLeave={e => {
                  if (!isActive) e.currentTarget.style.color = '#6b7280';
                }}
              >
                {h.text}
              </a>
            </li>
          );
        })}
      </ul>
    </aside>
  );
}
