import { useEffect, useRef } from 'react';

const TICK_MS = 100;

interface UseFixedDwellOptions {
  /** Reset key — restarts the timer when it changes (particle id). */
  id: string;
  durationS: number;
  paused: boolean;
  onEnded: () => void;
  onProgress?: (ratio: number) => void;
}

/**
 * Drives a fixed-duration dwell timer for particles without intrinsic
 * playback (text, tasks, events): reports progress and fires onEnded once
 * the duration elapses. Pausing freezes elapsed time rather than resetting.
 */
export function useFixedDwell({
  id,
  durationS,
  paused,
  onEnded,
  onProgress,
}: UseFixedDwellOptions): void {
  const elapsedRef = useRef(0);

  useEffect(() => {
    elapsedRef.current = 0;
  }, [id]);

  useEffect(() => {
    if (paused) return;

    const interval = setInterval(() => {
      elapsedRef.current += TICK_MS / 1000;
      const ratio = Math.min(elapsedRef.current / durationS, 1);
      onProgress?.(ratio);

      if (ratio >= 1) {
        clearInterval(interval);
        onEnded();
      }
    }, TICK_MS);

    return () => clearInterval(interval);
  }, [paused, durationS, onEnded, onProgress, id]);
}
