// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class SoundManager extends cc.Component {
    private static _instance: SoundManager = null;

    private sounds: { [key: string]: cc.AudioClip } = {};
    private musicId: number = -1;

    public static get instance(): SoundManager {
        if (!this._instance) {
            const node = new cc.Node("SoundManager");
            cc.game.addPersistRootNode(node); // stays across scenes
            this._instance = node.addComponent(SoundManager);
        }
        return this._instance;
    }

    // ✅ Preload all your sounds at startup
    preloadSounds() {
        cc.loader.loadResDir("sounds", cc.AudioClip, (err, clips, urls) => {
            if (err) {
                cc.error("Error loading sounds:", err);
                return;
            }

            for (let i = 0; i < clips.length; i++) {
                const key = urls[i].split("/").pop(); // file name without path
                this.sounds[key] = clips[i];
            }

            cc.audioEngine.setMusicVolume(0.1);
        });
    }

    // ✅ Play short effects (clicks, shots, explosions)
    playEffect(name: string, loop: boolean = false) {
        const clip = this.sounds[name];
        if (clip) {
            cc.audioEngine.setEffectsVolume(name === 'explosion' ? 0.1 : 0.2);
            cc.audioEngine.playEffect(clip, loop);
        } else {
            cc.warn(`Sound '${name}' not found. Make sure it's preloaded.`);
        }
    }

    // ✅ Play/Stop background music
    playMusic(name: string, loop: boolean = true) {
        const clip = this.sounds[name];
        if (clip) {
            if (this.musicId !== -1) {
                cc.audioEngine.stop(this.musicId);
            }
            this.musicId = cc.audioEngine.playMusic(clip, loop);
        } else {
            cc.warn(`Music '${name}' not found. Make sure it's preloaded.`);
        }
    }

    stopMusic() {
        cc.audioEngine.stopMusic();
        this.musicId = -1;
    }

}
