import { browser } from '$app/environment';

class AudioStore {
    private audio: HTMLAudioElement | null = null;
    private initialized = false;

    // Current values (live preview)
    musicVolume = $state(50);
    sfxVolume = $state(100);

    // Saved values (persisted)
    private savedMusicVolume = 50;
    private savedSfxVolume = 100;

    constructor() {
        if (browser) {
            // Load saved volumes
            const savedMusic = localStorage.getItem('kv_music_volume');
            const savedSfx = localStorage.getItem('kv_sfx_volume');
            if (savedMusic) {
                this.musicVolume = parseInt(savedMusic);
                this.savedMusicVolume = this.musicVolume;
            }
            if (savedSfx) {
                this.sfxVolume = parseInt(savedSfx);
                this.savedSfxVolume = this.sfxVolume;
            }
        }
    }

    initMusic(src: string) {
        if (!browser || this.initialized) return;

        this.audio = new Audio(src);
        this.audio.loop = true;
        this.audio.volume = this.musicVolume / 100;
        this.initialized = true;

        // Try to play
        this.audio.play().catch(() => {
            const playOnInteraction = () => {
                this.audio?.play();
                document.removeEventListener('click', playOnInteraction);
            };
            document.addEventListener('click', playOnInteraction);
        });
    }

    // Preview changes (not saved yet)
    setMusicVolume(value: number) {
        this.musicVolume = value;
        if (this.audio) {
            this.audio.volume = value / 100;
        }
    }

    setSfxVolume(value: number) {
        this.sfxVolume = value;
    }

    // Save current values to localStorage
    save() {
        if (browser) {
            localStorage.setItem('kv_music_volume', String(this.musicVolume));
            localStorage.setItem('kv_sfx_volume', String(this.sfxVolume));
        }
        this.savedMusicVolume = this.musicVolume;
        this.savedSfxVolume = this.sfxVolume;
    }

    // Revert to last saved values
    revert() {
        this.musicVolume = this.savedMusicVolume;
        this.sfxVolume = this.savedSfxVolume;
        if (this.audio) {
            this.audio.volume = this.musicVolume / 100;
        }
    }

    stopMusic() {
        if (this.audio) {
            this.audio.pause();
            this.audio.currentTime = 0;
        }
    }

    destroy() {
        if (this.audio) {
            this.audio.pause();
            this.audio.src = '';
            this.audio = null;
            this.initialized = false;
        }
    }
}

export const audioStore = new AudioStore();
