"use client";

import { useRef, useState, useCallback } from "react";

export function DashboardCarousel({
  children,
  className,
  count,
}: {
  children: React.ReactNode;
  className: string;
  count: number;
}) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(0);

  const onScroll = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const total = el.scrollWidth - el.clientWidth;
    if (total <= 0) return;
    setActive(Math.round((el.scrollLeft / total) * (count - 1)));
  }, [count]);

  const scrollTo = (i: number) => {
    const el = scrollRef.current;
    if (!el) return;
    const total = el.scrollWidth - el.clientWidth;
    el.scrollTo({ left: (total / (count - 1)) * i, behavior: "smooth" });
  };

  return (
    <div>
      <div ref={scrollRef} onScroll={onScroll} className={className}>
        {children}
      </div>
      <div className="flex justify-center gap-1.5 mt-2 lg:hidden">
        {Array.from({ length: count }, (_, i) => (
          <button
            key={i}
            aria-label={`Bölüm ${i + 1}`}
            onClick={() => scrollTo(i)}
            className={`h-1.5 rounded-full transition-all duration-200 ${
              i === active
                ? "w-4 bg-primary"
                : "w-1.5 bg-muted-foreground/30 hover:bg-muted-foreground/50"
            }`}
          />
        ))}
      </div>
    </div>
  );
}
