"use client";

import { useState } from "react";

/**
 * The live site's "Table of Content" box on a sample page — collapsed by
 * default, built by walking the article's own `<h2>` headings
 * (`sample.php`'s `$xpath->query("/html/body/h2")`), not stored anywhere in
 * the CMS. `items` are real headings found in the article's own HTML
 * (`extractSampleToc` below); clicking one scrolls to that heading the same
 * way the live `scrollTodiv1()` does.
 */
export function SampleToc({ items }: { items: { id: string; label: string }[] }) {
  const [open, setOpen] = useState(false);

  if (items.length === 0) return null;

  return (
    <div className="border border-slate-400 bg-slate-50 rounded-md px-4 py-3 my-5">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="w-full flex items-center justify-between text-left text-lg font-semibold text-slate-800"
      >
        Table of Content
        <span
          className={`inline-block w-2.5 h-2.5 border-b-2 border-l-2 border-slate-500 transition-transform ${
            open ? "rotate-[135deg]" : "-rotate-45"
          }`}
        />
      </button>
      {open && (
        <ol className="mt-4 ml-7 space-y-2.5">
          {items.map((item, i) => (
            <li key={item.id} className="relative text-sm text-slate-800">
              <span className="absolute -left-7 top-0.5 w-[18px] h-[18px] rounded-full bg-[#5C7A36] text-white text-[11px] flex items-center justify-center">
                {i + 1}
              </span>
              <a
                href={`#${item.id}`}
                className="underline hover:text-[#F58E0E]"
                onClick={(e) => {
                  e.preventDefault();
                  document.getElementById(item.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
                }}
              >
                {item.label}
              </a>
            </li>
          ))}
        </ol>
      )}
    </div>
  );
}
