"use client";
import React, { useEffect, useRef, useState } from "react";

type Heading = { id: string; text: string; level: number };

export function TableOfContents({ headings }: { headings: Heading[] }) {
  const [activeId, setActiveId] = useState<string | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const observerRef = useRef<IntersectionObserver | null>(null);

  useEffect(() => {
    // Disconnect old observer if it exists
    if (observerRef.current) {
      observerRef.current.disconnect();
    }

    // Only set up observer if we have headings
    if (headings.length === 0) {
      setActiveId(null);
      return;
    }

    const visibleHeadings = new Map<string, number>();
    
    const callback: IntersectionObserverCallback = (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          visibleHeadings.set(entry.target.id, entry.boundingClientRect.top);
        } else {
          visibleHeadings.delete(entry.target.id);
        }
      });
      
      // Find the topmost visible heading
      if (visibleHeadings.size > 0) {
        const sortedHeadings = Array.from(visibleHeadings.entries())
          .sort((a, b) => a[1] - b[1]);
        setActiveId(sortedHeadings[0][0]);
      } else {
        setActiveId(null);
      }
    };
    
    const observer = new IntersectionObserver(callback, {
      rootMargin: "-80px 0px -55% 0px",
      threshold: 0.1,
    });
    observerRef.current = observer;
    
    headings.forEach((h) => {
      const el = document.getElementById(h.id);
      if (el) observer.observe(el);
    });
    
    return () => observer.disconnect();
  }, [headings]);

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, headingId: string) => {
    e.preventDefault();
    const element = document.getElementById(headingId);
    if (element) {
      // Calculate the scroll offset to account for fixed header
      // Mobile: 80px, Desktop: 120px
      const isMobile = window.innerWidth < 768;
      const scrollOffset = isMobile ? 80 : 120;
      
      const elementPosition = element.getBoundingClientRect().top + window.scrollY;
      const targetPosition = elementPosition - scrollOffset;
      
      window.scrollTo({
        top: targetPosition,
        behavior: "smooth",
      });
      
      // Update URL without causing a page reload
      window.history.pushState(null, "", `#${headingId}`);
      // Close mobile menu after click
      setIsOpen(false);
    }
  };

  return (
    <>
      {/* Mobile Toggle Button */}
      <button
        className="md:hidden w-full mb-4 px-4 py-2 bg-blue-50 text-blue-600 border border-blue-200 rounded-lg font-medium text-sm transition hover:bg-blue-100"
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
        aria-label="Alternar tabela de conteúdos"
      >
        {isOpen ? "✕ Fechar conteúdos" : "☰ Mostrar conteúdos"}
      </button>

      {/* Desktop Sidebar + Mobile Collapsible */}
      <nav
        aria-label="Tabela de conteúdos"
        className={`
          md:sticky md:max-h-[calc(100vh-140px)] md:overflow-auto md:block
          ${isOpen ? "block" : "hidden md:block"}
          mb-6 md:mb-0 p-4 md:p-0
          bg-white md:bg-transparent
          border md:border-none border-gray-200 md:border-0
          rounded-lg md:rounded-none
        `}
        style={{ top: "120px" }}
      >
        <ul className="space-y-1">
          {headings.map((h) => (
            <li key={h.id} style={{ paddingLeft: (h.level - 1) * 12 }}>
              <a
                href={`#${h.id}`}
                onClick={(e) => handleClick(e, h.id)}
                className={`
                  block py-1 px-2 rounded transition
                  ${
                    activeId === h.id
                      ? "font-semibold text-blue-600 bg-blue-50"
                      : "text-gray-700 hover:bg-gray-100"
                  }
                `}
              >
                {h.text}
              </a>
            </li>
          ))}
        </ul>
      </nav>
    </>
  );
}
