"use client";

import { useEffect } from "react";

/**
 * Wires up click behavior for the `.draft-tabs` vertical tab widget CMS
 * article bodies embed (see `app/draft-tabs.css`) — the live site's own JS
 * (not exposed by the API, so not portable) toggles `.active` on the
 * clicked `<li>` and shows only the matching content panel; everything else
 * defaults to hidden. This wires the same behavior up generically, by
 * sibling index within each `.draft-tabs` section found in the rendered
 * article body, rather than relying on the CMS's own `Drf0N`/`DrfBox1N` id
 * numbering (so it keeps working regardless of how many tabs a given
 * article has, or what its ids happen to be).
 *
 * Runs as a plain DOM-query effect rather than parsing the CMS HTML into
 * JSX, since the tab markup arrives via `dangerouslySetInnerHTML` — the
 * same approach this app already uses for scoping CSS to CMS-authored
 * class names (see `.prose` rules in globals.css/strips.css).
 */
export function DraftTabs() {
  useEffect(() => {
    const sections = document.querySelectorAll<HTMLElement>(".prose .draft-tabs");
    const cleanups: Array<() => void> = [];

    sections.forEach((section) => {
      const tabs = Array.from(section.querySelectorAll<HTMLElement>(".left-section-drf > li"));
      const panels = Array.from(section.querySelectorAll<HTMLElement>(".right-section-drf > .drafrght1"));
      if (tabs.length === 0 || panels.length === 0) return;

      // Default to whichever tab the CMS marked `.active` (matches the live
      // site's `#DrfBox11 { display: block }` default), falling back to the
      // first one.
      const initialIndex = Math.max(
        0,
        tabs.findIndex((tab) => tab.classList.contains("active"))
      );
      panels.forEach((panel, i) => panel.classList.toggle("active", i === initialIndex));
      tabs.forEach((tab, i) => tab.classList.toggle("active", i === initialIndex));

      const listeners: Array<[HTMLElement, () => void]> = [];
      tabs.forEach((tab, index) => {
        const onClick = () => {
          tabs.forEach((t, i) => t.classList.toggle("active", i === index));
          panels.forEach((p, i) => p.classList.toggle("active", i === index));
        };
        tab.addEventListener("click", onClick);
        listeners.push([tab, onClick]);
      });

      cleanups.push(() => {
        listeners.forEach(([tab, onClick]) => tab.removeEventListener("click", onClick));
      });
    });

    return () => cleanups.forEach((cleanup) => cleanup());
  }, []);

  return null;
}
