// useAutoScroll.ts
import { ref, onMounted, onUnmounted, watch, type Ref } from 'vue';

interface AutoScrollOptions {
  speed?: number; // 滚动速度（像素/秒）
  direction?: 'up' | 'down' | 'left' | 'right'; // 滚动方向
  loop?: boolean; // 是否循环
  delay?: number; // 开始滚动前的延迟（毫秒）
  pauseOnHover?: boolean; // 鼠标悬停时是否暂停
}

export function useAutoScroll(
  containerRef: Ref<HTMLElement | null>,
  contentRef: Ref<HTMLElement | null>,
  options: AutoScrollOptions = {},
) {
  const { speed = 50, direction = 'up', loop = true, delay = 0, pauseOnHover = true } = options;

  const el = containerRef.value;
  const isPlaying = ref(false);
  const animationFrameId = ref<number | null>(null);
  const startTime = ref<number | null>(null);
  const scrollPosition = ref(0);
  const containerSize = ref(0);
  const contentSize = ref(0);

  // 初始化尺寸
  const initSizes = () => {
    if (!el || !contentRef.value) return;

    if (direction === 'up' || direction === 'down') {
      containerSize.value = el.clientHeight;
      contentSize.value = contentRef.value.scrollHeight;
    } else {
      containerSize.value = el.clientWidth;
      contentSize.value = contentRef.value.scrollWidth;
    }
  };

  // 设置滚动位置
  const setScrollPosition = (position: number) => {
    if (!el) return;

    if (direction === 'up' || direction === 'down') {
      el.scrollTop = position;
    } else {
      el.scrollLeft = position;
    }
  };

  // 动画循环
  const animate = (timestamp: number) => {
    if (!startTime.value) startTime.value = timestamp;
    const elapsed = timestamp - startTime.value;

    // 计算滚动位置
    const newPosition = (elapsed / 1000) * speed;

    if (loop) {
      // 循环模式
      const loopSize = contentSize.value - containerSize.value + 500;
      scrollPosition.value = newPosition % loopSize;

      // 反向滚动时调整位置
      if (direction === 'up' || direction === 'left') {
        setScrollPosition(contentSize.value - (scrollPosition.value % contentSize.value));
      } else {
        setScrollPosition(scrollPosition.value % contentSize.value);
      }
    } else {
      // 非循环模式
      scrollPosition.value = newPosition;

      // 检查是否滚动到底部
      if (scrollPosition.value >= contentSize.value - containerSize.value) {
        scrollPosition.value = contentSize.value - containerSize.value;
        setScrollPosition(scrollPosition.value);
        stop();
        return;
      }

      setScrollPosition(scrollPosition.value);
    }

    if (isPlaying.value) {
      animationFrameId.value = requestAnimationFrame(animate);
    }
  };

  // 开始滚动
  const play = () => {
    if (!isPlaying.value) {
      isPlaying.value = true;
      animationFrameId.value = requestAnimationFrame(animate);
    }
  };

  // 暂停滚动
  const pause = () => {
    isPlaying.value = false;
    if (animationFrameId.value) {
      cancelAnimationFrame(animationFrameId.value);
      animationFrameId.value = null;
    }
  };

  // 停止滚动并重置位置
  const stop = () => {
    pause();
    startTime.value = null;
    scrollPosition.value = 0;
    setScrollPosition(0);
  };

  // 重置并重新开始
  const restart = () => {
    stop();
    setTimeout(play, delay);
  };

  // 监听尺寸变化
  const resizeObserver = new ResizeObserver(() => {
    initSizes();
  });

  // 初始化
  onMounted(() => {
    if (!el || !contentRef.value) return;

    initSizes();
    resizeObserver.observe(el);
    resizeObserver.observe(contentRef.value);

    // 设置延迟
    setTimeout(play, delay);

    // 鼠标悬停暂停
    if (pauseOnHover) {
      el.addEventListener('mouseenter', pause);
      el.addEventListener('mouseleave', play);
    }
  });

  // 清理
  onUnmounted(() => {
    if (el) {
      el.removeEventListener('mouseenter', pause);
      el.removeEventListener('mouseleave', play);
    }
    resizeObserver.disconnect();
    pause();
  });

  // 监听选项变化
  watch(
    () => [speed, direction, loop, delay],
    () => {
      restart();
    },
  );

  return {
    isPlaying,
    play,
    pause,
    stop,
    restart,
  };
}
