"use client";

import { IconChevronDown } from "@tabler/icons-react";
import { useCallback, useEffect, useRef, useState } from "react";

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

interface TocProps {
  items: TocItem[];
}

export function TableOfContents({ items }: TocProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [activeSlug, setActiveSlug] = useState<string>("");
  const [isSticky, setIsSticky] = useState(false);
  const tocRef = useRef<HTMLElement>(null);
  const placeholderRef = useRef<HTMLDivElement>(null);

  // Smooth scroll handler
  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLAnchorElement>, slug: string) => {
      e.preventDefault();
      const element = document.getElementById(slug);
      if (element) {
        const headerOffset = 100; // Account for fixed header
        const elementPosition = element.getBoundingClientRect().top;
        const offsetPosition = elementPosition + window.scrollY - headerOffset;

        window.scrollTo({
          top: offsetPosition,
          behavior: "smooth",
        });
      }
    },
    []
  );

  // Active section tracking with Intersection Observer
  useEffect(() => {
    if (!items || items.length === 0) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveSlug(entry.target.id);
          }
        });
      },
      {
        rootMargin: "-100px 0px -66% 0px",
        threshold: 0,
      }
    );

    // Observe all heading elements
    items.forEach((item) => {
      const element = document.getElementById(item.slug);
      if (element) {
        observer.observe(element);
      }
    });

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

  // Sticky behavior - stick after scrolling past the TOC
  useEffect(() => {
    if (!tocRef.current) return;

    const handleScroll = () => {
      if (!placeholderRef.current) return;

      const placeholderRect = placeholderRef.current.getBoundingClientRect();
      // Become sticky when the placeholder top goes above the header
      const shouldStick = placeholderRect.top < 100;
      setIsSticky(shouldStick);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

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

  const tocContent = (
    <div className="max-w-2xl mx-auto">
      <nav
        ref={tocRef}
        aria-label="Table des matières"
        className={`border border-gray-100 rounded-lg bg-white transition-shadow ${
          isSticky ? "shadow-lg" : ""
        }`}
      >
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="flex items-center justify-between w-full p-4 text-left"
          aria-expanded={isOpen}
        >
          <span className="text-sm font-semibold text-black uppercase">
            Sommaire
          </span>
          <IconChevronDown
            className={`w-5 h-5 text-gray-900 transition-transform duration-200 ${
              isOpen ? "rotate-180" : ""
            }`}
          />
        </button>
        {isOpen && (
          <ul className="px-4 pb-4 space-y-2 max-h-[50vh] overflow-y-auto overscroll-contain">
            {items.map((item, index) => (
              <li
                key={`${item.slug}-${index}`}
                className={item.level === 3 ? "ml-4" : ""}
              >
                <a
                  href={`#${item.slug}`}
                  onClick={(e) => handleClick(e, item.slug)}
                  className={`text-base transition-colors block py-0.2 ${
                    activeSlug === item.slug
                      ? "text-orange-500 font-medium"
                      : "text-gray-800 hover:text-orange-700"
                  }`}
                >
                  {item.text}
                </a>
              </li>
            ))}
          </ul>
        )}
      </nav>
    </div>
  );

  return (
    <div className="mt-10 mb-6">
      {/* Placeholder to maintain layout when TOC becomes fixed */}
      <div ref={placeholderRef} className={isSticky ? "h-auto" : ""}>
        {!isSticky && tocContent}
      </div>

      {/* Sticky TOC - centered at bottom */}
      {isSticky && (
        <div className="fixed bottom-4 left-1/2 -translate-x-1/2 w-[90%] max-w-md z-40">
          {tocContent}
        </div>
      )}
    </div>
  );
}
