/**
 * TabataFit Audio Hook
 * Sound effects for timer events using expo-av
 * Respects userStore soundEffects setting
 */

import { useRef, useEffect, useCallback } from 'react'
import { Audio } from 'expo-av'
import { useUserStore } from '../stores'

// Audio assets
const SOUNDS = {
  countdown: require('../../../assets/audio/countdown.wav'),
  phaseStart: require('../../../assets/audio/phase-start.wav'),
  complete: require('../../../assets/audio/complete.wav'),
}

type SoundKey = keyof typeof SOUNDS

export function useAudio() {
  const soundEnabled = useUserStore((s) => s.settings.soundEffects)
  const loadedSounds = useRef<Record<string, Audio.Sound>>({})

  // Configure audio session
  useEffect(() => {
    Audio.setAudioModeAsync({
      playsInSilentModeIOS: true,
      staysActiveInBackground: false,
      shouldDuckAndroid: true,
    })

    return () => {
      // Unload all sounds on cleanup
      Object.values(loadedSounds.current).forEach(sound => {
        sound.unloadAsync().catch(() => {})
      })
      loadedSounds.current = {}
    }
  }, [])

  const getSound = useCallback(async (key: SoundKey): Promise<Audio.Sound | null> => {
    if (loadedSounds.current[key]) {
      return loadedSounds.current[key]
    }
    try {
      const { sound } = await Audio.Sound.createAsync(SOUNDS[key])
      loadedSounds.current[key] = sound
      return sound
    } catch {
      return null
    }
  }, [])

  const play = useCallback(async (key: SoundKey) => {
    if (!soundEnabled) return
    const sound = await getSound(key)
    if (!sound) return
    try {
      await sound.setPositionAsync(0)
      await sound.playAsync()
    } catch {
      // Sound may have been unloaded
    }
  }, [soundEnabled, getSound])

  return {
    /** Short beep for countdown ticks (3, 2, 1) */
    countdownBeep: useCallback(() => play('countdown'), [play]),
    /** Ding for phase transitions (work → rest, rest → work) */
    phaseStart: useCallback(() => play('phaseStart'), [play]),
    /** Celebration chime on workout completion */
    workoutComplete: useCallback(() => play('complete'), [play]),
  }
}
