/**
 * Video utility functions
 */

/**
 * Format duration from seconds to HH:MM:SS or MM:SS
 */
export function formatDuration(seconds: number | null | undefined): string {
  if (seconds === null || seconds === undefined || isNaN(seconds)) {
    return '--:--';
  }

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }

  return `${minutes}:${secs.toString().padStart(2, '0')}`;
}

/**
 * Format file size to human-readable format
 */
export function formatFileSize(bytes: number | null | undefined): string {
  if (bytes === null || bytes === undefined || isNaN(bytes)) {
    return 'Unknown';
  }

  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let size = bytes;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(1)} ${units[unitIndex]}`;
}

/**
 * Get video orientation label
 */
export function getOrientationLabel(orientation: string | null): string {
  if (!orientation) return 'Unknown';

  switch (orientation.toUpperCase()) {
    case 'H':
      return 'Horizontal';
    case 'V':
      return 'Vertical';
    case 'S':
      return 'Square';
    default:
      return orientation;
  }
}

/**
 * Get video quality badge color
 */
export function getQualityColor(quality: string | null): string {
  if (!quality) return 'default';

  switch (quality.toLowerCase()) {
    case '4k':
    case '2160p':
      return 'gold';
    case '1080p':
    case 'hd':
      return 'green';
    case '720p':
      return 'blue';
    case '480p':
    case 'sd':
      return 'default';
    default:
      return 'default';
  }
}

/**
 * Calculate aspect ratio from width and height
 */
export function calculateAspectRatio(
  width: number | null,
  height: number | null
): string | null {
  if (!width || !height) return null;

  const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
  const divisor = gcd(width, height);

  return `${width / divisor}:${height / divisor}`;
}

/**
 * Get video dimensions string
 */
export function getVideoDimensions(
  width: number | null,
  height: number | null
): string {
  if (!width || !height) return 'Unknown';
  return `${width} × ${height}`;
}

/**
 * Check if video is high quality
 */
export function isHighQuality(width: number | null, quality: string | null): boolean {
  if (quality) {
    const highQualityKeywords = ['4k', '2160p', '1080p', 'hd'];
    return highQualityKeywords.some((kw) => quality.toLowerCase().includes(kw));
  }

  if (width && width >= 1920) {
    return true;
  }

  return false;
}

/**
 * Get media API URL from environment
 * For public gallery, returns empty string to use relative URLs
 */
export function getMediaApiUrl(): string {
  // Use relative URLs to go through nginx proxy
  // This avoids SSL issues and mixed content errors in production
  return '';
}

/**
 * Build video stream URL
 * Uses relative path for both admin and public gallery
 */
export function getVideoStreamUrl(videoId: number): string {
  return `/media/videos/${videoId}/stream`;
}

/**
 * Build video thumbnail URL
 * Uses relative path for both admin and public gallery
 */
export function getVideoThumbnailUrl(videoId: number): string {
  return `/media/videos/${videoId}/thumbnail`;
}

/**
 * Build video metadata URL
 * Uses relative path for both admin and public gallery
 */
export function getVideoMetadataUrl(videoId: number): string {
  return `/media/videos/${videoId}/metadata`;
}

/**
 * Build HLS master manifest URL for an admin context.
 * Sign this via useSignedMediaUrl before binding to a player to authorize
 * unpublished or access-gated content.
 */
export function getVideoHlsManifestUrl(videoId: number): string {
  return `/media/videos/${videoId}/hls/master.m3u8`;
}

/**
 * Build HLS master manifest URL for the public gallery.
 * No signing needed — the public endpoint gates by isPublished + access tier.
 */
export function getPublicHlsManifestUrl(videoId: number): string {
  return `/media/public/${videoId}/hls/master.m3u8`;
}
