'use client';

import { useEffect, useRef } from 'react';
import { usePlayerAudio, usePlayerDuration } from '../../context/selectors';
import { formatTime } from '../../utils/formatTime';

const READ_INTERVAL_MS = 200;

export function TimeDisplay() {
  const audio = usePlayerAudio();
  const duration = usePlayerDuration();
  const currentRef = useRef<HTMLSpanElement | null>(null);

  useEffect(() => {
    const el = currentRef.current;
    if (!el) return;
    let last = -1;
    const write = () => {
      const t = audio.currentTime;
      if (Math.abs(t - last) < 0.5) return;
      last = t;
      el.textContent = formatTime(t);
    };
    write();
    const onSeek = () => write();
    audio.addEventListener('seeked', onSeek);
    audio.addEventListener('timeupdate', onSeek);
    // Backup poll when timeupdate is throttled (e.g. background tab → visible).
    const timer = setInterval(() => {
      if (!audio.paused) write();
    }, READ_INTERVAL_MS);
    return () => {
      audio.removeEventListener('seeked', onSeek);
      audio.removeEventListener('timeupdate', onSeek);
      clearInterval(timer);
    };
  }, [audio]);

  return (
    <span className="tabular-nums text-xs text-muted-foreground">
      <span ref={currentRef}>{formatTime(audio.currentTime)}</span>
      {' / '}
      {formatTime(duration)}
    </span>
  );
}
