"use client";

import { useEffect, useRef } from "react";

const WHEEL_COOLDOWN_MS = 380;
const WHEEL_THRESHOLD = 18;

/** ارتفاع هر اسلات ریلز — یک منبع برای snap */
export function getReelsStepHeight(el: HTMLElement | null) {
  if (!el) return typeof window !== "undefined" ? window.innerHeight : 0;
  return el.clientHeight || window.innerHeight;
}

/**
 * اسکرول عمودی ریلز — snap بومی CSS + wheel یک‌پستی روی دسکتاپ
 */
export function useReelsSnapScroll(
  scrollRef: React.RefObject<HTMLDivElement | null>
) {
  const wheelLockRef = useRef(false);
  const wheelTimerRef = useRef<number | null>(null);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;

    const onWheel = (e: WheelEvent) => {
      const absY = Math.abs(e.deltaY);
      const absX = Math.abs(e.deltaX);
      if (absY < WHEEL_THRESHOLD || absY < absX) return;

      e.preventDefault();

      if (wheelLockRef.current) return;
      wheelLockRef.current = true;

      const step = getReelsStepHeight(el);
      if (!step) return;

      const maxScroll = Math.max(0, el.scrollHeight - el.clientHeight);
      const currentIndex = Math.round(el.scrollTop / step);
      const maxIndex = Math.round(maxScroll / step);
      const nextIndex = Math.min(
        maxIndex,
        Math.max(0, currentIndex + (e.deltaY > 0 ? 1 : -1))
      );

      el.scrollTo({
        top: nextIndex * step,
        behavior: "smooth",
      });

      if (wheelTimerRef.current) window.clearTimeout(wheelTimerRef.current);
      wheelTimerRef.current = window.setTimeout(() => {
        wheelLockRef.current = false;
      }, WHEEL_COOLDOWN_MS);
    };

    el.addEventListener("wheel", onWheel, { passive: false });

    return () => {
      el.removeEventListener("wheel", onWheel);
      if (wheelTimerRef.current) window.clearTimeout(wheelTimerRef.current);
    };
  }, [scrollRef]);
}

export const REELS_SCROLL_CLASS =
  "reels-vertical-scroll h-[100dvh] overflow-y-auto overscroll-y-contain";
