"use client";

import { useEffect } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { createRoot } from "react-dom/client";

/**
 * Wires up the `.dissertation-regular-slider` (and similarly-classed
 * `.slider`) sample carousels CMS article bodies embed — see
 * `app/dissertation-sections.css` for `.slider-box31` styling. The live
 * site drives this with a jQuery `slick` carousel; no exact init call was
 * found for this specific class in `custom.js`; this reproduces the same
 * "browse several cards, prev/next" behavior with CSS scroll-snap + two
 * injected arrow buttons instead of porting Slick, since the markup arrives
 * via `dangerouslySetInnerHTML` (plain nested `<div>`s, not React-owned
 * slides) — scroll-snap needs no index bookkeeping against content we don't
 * control the shape of, unlike the translate-based carousels elsewhere in
 * this app (`WritersCarousel`, `HeroBannerCarousel`), which do own their
 * slide data as real props.
 */
export function SamplesCarousel() {
  useEffect(() => {
    const tracks = document.querySelectorAll<HTMLElement>(".prose .dissertation-regular-slider");
    const cleanups: Array<() => void> = [];

    tracks.forEach((track) => {
      if (track.dataset.carouselReady) return;
      track.dataset.carouselReady = "true";
      track.classList.add("samples-carousel-track");

      const wrapper = document.createElement("div");
      wrapper.className = "samples-carousel-wrapper";
      track.parentElement?.insertBefore(wrapper, track);
      wrapper.appendChild(track);

      const prevBtn = document.createElement("button");
      const nextBtn = document.createElement("button");
      prevBtn.type = "button";
      nextBtn.type = "button";
      prevBtn.className = "samples-carousel-arrow samples-carousel-arrow-prev";
      nextBtn.className = "samples-carousel-arrow samples-carousel-arrow-next";
      prevBtn.setAttribute("aria-label", "Previous sample");
      nextBtn.setAttribute("aria-label", "Next sample");
      wrapper.appendChild(prevBtn);
      wrapper.appendChild(nextBtn);

      createRoot(prevBtn).render(<ChevronLeft size={20} />);
      createRoot(nextBtn).render(<ChevronRight size={20} />);

      const scrollByCard = (dir: 1 | -1) => {
        const card = track.querySelector<HTMLElement>(":scope > div");
        const amount = (card?.offsetWidth ?? 280) + 16;
        track.scrollBy({ left: dir * amount, behavior: "smooth" });
      };
      const onPrev = () => scrollByCard(-1);
      const onNext = () => scrollByCard(1);
      prevBtn.addEventListener("click", onPrev);
      nextBtn.addEventListener("click", onNext);

      cleanups.push(() => {
        prevBtn.removeEventListener("click", onPrev);
        nextBtn.removeEventListener("click", onNext);
      });
    });

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

  return null;
}
