import { useEffect, useRef } from 'react';

interface InterstellarTickerProps {
  isPlaying: boolean;
}

export function InterstellarTicker({ isPlaying }: InterstellarTickerProps) {
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useEffect(() => {
    if (!audioRef.current) {
      // Initialize audio element
      const protocol = window.location.protocol;
      const hostname = window.location.hostname;
      const port = import.meta.env.VITE_API_BASE_URL ? '' : ':8000'; 
      const audioUrl = `${protocol}//${hostname}${port}/upload/assets/tick_sample.m4a`;
      
      const audio = new Audio(audioUrl);
      audio.loop = true; // Enable looping
      audio.volume = 0.5; // Set default volume
      audioRef.current = audio;
    }

    if (isPlaying) {
      audioRef.current.play().catch(e => console.error("Audio play failed:", e));
    } else {
      audioRef.current.pause();
      // Optional: reset time to 0 if you want it to start from beginning each time
      // audioRef.current.currentTime = 0; 
    }

    return () => {
      // Cleanup not strictly necessary for singleton audio, but good practice if component unmounts
      if (audioRef.current) {
        audioRef.current.pause();
      }
    };
  }, [isPlaying]);

  return null;
}