import { useEffect, useState } from 'react';

const IDLE_AFTER_MS = 30_000;
const TICK_MS = 2_000;

export type Mood = 'awake' | 'idle';

const ACTIVITY_EVENTS: Array<keyof WindowEventMap> = [
  'pointerdown',
  'touchstart',
  'keydown',
  'scroll',
  'wheel',
];

export function useIdleMood(idleAfterMs: number = IDLE_AFTER_MS): Mood {
  const [mood, setMood] = useState<Mood>('awake');

  useEffect(() => {
    let lastActivity = Date.now();
    const onActivity = () => {
      lastActivity = Date.now();
      setMood((prev) => (prev === 'awake' ? prev : 'awake'));
    };
    ACTIVITY_EVENTS.forEach((evt) =>
      window.addEventListener(evt, onActivity, { passive: true })
    );
    const tick = window.setInterval(() => {
      if (Date.now() - lastActivity >= idleAfterMs) {
        setMood((prev) => (prev === 'idle' ? prev : 'idle'));
      }
    }, TICK_MS);
    return () => {
      ACTIVITY_EVENTS.forEach((evt) => window.removeEventListener(evt, onActivity));
      window.clearInterval(tick);
    };
  }, [idleAfterMs]);

  return mood;
}
