import { world, system, DisplaySlotId, ScoreboardIdentityType } from "@minecraft/server";

export class Economy {
    constructor() {
        this.objectiveId = "obw_gold";
    }

    init() {
        this.initScoreboard();
        
        system.runInterval(() => {
            this.cleanupOfflinePlayers();
        }, 200);
    }

    initScoreboard() {
        try {
            let objective = world.scoreboard.getObjective(this.objectiveId);
            if (!objective) {
                objective = world.scoreboard.addObjective(this.objectiveId, "§e§lGold");
            }
            
            world.scoreboard.setObjectiveAtDisplaySlot(DisplaySlotId.Sidebar, {
                objective: objective
            });
        } catch (e) {
            console.error("Economy Init Error: " + e);
        }
    }

    cleanupOfflinePlayers() {
        try {
            const objective = world.scoreboard.getObjective(this.objectiveId);
            if (!objective) return;

            const onlinePlayerNames = new Set(world.getAllPlayers().map(p => p.name));
            
            for (const participant of objective.getParticipants()) {
                if (participant.type === ScoreboardIdentityType.Player) {
                     if (!onlinePlayerNames.has(participant.displayName)) {
                         objective.removeParticipant(participant);
                     }
                }
            }
        } catch (e) {}
    }

    getMoney(player) {
        try {
            const saved = player.getDynamicProperty("obw_gold");
            return saved !== undefined ? saved : 0;
        } catch (e) {
            return 0;
        }
    }

    setMoney(player, amount) {
        try {
            if (amount < 0) amount = 0;
            player.setDynamicProperty("obw_gold", amount);
            const objective = world.scoreboard.getObjective(this.objectiveId);
            if (objective) {
                objective.setScore(player, Math.floor(amount));
            }
        } catch (e) {}
    }

    /**
     * ダミープレイヤー（統計情報など）のスコアを設定する
     * @param {string} fakeName 表示名 (例: "§bSurvivors")
     * @param {number} score スコア
     */
    setFakeScore(fakeName, score) {
        try {
            const objective = world.scoreboard.getObjective(this.objectiveId);
            if (objective) {
                objective.setScore(fakeName, score);
            }
        } catch(e) {}
    }

    /**
     * ダミープレイヤーのスコアを削除する
     */
    resetFakeScore(fakeName) {
         try {
            const objective = world.scoreboard.getObjective(this.objectiveId);
            if (objective) {
                objective.removeParticipant(fakeName);
            }
        } catch(e) {}
    }

    addMoney(player, amount) {
        const current = this.getMoney(player);
        this.setMoney(player, current + amount);
        this.playSound(player, "random.orb");
    }

    subtractMoney(player, amount) {
        const current = this.getMoney(player);
        if (current >= amount) {
            this.setMoney(player, current - amount);
            return true;
        }
        return false;
    }

    playSound(player, soundName) {
        try {
            if (typeof player.playSound === 'function') {
                player.playSound(soundName);
            } else {
                player.runCommand(`playsound ${soundName} @s`);
            }
        } catch (e) {}
    }
}