export function formatRuntime(runtime?: string): string {
  if (!runtime) return '';
  // Already formatted like "2h 3min"
  if (runtime.includes('h') || runtime.includes('min')) return runtime;
  // Numeric minutes
  const mins = parseInt(runtime, 10);
  if (isNaN(mins)) return runtime;
  const h = Math.floor(mins / 60);
  const m = mins % 60;
  if (h === 0) return `${m}min`;
  if (m === 0) return `${h}h`;
  return `${h}h ${m}min`;
}

export function formatBytes(bytes?: number): string {
  if (!bytes) return '';
  const gb = bytes / (1024 * 1024 * 1024);
  if (gb >= 1) return `${gb.toFixed(1)} GB`;
  const mb = bytes / (1024 * 1024);
  return `${mb.toFixed(0)} MB`;
}

export function formatDate(dateStr?: string): string {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  } catch {
    return dateStr;
  }
}

export function formatYear(releaseInfo?: string): string {
  if (!releaseInfo) return '';
  return releaseInfo.split('-')[0];
}

export function formatRating(rating?: string): string {
  if (!rating) return '';
  const num = parseFloat(rating);
  if (isNaN(num)) return rating;
  return num.toFixed(1);
}

export function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength - 3) + '...';
}

export function formatEpisodeLabel(season?: number, episode?: number): string {
  if (season !== undefined && episode !== undefined) {
    return `S${String(season).padStart(2, '0')}E${String(episode).padStart(2, '0')}`;
  }
  return '';
}

export function formatStreamTitle(stream: {
  name?: string;
  title?: string;
  url?: string;
  infoHash?: string;
  ytId?: string;
}): string {
  if (stream.title) return stream.title;
  if (stream.name) return stream.name;
  if (stream.url) return 'Direct Stream';
  if (stream.infoHash) return 'Torrent';
  if (stream.ytId) return 'YouTube';
  return 'Stream';
}
