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

const TICK_INTERVAL = 1000; // update every 1 second in live mode

export interface MonitorState {
  currentTime: number;   // always Date.now()
  historyMinutes: number; // how far back to show (default 60)
}

export function useMonitor() {
  const [state, setState] = useState<MonitorState>({
    currentTime: Date.now(),
    historyMinutes: 60,
  });

  const intervalRef = useRef<number | null>(null);

  // Start ticking immediately
  useEffect(() => {
    intervalRef.current = window.setInterval(() => {
      setState(prev => ({ ...prev, currentTime: Date.now() }));
    }, TICK_INTERVAL);
    return () => {
      if (intervalRef.current !== null) clearInterval(intervalRef.current);
    };
  }, []);

  const setHistoryMinutes = useCallback((minutes: number) => {
    setState(prev => ({ ...prev, historyMinutes: minutes }));
  }, []);

  const startTime = state.currentTime - state.historyMinutes * 60_000;
  const endTime = state.currentTime;

  return { state, startTime, endTime, setHistoryMinutes };
}
