import { useState, useEffect, useCallback } from 'react';

/**
 * useCountdown Hook
 * 倒计时钩子，用于验证码发送倒计时
 * @param {number} initialSeconds - 初始秒数
 * @returns {Object} { countdown, isActive, start, reset }
 */
const useCountdown = (initialSeconds = 60) => {
  const [countdown, setCountdown] = useState(0);
  const [isActive, setIsActive] = useState(false);

  useEffect(() => {
    let timer;
    if (isActive && countdown > 0) {
      timer = setInterval(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
    } else if (countdown === 0 && isActive) {
      setIsActive(false);
    }
    return () => clearInterval(timer);
  }, [isActive, countdown]);

  /**
   * 开始倒计时
   */
  const start = useCallback(() => {
    setCountdown(initialSeconds);
    setIsActive(true);
  }, [initialSeconds]);

  /**
   * 重置倒计时
   */
  const reset = useCallback(() => {
    setCountdown(0);
    setIsActive(false);
  }, []);

  return { countdown, isActive, start, reset };
};

export default useCountdown;
