/**
 * TabataFit VideoPlayer Component
 * Looping muted preview mode (detail) + full-screen background mode (player)
 * Falls back to gradient when no video URL
 */

import { useRef, useEffect, useCallback } from 'react'
import { View, StyleSheet } from 'react-native'
import { useVideoPlayer, VideoView } from 'expo-video'
import { LinearGradient } from 'expo-linear-gradient'
import { BRAND, NAVY } from '../constants/colors'

interface VideoPlayerProps {
  /** HLS or MP4 video URL */
  videoUrl?: string
  /** Fallback gradient colors when no video */
  gradientColors?: readonly [string, string, ...string[]]
  /** Looping muted preview (detail) or full-screen background (player) */
  mode?: 'preview' | 'background'
  /** Whether to play the video */
  isPlaying?: boolean
  style?: object
  /** Test identifier for QA automation */
  testID?: string
}

export function VideoPlayer({
  videoUrl,
  gradientColors = [BRAND.PRIMARY, BRAND.SECONDARY],
  mode = 'preview',
  isPlaying = true,
  style,
  testID,
}: VideoPlayerProps) {
  const player = useVideoPlayer(videoUrl ?? null, (p) => {
    p.loop = true
    p.muted = mode === 'preview'
    p.volume = mode === 'background' ? 0.3 : 0
  })

  useEffect(() => {
    if (!player || !videoUrl) return
    if (isPlaying) {
      player.play()
    } else {
      player.pause()
    }
  }, [isPlaying, player, videoUrl])

  // No video URL — show gradient fallback
  if (!videoUrl) {
    return (
      <View testID={testID} style={[styles.container, style]}>
        <LinearGradient
          colors={gradientColors}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={StyleSheet.absoluteFill}
        />
      </View>
    )
  }

  return (
    <View testID={testID} style={[styles.container, style]}>
      <VideoView
        player={player}
        style={StyleSheet.absoluteFill}
        contentFit={mode === 'background' ? 'cover' : 'cover'}
        nativeControls={false}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
    backgroundColor: NAVY[900],
  },
})
