import { STREAMING_FALLBACK_DURATION } from './constants';
import { SongData } from './interfaces';

/**
 * Determine the current song based on the current time
 */
export const getCurrentSong = (songList: SongData[]): SongData | null => {
  if (!songList.length) return null;

  const now = new Date().getTime();

  // Sort songs by start time
  const sortedSongs = [...songList].sort(
    (a, b) =>
      new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
  );

  // Find the song that should be playing now
  for (let i = 0; i < sortedSongs.length; i++) {
    const song = sortedSongs[i];
    const startTime = new Date(song.start_time).getTime();
    const duration = song.duration || STREAMING_FALLBACK_DURATION;
    const endTime = startTime + duration * 1000;

    if (now >= startTime && now < endTime) {
      return song;
    }
  }

  // If no song is currently playing, return null
  return null;
};

/**
 * Calculate how far into the current song we should be
 */
export const getCurrentSongPosition = (song: SongData): number => {
  if (!song) return 0;
  let duration = song.duration;
  if (duration === 0) duration = STREAMING_FALLBACK_DURATION;

  const now = new Date().getTime();
  const startTime = new Date(song.start_time).getTime();
  const elapsed = (now - startTime) / 1000;

  const result = Math.max(0, Math.min(elapsed, duration));

  return result;
};

/**
 * Get time until the playlist ends (in seconds)
 */
export const getTimeUntilPlaylistEnd = (songs: SongData[]): number => {
  if (!songs || songs.length === 0) return 0;

  // Sort songs by start time to find the last one
  const sortedSongs = [...songs].sort(
    (a, b) =>
      new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
  );

  const lastSong = sortedSongs[sortedSongs.length - 1];
  if (!lastSong) return 0;

  // Calculate when the last song ends
  const lastSongEndTime =
    new Date(lastSong.start_time).getTime() + lastSong.duration * 1000;
  const now = new Date().getTime();
  const timeUntilEnd = (lastSongEndTime - now) / 1000; // in seconds

  return timeUntilEnd;
};

/**
 * Check if the current pathname is a live radio page
 */
export function isLiveRadioPath(pathname: string): boolean {
  return pathname.startsWith('/live-radio');
}
