import React, { useEffect, useState } from "react";

const TableOfContents = () => {
  const [headings, setHeadings] = useState([]);

  useEffect(() => {
    // Function to extract headings
    const headingElements = Array.from(document.querySelectorAll("h2, h3"));
    const headingList = headingElements.map((heading, index) => {
      // Create a unique ID for each heading if it doesn't have one
      if (!heading.id) {
        heading.id = `heading-${index}`;
      }
      return {
        id: heading.id,
        text: heading.innerText,
        level: heading.tagName.toLowerCase(),
      };
    });
    setHeadings(headingList);
  }, []);

  return (
    <nav aria-label="Table of contents" className="p-4 bg-gray-50 rounded-lg">
      <ul className="list-none pl-0">
        {headings.map((heading) => (
          <li
            key={heading.id}
            className={`mt-2 ${heading.level === "h3" ? "ml-4" : ""}`}
          >
            <a
              href={`#${heading.id}`}
              className="text-blue-600 hover:text-blue-800"
            >
              {heading.text}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
};

export default TableOfContents;
