import { world, system, ItemStack, ItemLockMode } from "@minecraft/server";

export class InventoryMgr {
    constructor(oneBlockSystem, economy) {
        this.oneBlockSystem = oneBlockSystem;
        this.economy = economy;
        this.shopUI = null;
        this.gameManager = null; // Mainでセットされる
    }

    init() {
        // 【V2.4 修正】負荷対策: チェック頻度を20ticks(1秒)から40ticks(2秒)に変更
        system.runInterval(() => {
            this.checkInventories();
        }, 40);
    }

    giveShopItem(player) {
        const inv = player.getComponent("inventory");
        if (!inv || !inv.container) return;
        
        const container = inv.container;
        
        // 【V2.4 追加】既に持っている場合は付与しない (増殖防止の簡易チェック)
        // スロット8以外にある場合も考慮
        let alreadyHas = false;
        for (let i = 0; i < container.size; i++) {
            const item = container.getItem(i);
            if (item && item.typeId === "minecraft:emerald" && item.nameTag === "§aShop Menu") {
                alreadyHas = true;
                break;
            }
        }
        if (alreadyHas) return;

        const shopItem = new ItemStack("minecraft:emerald", 1);
        shopItem.nameTag = "§aShop Menu";
        shopItem.setLore(["§7Right-click to open shop", "§7(Everywhere)"]);
        
        try {
            shopItem.lockMode = ItemLockMode.slot;
        } catch(e) {} 

        // 強制的にスロット8へセット (空きがない場合の考慮はバニラの挙動に任せるか、上書きする)
        container.setItem(8, shopItem);
        this.giveLevelTools(player);
    }

    giveRuleBook(player) {
        const inv = player.getComponent("inventory");
        if (!inv || !inv.container) return;
        
        const container = inv.container;
        
        const slot7 = container.getItem(7);
        if (slot7 && slot7.typeId === "minecraft:book" && slot7.nameTag === "§eRule Book") return;

        // 既に他の場所に持っているかチェック
        for (let i = 0; i < container.size; i++) {
            const item = container.getItem(i);
            if (item && item.typeId === "minecraft:book" && item.nameTag === "§eRule Book") return;
        }

        const book = new ItemStack("minecraft:book", 1);
        book.nameTag = "§eRule Book";
        book.setLore(["§7Right-click to read rules", "", "§8Credit: Aperion-HQ"]);
        
        try {
            book.lockMode = ItemLockMode.slot;
        } catch(e) {} 

        container.setItem(7, book);
    }

    giveLevelTools(player) {
        try {
            const inv = player.getComponent("inventory").container;
            const blockLoc = this.oneBlockSystem.getNearestHomeBlock(player);
            let level = 1;
            if (blockLoc) {
                level = this.oneBlockSystem.getBlockLevel(blockLoc);
            }

            let tools = [];
            if (level === 1) {
                tools = ["minecraft:wooden_pickaxe"];
            } else if (level === 2) {
                tools = ["minecraft:stone_pickaxe"];
            } else {
                tools = ["minecraft:iron_pickaxe"];
            }

            for (const typeId of tools) {
                let hasItem = false;
                for (let i = 0; i < inv.size; i++) {
                    const item = inv.getItem(i);
                    if (item && item.typeId === typeId) {
                        hasItem = true;
                        break;
                    }
                }
                if (!hasItem) {
                    inv.addItem(new ItemStack(typeId, 1));
                }
            }

            if (!player.hasTag("obw_received_start_logs")) {
                const logId = "minecraft:oak_log";
                inv.addItem(new ItemStack(logId, 4));
                player.addTag("obw_received_start_logs");
            }

        } catch (e) {
            console.warn(`Tool Give Error: ${e}`);
        }
    }

    checkInventories() {
        // ゲームの状態を確認
        let isRuleBookAllowed = true;
        
        if (this.gameManager) {
            // ゲーム中(INGAME)なら、フェーズに関わらずルールブックを削除する
            if (this.gameManager.gameState === "INGAME") {
                isRuleBookAllowed = false;
            }
        }

        for (const player of world.getAllPlayers()) {
            const inv = player.getComponent("inventory");
            if (!inv || !inv.container) continue;
            
            const container = inv.container;
            
            // 1. ショップメニュー (常時)
            // スロット8をチェックし、なければgiveShopItemを呼ぶ
            // giveShopItem内で全スキャンして重複チェックを行うようになったため安全
            const slot8 = container.getItem(8);
            if (!slot8 || slot8.typeId !== "minecraft:emerald" || slot8.nameTag !== "§aShop Menu") {
                this.giveShopItem(player);
            }

            // 2. ルールブック (ゲーム中は削除)
            if (isRuleBookAllowed) {
                // スロット7になければ付与試行 (giveRuleBook内で重複チェックあり)
                const slot7 = container.getItem(7);
                if (!slot7 || slot7.typeId !== "minecraft:book" || slot7.nameTag !== "§eRule Book") {
                    this.giveRuleBook(player);
                }
            } else {
                // ゲーム中はルールブックを削除 (全スキャンして消す)
                for (let i = 0; i < container.size; i++) {
                    const item = container.getItem(i);
                    if (item && item.typeId === "minecraft:book" && item.nameTag === "§eRule Book") {
                        container.setItem(i, undefined);
                    }
                }
            }

            // 3. 禁止アイテム削除
            for (let i = 0; i < container.size; i++) {
                const item = container.getItem(i);
                if (item && item.typeId.includes("bed") && !item.typeId.includes("bedrock")) {
                    container.setItem(i, undefined);
                }
            }
        }
    }

    onItemUse(event) {
        const item = event.itemStack;
        const player = event.source;

        // ショップメニュー
        if (item.typeId === "minecraft:emerald" && item.nameTag === "§aShop Menu") {
            if (this.shopUI) {
                this.shopUI.openMainMenu(player);
            } else {
                player.sendMessage("§cShop UI system is not ready.");
            }
        }
        
        // ルールブック使用検知
        if (item.typeId === "minecraft:book" && item.nameTag === "§eRule Book") {
            if (this.shopUI) {
                this.shopUI.openRuleBook(player);
            }
        }
    }

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