/**
 * Video Utility Functions
 *
 * Hilfsfunktionen für Video-URL-Parsing, Embed-Generierung und Formatierung.
 */

export type VideoPlatform = 'youtube' | 'vimeo' | 'external' | 'unknown'

export interface VideoInfo {
  platform: VideoPlatform
  videoId: string | null
  originalUrl: string
  embedUrl: string | null
  thumbnailUrl: string | null
}

export interface EmbedOptions {
  autoplay?: boolean
  muted?: boolean
  loop?: boolean
  controls?: boolean
  startTime?: number
  privacyMode?: boolean
  showRelated?: boolean
}

/**
 * Parst eine Video-URL und extrahiert Plattform, Video-ID und Embed-URL
 */
export function parseVideoUrl(url: string): VideoInfo | null {
  if (!url || typeof url !== 'string') {
    return null
  }

  const trimmedUrl = url.trim()

  // YouTube URL patterns
  const youtubePatterns = [
    // Standard watch URL: youtube.com/watch?v=VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})(?:&.*)?/,
    // Short URL: youtu.be/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?youtu\.be\/([a-zA-Z0-9_-]{11})(?:\?.*)?/,
    // Embed URL: youtube.com/embed/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?youtube\.com\/embed\/([a-zA-Z0-9_-]{11})(?:\?.*)?/,
    // YouTube-nocookie (privacy mode)
    /(?:https?:\/\/)?(?:www\.)?youtube-nocookie\.com\/embed\/([a-zA-Z0-9_-]{11})(?:\?.*)?/,
    // Shorts URL: youtube.com/shorts/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})(?:\?.*)?/,
  ]

  for (const pattern of youtubePatterns) {
    const match = trimmedUrl.match(pattern)
    if (match && match[1]) {
      const videoId = match[1]
      return {
        platform: 'youtube',
        videoId,
        originalUrl: trimmedUrl,
        embedUrl: `https://www.youtube.com/embed/${videoId}`,
        thumbnailUrl: `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,
      }
    }
  }

  // Vimeo URL patterns
  const vimeoPatterns = [
    // Standard URL: vimeo.com/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?vimeo\.com\/(\d+)(?:\?.*)?/,
    // Player URL: player.vimeo.com/video/VIDEO_ID
    /(?:https?:\/\/)?player\.vimeo\.com\/video\/(\d+)(?:\?.*)?/,
    // Channel URL: vimeo.com/channels/CHANNEL/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?vimeo\.com\/channels\/[^/]+\/(\d+)(?:\?.*)?/,
    // Groups URL: vimeo.com/groups/GROUP/videos/VIDEO_ID
    /(?:https?:\/\/)?(?:www\.)?vimeo\.com\/groups\/[^/]+\/videos\/(\d+)(?:\?.*)?/,
  ]

  for (const pattern of vimeoPatterns) {
    const match = trimmedUrl.match(pattern)
    if (match && match[1]) {
      const videoId = match[1]
      return {
        platform: 'vimeo',
        videoId,
        originalUrl: trimmedUrl,
        embedUrl: `https://player.vimeo.com/video/${videoId}`,
        thumbnailUrl: null, // Vimeo requires API call for thumbnail
      }
    }
  }

  // Check if it's a direct video file URL
  const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.avi', '.mkv']
  const isVideoFile = videoExtensions.some((ext) =>
    trimmedUrl.toLowerCase().includes(ext)
  )

  if (isVideoFile) {
    return {
      platform: 'external',
      videoId: null,
      originalUrl: trimmedUrl,
      embedUrl: trimmedUrl,
      thumbnailUrl: null,
    }
  }

  // Unknown URL format
  return {
    platform: 'unknown',
    videoId: null,
    originalUrl: trimmedUrl,
    embedUrl: null,
    thumbnailUrl: null,
  }
}

/**
 * Generiert eine Embed-URL mit den angegebenen Optionen
 */
export function generateEmbedUrl(
  videoInfo: VideoInfo,
  options: EmbedOptions = {}
): string | null {
  if (!videoInfo || !videoInfo.embedUrl) {
    return null
  }

  const {
    autoplay = false,
    muted = false,
    loop = false,
    controls = true,
    startTime = 0,
    privacyMode = false,
    showRelated = false,
  } = options

  const params = new URLSearchParams()

  if (videoInfo.platform === 'youtube') {
    // YouTube-spezifische Parameter
    let baseUrl = videoInfo.embedUrl

    // Privacy Mode: youtube-nocookie.com verwenden
    if (privacyMode) {
      baseUrl = baseUrl.replace('youtube.com', 'youtube-nocookie.com')
    }

    if (autoplay) params.set('autoplay', '1')
    if (muted) params.set('mute', '1')
    if (loop && videoInfo.videoId) {
      params.set('loop', '1')
      params.set('playlist', videoInfo.videoId) // Loop benötigt playlist Parameter
    }
    if (!controls) params.set('controls', '0')
    if (startTime > 0) params.set('start', String(Math.floor(startTime)))
    if (!showRelated) params.set('rel', '0')

    // Modestbranding und iv_load_policy für cleanes Embedding
    params.set('modestbranding', '1')
    params.set('iv_load_policy', '3') // Annotationen ausblenden

    const paramString = params.toString()
    return paramString ? `${baseUrl}?${paramString}` : baseUrl
  }

  if (videoInfo.platform === 'vimeo') {
    // Vimeo-spezifische Parameter
    if (autoplay) params.set('autoplay', '1')
    if (muted) params.set('muted', '1')
    if (loop) params.set('loop', '1')
    if (!controls) params.set('controls', '0')

    // Vimeo unterstützt startTime als #t=XXs
    let url = videoInfo.embedUrl
    const paramString = params.toString()
    if (paramString) {
      url = `${url}?${paramString}`
    }
    if (startTime > 0) {
      url = `${url}#t=${Math.floor(startTime)}s`
    }

    return url
  }

  // Für externe URLs keine Parameter hinzufügen
  return videoInfo.embedUrl
}

