import { Howler } from 'howler'
import { ExtendedHowl, createSound, stopAllSounds } from './ExtendedHowl'
import { AUDIOS } from './audios'

export class AudioController {
  private audioElement: ExtendedHowl | null = null
  private isMuted = false

  load(url: string): void {
    this.audioElement?.stop()
    this.audioElement = createSound(url)
  }

  setHowl(howl: ExtendedHowl): void {
    this.audioElement?.stop()
    this.audioElement = howl
  }

  stopAllAndPlay(howl: ExtendedHowl): void {
    stopAllSounds()
    this.setHowl(howl)
    this.play()
  }

  play(): void {
    this.audioElement?.play()
  }

  pause(): void {
    this.audioElement?.pause()
  }

  stop(): void {
    this.audioElement?.stop()
  }

  toggle(): void {
    if (!this.audioElement) return
    this.audioElement.playing() ? this.pause() : this.play()
  }

  toggleMute(): void {
    this.isMuted = !this.isMuted
    Howler.mute(this.isMuted)
  }

  isPlaying(): boolean {
    return this.audioElement?.playing() ?? false
  }

  getMuted(): boolean {
    return this.isMuted
  }

  getDuration(): number {
    return (this.audioElement?.duration() as number) ?? 0
  }

  onTimeUpdate(cb: (currentTime: number) => void): void {
    this.audioElement?.onTimeUpdate(cb)
  }

  offTimeUpdate(cb: (currentTime: number) => void): void {
    this.audioElement?.offTimeUpdate(cb)
  }

  on(event: string, cb: () => void): void {
    this.audioElement?.on(event, cb)
  }
}

export const audioController = new AudioController()

// Sonidos precargados listos para usar
export const sounds = {
  click: createSound(AUDIOS.click),
  wheelSpin: createSound(AUDIOS.wheelSpin),
  correct: createSound(AUDIOS.correct),
  incorrect: createSound(AUDIOS.incorrect),
}
