const SOURCE_TYPE_MAP = {
  mp4: "video/mp4",
  webm: "video/webm",
  ogv: "video/ogg",
  // Audio types
  mp3: "audio/mpeg",
  m4a: "audio/mp4",
  aac: "audio/aac",
  wav: "audio/wav",
  oga: "audio/ogg",
  ogg: "audio/ogg",
  // Encrypted Media Extensions
  m3u8: "application/x-mpegURL",
  mpd: "application/dash+xml",
};

/**
 * Strip query string / fragment before extracting the file extension.
 * "video.m3u8?token=abc" and "video.m3u8#t=10" must resolve the same as
 * "video.m3u8" — a raw `.split(".").pop()` would otherwise pick up the
 * query/fragment tail (e.g. "m3u8?token=abc") and silently fall back to
 * "video/mp4", which in turn causes Shaka's canPlaySource() to reject the
 * source and Video.js to select the wrong tech.
 */
export function detectSourceType(source) {
  if (typeof source !== "string" || !source) {
    return "video/mp4";
  }

  const pathOnly = source.split(/[?#]/)[0];
  const lastDotIndex = pathOnly.lastIndexOf(".");
  if (lastDotIndex === -1) {
    return "video/mp4";
  }

  const extension = pathOnly.slice(lastDotIndex + 1).toLowerCase();
  return SOURCE_TYPE_MAP[extension] || "video/mp4";
}

export function isAudioMime(type) {
  return typeof type === "string" && type.startsWith("audio/");
}

// Helper function to format time
export function formatTime(seconds) {
  if (isNaN(seconds) || seconds < 0) {
    seconds = 0;
  }
  const date = new Date(null);
  date.setSeconds(seconds);
  const result = date.toISOString().substr(11, 8);
  return result.startsWith("00:") ? result.substr(3) : result;
}

export function formatTimeDisplay(seconds) {
  if (isNaN(seconds) || !isFinite(seconds)) {
    return '00:00';
  }
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  } else {
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
}