import { useEffect, useState } from 'react'

const COMBAT_AUDIO_STORAGE_KEY = 'actionModeSoundEnabled'
const COMBAT_AUDIO_EVENT = 'action-mode-sound-enabled-change'

let combatAudioEnabledFallback = false

export function getCombatAudioEnabled() {
  if (typeof window === 'undefined') return false
  try {
    const value = window.localStorage.getItem(COMBAT_AUDIO_STORAGE_KEY)
    if (value === null) return combatAudioEnabledFallback
    return value === 'true'
  } catch {
    return combatAudioEnabledFallback
  }
}

export function setCombatAudioEnabled(enabled: boolean) {
  combatAudioEnabledFallback = enabled
  if (typeof window === 'undefined') return
  try {
    window.localStorage.setItem(COMBAT_AUDIO_STORAGE_KEY, enabled ? 'true' : 'false')
  } catch {
    // WebViews can deny localStorage; module fallback still controls playback.
  }
  window.dispatchEvent(new CustomEvent(COMBAT_AUDIO_EVENT, { detail: enabled }))
}

export function useCombatAudioEnabled() {
  const [enabled, setEnabled] = useState(() => getCombatAudioEnabled())

  useEffect(() => {
    const sync = (event?: Event) => {
      if (event instanceof CustomEvent && typeof event.detail === 'boolean') {
        setEnabled(event.detail)
        return
      }
      setEnabled(getCombatAudioEnabled())
    }
    window.addEventListener(COMBAT_AUDIO_EVENT, sync)
    window.addEventListener('storage', sync)
    return () => {
      window.removeEventListener(COMBAT_AUDIO_EVENT, sync)
      window.removeEventListener('storage', sync)
    }
  }, [])

  return [enabled, setCombatAudioEnabled] as const
}

export function playCombatSound(src: string, options: { unlocked?: { current: boolean }, volume?: number } = {}) {
  if (typeof window === 'undefined' || !getCombatAudioEnabled()) return
  if (options.unlocked) options.unlocked.current = true
  const audio = new Audio(src)
  audio.volume = options.volume ?? 0.32
  audio.play().catch(() => {
    // Browser blocked autoplay; direct user input will retry later.
  })
}
