import { useEffect } from 'react';
import { useGameStore, flushGameState } from '../store/useGameStore';

export function useIdleTick() {
  const tickIdle = useGameStore((s) => s.tickIdle);
  const initOffline = useGameStore((s) => s.initOffline);

  useEffect(() => {
    initOffline();

    const interval = setInterval(() => {
      tickIdle(1);
    }, 1000);

    // 탭 전환/앱 종료 시 즉시 저장 (스로틀 우회)
    window.addEventListener('beforeunload', flushGameState);

    return () => {
      clearInterval(interval);
      window.removeEventListener('beforeunload', flushGameState);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}
