import { useEffect, type RefObject } from 'react'
import type { MediaPlayerInstance } from '@vidstack/react'
import { usePreferencesStore } from '../stores/preferences-store'

/**
 * Apply a CSS `filter` chain (brightness/contrast/saturate) to the player's
 * underlying `<video>` element, driven by preferences. Updates whenever the
 * preference values change or a new stream loads (streamUrl serves as the
 * trigger after `<video>` is re-attached for a fresh source).
 */
export function usePlayerPictureFilter(
  playerRef: RefObject<MediaPlayerInstance | null>,
  streamUrl: string,
) {
  const videoBrightness = usePreferencesStore(s => s.videoBrightness)
  const videoContrast = usePreferencesStore(s => s.videoContrast)
  const videoSaturation = usePreferencesStore(s => s.videoSaturation)

  useEffect(() => {
    const el = (playerRef.current as unknown as { el?: HTMLElement })?.el
    const video = el?.querySelector('video') as HTMLVideoElement | null
    if (!video) return
    const b = videoBrightness ?? 1
    const c = videoContrast ?? 1
    const s = videoSaturation ?? 1
    const isDefault = b === 1 && c === 1 && s === 1
    video.style.filter = isDefault ? '' : `brightness(${b}) contrast(${c}) saturate(${s})`
  }, [playerRef, videoBrightness, videoContrast, videoSaturation, streamUrl])

  return { videoBrightness, videoContrast, videoSaturation }
}
