"use client";

/**
 * اسلایدر افقی با scroll-snap که هر چند ثانیه خودکار به اسلاید بعد می‌رود.
 * - با لمس، نگه داشتن ماوس یا فوکوس کیبورد متوقف می‌شود
 * - فقط وقتی در صفحه دیده می‌شود و تب فعال است حرکت می‌کند
 * - برای کاربرانی که «کاهش حرکت» را فعال کرده‌اند خودکار نمی‌چرخد
 * چون از scrollBy نسبی استفاده می‌شود، در حالت راست‌به‌چپ هم درست کار می‌کند.
 */
import { Children, useCallback, useEffect, useRef, useState, type ReactNode } from "react";

interface Props {
  children: ReactNode;
  className?: string;
  interval?: number;
}

export function AutoSlider({ children, className = "", interval = 5000 }: Props) {
  const ref = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState(0);
  const paused = useRef(false);
  const visible = useRef(true);
  const count = Children.count(children);

  /** اسلایدی که مرکزش به مرکز کادر نزدیک‌تر است */
  const currentIndex = useCallback(() => {
    const el = ref.current;
    if (!el) return 0;
    const box = el.getBoundingClientRect();
    const center = box.left + box.width / 2;
    let best = 0;
    let bestDist = Infinity;
    Array.from(el.children).forEach((c, i) => {
      const r = c.getBoundingClientRect();
      const d = Math.abs(r.left + r.width / 2 - center);
      if (d < bestDist) [best, bestDist] = [i, d];
    });
    return best;
  }, []);

  const goTo = useCallback((i: number) => {
    const el = ref.current;
    const slide = el?.children[i] as HTMLElement | undefined;
    if (!el || !slide) return;
    const box = el.getBoundingClientRect();
    const r = slide.getBoundingClientRect();
    el.scrollBy({ left: r.left + r.width / 2 - (box.left + box.width / 2), behavior: "smooth" });
  }, []);

  // به‌روزرسانی نقطه فعال هنگام اسکرول (دستی یا خودکار)
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let frame = 0;
    const onScroll = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => setActive(currentIndex()));
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      el.removeEventListener("scroll", onScroll);
      cancelAnimationFrame(frame);
    };
  }, [currentIndex]);

  // فقط وقتی اسلایدر در صفحه دیده می‌شود حرکت کند
  useEffect(() => {
    const el = ref.current;
    if (!el || typeof IntersectionObserver === "undefined") return;
    const io = new IntersectionObserver(([e]) => (visible.current = e.isIntersecting), { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // حرکت خودکار
  useEffect(() => {
    if (count < 2 || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const id = window.setInterval(() => {
      if (paused.current || !visible.current || document.hidden) return;
      goTo((currentIndex() + 1) % count);
    }, interval);
    return () => window.clearInterval(id);
  }, [count, interval, goTo, currentIndex]);

  const pause = () => (paused.current = true);
  const resume = () => (paused.current = false);

  return (
    <div onPointerEnter={pause} onPointerLeave={resume} onTouchStart={pause} onTouchEnd={resume} onFocus={pause} onBlur={resume}>
      <div ref={ref} className={className}>
        {children}
      </div>
      {count > 1 && (
        <div className="mt-3 flex justify-center gap-1.5">
          {Array.from({ length: count }, (_, i) => (
            <button
              key={i}
              type="button"
              onClick={() => goTo(i)}
              aria-label={`اسلاید ${i + 1}`}
              aria-current={i === active}
              className={`h-1.5 rounded-full transition-all ${i === active ? "w-6 bg-ink" : "w-1.5 bg-line"}`}
            />
          ))}
        </div>
      )}
    </div>
  );
}
