import { useEffect, useState } from "react";

/**
 * 检测用户是否处于空闲状态
 */
function useIdle(options = {}) {
  const {
    timeout = 10000,
    events = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"],
  } = options;

  const [isIdle, setIsIdle] = useState(false);

  useEffect(() => {
    let idleTimer;

    // 设置空闲状态
    const setIdle = () => {
      setIsIdle(true);
    };

    // 重置为空闲前的状态
    const setActive = () => {
      setIsIdle(false);
    };

    // 重置计时器
    const resetTimer = () => {
      clearTimeout(idleTimer);
      idleTimer = setTimeout(setIdle, timeout);
    };

    // 初始化计时器（仅在非空闲状态下）
    if (!isIdle) {
      resetTimer();
    }

    // 事件处理函数
    const handleUserActivity = () => {
      // 如果当前是空闲状态，用户操作后重置为活跃状态
      if (isIdle) {
        setActive();
      }
      else {
        // 如果当前是活跃状态，重置计时器
        resetTimer();
      }
    };

    // 添加事件监听器
    events.forEach((event) => {
      window.addEventListener(event, handleUserActivity, { passive: true });
    });

    // 清理函数
    return () => {
      clearTimeout(idleTimer);
      events.forEach((event) => {
        window.removeEventListener(event, handleUserActivity);
      });
    };
  }, [timeout, events, isIdle]);

  return isIdle;
}

export default useIdle;
