"use client";
import { useRef, useState, useEffect } from "react";

interface HorizontalScrollProps {
  items: string[]; // or any data type, for simplicity string here
}

export default function HorizontalScroll({ items }: HorizontalScrollProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [canScrollPrev, setCanScrollPrev] = useState(false);
  const [canScrollNext, setCanScrollNext] = useState(false);

  // Check scroll position to enable/disable buttons
  function updateScrollButtons() {
    const container = containerRef.current;
    if (!container) return;
    setCanScrollPrev(container.scrollLeft > 0);
    setCanScrollNext(container.scrollLeft + container.clientWidth < container.scrollWidth);
  }

  // Scroll container by fixed amount (e.g. 200px)
  function scrollBy(offset: number) {
    const container = containerRef.current;
    if (!container) return;
    container.scrollBy({ left: offset, behavior: "smooth" });
  }

  useEffect(() => {
    updateScrollButtons();
    const container = containerRef.current;
    if (!container) return;

    // Update buttons on scroll
    container.addEventListener("scroll", updateScrollButtons);
    // Update buttons on resize (optional)
    window.addEventListener("resize", updateScrollButtons);

    return () => {
      container.removeEventListener("scroll", updateScrollButtons);
      window.removeEventListener("resize", updateScrollButtons);
    };
  }, []);

  return (
    <div className="relative flex items-center w-full">
      {/* Prev button */}
      <button
        onClick={() => scrollBy(-200)}
        disabled={!canScrollPrev}
        aria-label="Scroll left"
        className={`absolute left-0 z-10 h-10 w-10 rounded-full bg-gray-300 text-gray-700 disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center`}
        style={{ top: "50%", transform: "translateY(-50%)" }}
      >
        ◀
      </button>

      {/* Scroll container */}
      <div
        ref={containerRef}
        className="flex overflow-x-auto scrollbar-hide space-x-4 px-12"
        style={{ scrollBehavior: "smooth" }}
      >
        {items.map((item, idx) => (
          <div
            key={idx}
            className="flex-shrink-0 w-40 h-24 bg-blue-400 text-white flex items-center justify-center rounded-md"
          >
            {item}
          </div>
        ))}
      </div>

      {/* Next button */}
      <button
        onClick={() => scrollBy(200)}
        disabled={!canScrollNext}
        aria-label="Scroll right"
        className={`absolute right-0 z-10 h-10 w-10 rounded-full bg-gray-300 text-gray-700 disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center`}
        style={{ top: "50%", transform: "translateY(-50%)" }}
      >
        ▶
      </button>
    </div>
  );
}
