import { useEffect, type RefObject } from 'react'
import type { MediaPlayerInstance } from '@vidstack/react'
import { usePreferencesStore } from '../stores/preferences-store'
import { usePlayerRuntimeStore } from '../stores/player-runtime-store'
import { applyAudioGraphState } from '../lib/audio-graph'

/**
 * Drives the Web Audio graph that sits between the `<video>` element and
 * the device output. Reads the persistent prefs (audio delay default,
 * volume boost, night-mode compressor) plus per-session runtime offset,
 * and pushes the combined state into `applyAudioGraphState` whenever any
 * of them change. The hook also re-applies on streamUrl swap because the
 * `<video>` element gets a new MediaSource on each episode change.
 */
export function usePlayerAudioGraph(
  playerRef: RefObject<MediaPlayerInstance | null>,
  streamUrl: string,
) {
  const audioDelayPref = usePreferencesStore(s => s.audioDelayMs)
  const volumeBoost = usePreferencesStore(s => s.volumeBoost)
  const nightMode = usePreferencesStore(s => s.nightMode)
  const audioOffsetMs = usePlayerRuntimeStore(s => s.audioOffsetMs)

  useEffect(() => {
    const el = (playerRef.current as unknown as { el?: HTMLElement })?.el
    const video = el?.querySelector('video') as HTMLVideoElement | null
    if (!video) return
    const totalDelay = (audioDelayPref ?? 0) + (audioOffsetMs ?? 0)
    applyAudioGraphState(video, {
      delayMs: totalDelay,
      boost: volumeBoost ?? 1,
      compressor: !!nightMode,
    })
  }, [playerRef, audioDelayPref, audioOffsetMs, volumeBoost, nightMode, streamUrl])

  return { volumeBoost, nightMode }
}
