import { world, system } from "@minecraft/server";
import { Config } from "../config.js";

export class PhaseManager {
    constructor(gameManager, oneBlockSystem) {
        this.gameManager = gameManager;
        this.oneBlockSystem = oneBlockSystem;
        this.currentPhase = 0; // 0:Lobby, 1:Prep, 2:War, 3:Elim, 4:SuddenDeath
        this.phaseTimer = 0;
        this.gameMode = "normal"; // "normal" or "blitz"
    }

    startGame(mode = "normal") {
        this.gameMode = mode;
        this.setPhase(1);
    }

    stopGame() {
        this.currentPhase = 0;
        this.gameMode = "normal";
        // ゲーム終了時にルールを更新 (ここでLobby用のルール、つまりPvPオフが適用される)
        this.updateGameRules();
        
        // 表示をクリア
        for (const p of world.getAllPlayers()) {
            try { p.onScreenDisplay.setActionBar(""); } catch(e){}
        }
    }

    setPhase(phase) {
        this.currentPhase = phase;
        this.phaseTimer = 0;
        
        // Blitzモードなら時間を1/5にする
        const timeDivisor = (this.gameMode === "blitz") ? 5 : 1;
        
        switch (phase) {
            case 1:
                this.phaseTimer = Math.floor(Config.PHASE_1_DURATION / timeDivisor);
                world.sendMessage("§a§l=== PHASE 1: PREPARATION ===");
                world.sendMessage("§e- PVP: Disabled");
                world.sendMessage("§e- Inventory: Kept on death");
                world.sendMessage("§e- Mid Mining: Disabled");
                break;
            case 2:
                this.phaseTimer = Math.floor(Config.PHASE_2_DURATION / timeDivisor);
                world.sendMessage("§6§l=== PHASE 2: WAR BEGINS ===");
                world.sendMessage("§c- PVP: ENABLED");
                world.sendMessage("§c- Inventory: Items LOST on death (Armor Kept)"); 
                world.sendMessage("§6- Mid Mining: ENABLED");
                this.playSound("mob.wither.spawn");
                break;
            case 3:
                this.phaseTimer = Math.floor(Config.PHASE_3_DURATION / timeDivisor);
                world.sendMessage("§c§l=== PHASE 3: ELIMINATION ===");
                world.sendMessage("§4- DEATH = ELIMINATION (No Respawn)");
                this.playSound("ambient.weather.thunder");
                break;
            case 4:
                this.phaseTimer = -1;
                world.sendMessage("§4§l=== PHASE 4: SUDDEN DEATH ===");
                world.sendMessage("§4- HOME BLOCKS DESTROYED!");
                world.sendMessage("§4- FIGHT TO THE DEATH!");
                this.playSound("mob.enderdragon.growl");
                
                if (this.oneBlockSystem) {
                    this.oneBlockSystem.destroyAllHomeBlocks();
                }
                break;
        }

        this.updateGameRules();
    }

    updateGameRules() {
        const dim = world.getDimension("overworld");
        try {
            dim.runCommand("gamerule keepinventory true");

            // 【修正】Phase 0 (Lobby) と Phase 1 (Prep) は PVP OFF
            if (this.currentPhase === 0 || this.currentPhase === 1) {
                dim.runCommand("gamerule pvp false");
            } else {
                dim.runCommand("gamerule pvp true");
            }
        } catch(e) {}
    }

    /**
     * GameManagerから毎ティック呼ばれる処理
     * @param {number} tickCount 現在のティック数
     */
    onTick(tickCount) {
        if (this.currentPhase === 0) return;

        // 1秒に1回タイマーを減らす (20ticks = 1秒)
        if (tickCount % 20 === 0 && this.phaseTimer > 0) {
            this.phaseTimer--;
            if (this.phaseTimer <= 0) {
                this.nextPhase();
            }
        }

        // アクションバー表示
        if (tickCount % 5 === 0) {
            this.updateActionBar();
        }
    }

    updateActionBar() {
        let timerText = "";
        const phaseName = ["Lobby", "§aPreparation", "§6War", "§cElimination", "§4Sudden Death"][this.currentPhase];
        
        if (this.phaseTimer >= 0) {
            const m = Math.floor(this.phaseTimer / 60);
            const s = this.phaseTimer % 60;
            timerText = ` §f- §e${m}:${s.toString().padStart(2, '0')}`;
        } else if (this.currentPhase === 4) {
            timerText = " §f- §cFINAL";
        }
        
        // モード表示追加
        const modeSuffix = (this.gameMode === "blitz") ? " §c[BLITZ]" : "";
        const baseText = `${phaseName}${timerText}${modeSuffix}`;

        for (const p of world.getAllPlayers()) {
            try {
                // キル数を取得して表示に追加
                const kills = this.gameManager.getPlayerKills(p);
                const killText = ` §7| §c⚔ ${kills}`;
                
                p.onScreenDisplay.setActionBar(baseText + killText);
            } catch(e){}
        }
    }

    nextPhase() {
        if (this.currentPhase < 4) {
            this.setPhase(this.currentPhase + 1);
        }
    }

    playSound(sound) {
        try {
            const dim = world.getDimension("overworld");
            dim.runCommand(`playsound ${sound} @a`);
        } catch(e) {}
    }
}