/**
 * Formatiert Sekunden als Dauer-String (z.B. "2:30" oder "1:02:30")
 */
export function formatDuration(seconds: number): string {
  if (typeof seconds !== 'number' || isNaN(seconds) || seconds < 0) {
    return '0: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}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
  }

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

/**
 * Parst einen Dauer-String zu Sekunden
 * Unterstützt: "2:30", "1:02:30", "90", "1h 30m", "90s"
 */
export function parseDuration(duration: string): number {
  if (!duration || typeof duration !== 'string') {
    return 0
  }

  const trimmed = duration.trim()

  // Format: "HH:MM:SS" oder "MM:SS"
  if (trimmed.includes(':')) {
    const parts = trimmed.split(':').map((p) => parseInt(p, 10))

    if (parts.length === 3) {
      // HH:MM:SS
      const [hours, minutes, seconds] = parts
      return (hours || 0) * 3600 + (minutes || 0) * 60 + (seconds || 0)
    }

    if (parts.length === 2) {
      // MM:SS
      const [minutes, seconds] = parts
      return (minutes || 0) * 60 + (seconds || 0)
    }
  }

  // Format: "1h 30m 45s" oder Kombinationen
  const hourMatch = trimmed.match(/(\d+)\s*h/i)
  const minuteMatch = trimmed.match(/(\d+)\s*m/i)
  const secondMatch = trimmed.match(/(\d+)\s*s/i)

  if (hourMatch || minuteMatch || secondMatch) {
    const hours = hourMatch ? parseInt(hourMatch[1], 10) : 0
    const minutes = minuteMatch ? parseInt(minuteMatch[1], 10) : 0
    const seconds = secondMatch ? parseInt(secondMatch[1], 10) : 0
    return hours * 3600 + minutes * 60 + seconds
  }

  // Nur Sekunden als Zahl
  const numericValue = parseInt(trimmed, 10)
  return isNaN(numericValue) ? 0 : numericValue
}

/**
 * Gibt die passende Tailwind-CSS-Klasse für ein Aspect-Ratio zurück
 */
export function getAspectRatioClass(ratio: string): string {
  const ratioMap: Record<string, string> = {
    '16:9': 'aspect-video', // aspect-[16/9]
    '4:3': 'aspect-[4/3]',
    '1:1': 'aspect-square', // aspect-[1/1]
    '9:16': 'aspect-[9/16]',
    '21:9': 'aspect-[21/9]',
    '3:2': 'aspect-[3/2]',
    '2:3': 'aspect-[2/3]',
  }

  return ratioMap[ratio] || 'aspect-video'
}

/**
 * Extrahiert die Video-ID aus einer URL
 */
export function extractVideoId(url: string): string | null {
  const info = parseVideoUrl(url)
  return info?.videoId || null
}

/**
 * Prüft ob eine URL eine gültige Video-URL ist
 */
export function isValidVideoUrl(url: string): boolean {
  const info = parseVideoUrl(url)
  return info !== null && info.platform !== 'unknown'
}

/**
 * Gibt die Plattform einer Video-URL zurück
 */
export function getVideoPlatform(url: string): VideoPlatform {
  const info = parseVideoUrl(url)
  return info?.platform || 'unknown'
}

/**
 * Generiert eine Thumbnail-URL für ein Video
 * Für YouTube direkt, für Vimeo wird null zurückgegeben (API erforderlich)
 */
export function getVideoThumbnail(
  url: string,
  quality: 'default' | 'medium' | 'high' | 'max' = 'high'
): string | null {
  const info = parseVideoUrl(url)

  if (!info || !info.videoId) {
    return null
  }

  if (info.platform === 'youtube') {
    const qualityMap: Record<string, string> = {
      default: 'default.jpg',
      medium: 'mqdefault.jpg',
      high: 'hqdefault.jpg',
      max: 'maxresdefault.jpg',
    }
    return `https://img.youtube.com/vi/${info.videoId}/${qualityMap[quality]}`
  }

  // Vimeo Thumbnails benötigen API-Aufruf
  return null
}

/**
 * Validiert eine Video-URL und gibt Fehlermeldungen zurück
 */
export function validateVideoUrl(url: string): { valid: boolean; error?: string } {
  if (!url || typeof url !== 'string') {
    return { valid: false, error: 'URL ist erforderlich' }
  }

  const trimmed = url.trim()

  if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
    return { valid: false, error: 'URL muss mit http:// oder https:// beginnen' }
  }

  const info = parseVideoUrl(trimmed)

  if (!info) {
    return { valid: false, error: 'Ungültige URL' }
  }

  if (info.platform === 'unknown') {
    return {
      valid: false,
      error: 'Unbekanntes Video-Format. Unterstützt: YouTube, Vimeo, oder direkte Video-URLs',
    }
  }

  return { valid: true }
}
