import { world, system, ItemStack, ItemLockMode, EnchantmentTypes, EquipmentSlot } from "@minecraft/server";
import { ActionFormData, ModalFormData, MessageFormData } from "@minecraft/server-ui";
import { Prices } from "../data/prices.js";

export class ShopUI {
    /**
     * @param {Economy} economy 
     * @param {OneBlockSystem} oneBlockSystem
     */
    constructor(economy, oneBlockSystem) {
        this.economy = economy;
        this.oneBlockSystem = oneBlockSystem;
        this.automation = null;

        if (!Prices.buy["minecraft:iron_pickaxe"]) {
            Prices.buy["minecraft:iron_pickaxe"] = 500;
        }
        if (!Prices.buy["minecraft:ender_chest"]) {
            Prices.buy["minecraft:ender_chest"] = 1000;
        }

        this.iconMap = {
            "minecraft:oak_planks": "textures/blocks/planks_oak",
            "minecraft:stone_sword": "textures/items/stone_sword",
            "minecraft:bow": "textures/items/bow_standby",
            "minecraft:arrow": "textures/items/arrow",
            "minecraft:anvil": "textures/blocks/anvil_top_damaged_0",
            "minecraft:mace": "textures/items/mace",
            "minecraft:wind_charge": "textures/items/wind_charge",
            "minecraft:experience_bottle": "textures/items/experience_bottle",
            
            "minecraft:chainmail_helmet": "textures/items/chainmail_helmet",
            "minecraft:chainmail_chestplate": "textures/items/chainmail_chestplate",
            "minecraft:chainmail_leggings": "textures/items/chainmail_leggings",
            "minecraft:chainmail_boots": "textures/items/chainmail_boots",
            
            "obw:home_scroll": "textures/items/paper",
            "minecraft:netherite_upgrade_smithing_template": "textures/items/netherite_upgrade_smithing_template",
            
            "obw:knockback_sword": "textures/items/wood_sword",
            "minecraft:silverfish_spawn_egg": "textures/items/spawn_egg",
            "minecraft:ender_chest": "textures/blocks/ender_chest_front"
        };
    }

    getAdjustedPrice(price, itemId = null) {
        if (this.oneBlockSystem && this.oneBlockSystem.phaseManager && this.oneBlockSystem.phaseManager.gameMode === "blitz") {
            if (itemId === "minecraft:ender_pearl" || itemId === "obw:bridge_egg") {
                return Math.floor(price * 0.5);
            }
            return Math.floor(price * 0.75);
        }
        return price;
    }

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

    getIconPath(id) {
        if (this.iconMap[id]) return this.iconMap[id];
        
        let pathId = id.replace("minecraft:", "").replace("obw:", "");
        pathId = pathId.replace("wooden_", "wood_");
        pathId = pathId.replace("golden_", "gold_");
        
        if (pathId.includes("book:")) return "textures/items/book_normal";
        if (pathId === "auto_miner") return "textures/items/armor_stand";
        if (pathId === "generator") return "textures/blocks/gold_block";
        if (pathId === "fireball") return "textures/items/fireball";
        if (pathId === "bridge_egg") return "textures/items/egg";
        if (pathId === "home_scroll") return "textures/items/paper";
        if (pathId.includes("copper")) return "textures/items/copper_ingot";

        const isTool = pathId.includes("sword") || pathId.includes("pickaxe") || pathId.includes("axe") || pathId.includes("shovel") || pathId.includes("hoe");

        if (!isTool && (pathId.includes("block") || pathId.includes("dirt") || pathId.includes("stone") || pathId.includes("planks") || pathId.includes("obsidian"))) {
             return "textures/blocks/" + pathId;
        }

        return "textures/items/" + pathId;
    }

    // =========================================
    //  ルールブック (多言語対応)
    // =========================================

    openRuleBook(player, lang = null) {
        // 言語設定の読み込み/保存
        if (!lang) {
            try { lang = player.getDynamicProperty("obw_rule_lang") || "en"; } 
            catch(e) { lang = "en"; }
        } else {
            try { player.setDynamicProperty("obw_rule_lang", lang); } 
            catch(e) {}
        }

        const isJa = lang === "ja";

        const title = isJa ? "§lOne Block Wars ルール" : "§lOne Block Wars Rules";
        const body = isJa ? "§eOne Block Wars へようこそ！\n§f読みたい項目を選んでください。" : "§eWelcome to One Block Wars!\n§fSelect a topic to read more.";

        const btn0 = isJa ? "§l操作とコマンド\n§7開始・終了など" : "§lGame Controls\n§7Start & Stop commands";
        const btn1 = isJa ? "§lゲーム概要\n§7目的と基本" : "§lGame Overview\n§7Objective & Basics";
        const btn2 = isJa ? "§lゲームモード\n§7通常とBlitz" : "§lGame Modes\n§7Normal vs Blitz";
        const btn3 = isJa ? "§lフェーズ進行\n§7ゲームの流れ" : "§lGame Phases\n§7Flow of the game";
        const btn4 = isJa ? "§lショップと経済\n§7強化の方法" : "§lShop & Economy\n§7How to get stronger";
        const btn5 = isJa ? "§l特殊アイテム\n§7武器とユーティリティ" : "§lSpecial Items\n§7Weapons & Utilities";
        const btnLang = isJa ? "§dSwitch to English" : "§d日本語に切り替え";
        const btnClose = isJa ? "§c閉じる" : "§cClose";

        const form = new ActionFormData()
            .title(title)
            .body(body)
            .button(btn0, "textures/blocks/command_block") 
            .button(btn1, "textures/items/book_writable")
            .button(btn2, "textures/items/magma_cream")
            .button(btn3, "textures/items/clock_item")
            .button(btn4, "textures/items/emerald")
            .button(btn5, "textures/items/nether_star")
            .button(btnLang, "textures/items/paper")
            .button(btnClose);

        form.show(player).then(res => {
            if (res.canceled) return;
            switch(res.selection) {
                case 0: this.showRuleDetail(player, isJa ? "操作とコマンド" : "Game Controls", 
                    isJa ? 
                    "§lコマンド:§r\n(チャットで入力)\n\n" +
                    "§e!start§r\n" +
                    "- 通常モードで開始します。\n\n" +
                    "§c!start_b§r\n" +
                    "- §cBlitzモード§rで開始します。\n\n" +
                    "§c!stop§r (または §c!reset§r)\n" +
                    "- ゲームを強制終了しリセットします。"
                    :
                    "§lCommands:§r\n(Type these in chat)\n\n" +
                    "§e!start§r\n" +
                    "- Starts the game in Normal Mode.\n\n" +
                    "§c!start_b§r\n" +
                    "- Starts the game in §cBlitz Mode§r.\n\n" +
                    "§c!stop§r (or §c!reset§r)\n" +
                    "- Stops the current game.\n" +
                    "- Resets the map and inventories.\n" +
                    "- Teleports everyone back to the lobby.", lang
                ); break;

                case 1: this.showRuleDetail(player, isJa ? "ゲーム概要" : "Game Overview", 
                    isJa ?
                    "§l目的:§r\n最後まで生き残ること！\n\n" +
                    "§l遊び方:§r\n" +
                    "1. 1つのブロックがある浮島から始まります。\n" +
                    "2. ブロックを壊して素材を集めます。\n" +
                    "3. 島を広げ、防壁を作りましょう。\n" +
                    "4. ショップで装備を整えましょう。\n" +
                    "5. 他プレイヤーを倒し、生き残りましょう！\n\n" +
                    "§e注意:§r 奈落に落ちるとデスになります！"
                    :
                    "§lObjective:§r\nBe the last player standing!\n\n" +
                    "§lHow to Play:§r\n" +
                    "1. You spawn on a floating island with a single block.\n" +
                    "2. Break the block repeatedly to get resources.\n" +
                    "3. Use blocks to expand your island and build defenses.\n" +
                    "4. Use resources to buy weapons and armor from the Shop.\n" +
                    "5. Defeat other players and survive!\n\n" +
                    "§eNote:§r Falling into the void means death!", lang
                ); break;
                
                case 2: this.showRuleDetail(player, isJa ? "ゲームモード" : "Game Modes", 
                    isJa ?
                    "§l通常モード:§r\n" +
                    "コマンド: §e!start§r\n" +
                    "- 標準の進行速度とバランスです。\n\n" +
                    "§c§lBlitzモード:§r\n" +
                    "コマンド: §c!start_b§r\n" +
                    "高速でカオスな試合を楽しみたい時に！\n\n" +
                    "§e1. ターボスピード:§r\n" +
                    "- 各フェーズの時間が §c1/5§r になります。\n" +
                    "  (例: 準備フェーズ 10分 -> 2分)\n\n" +
                    "§a2. 資源増加:§r\n" +
                    "- OneBlockからドロップする資源が §ax5倍§r になります。\n\n" +
                    "§b3. ショップセール:§r\n" +
                    "- 通常アイテム: §e25% OFF§r\n" +
                    "- 移動系アイテム: §e50% OFF§r"
                    :
                    "§lNormal Mode:§r\n" +
                    "Command: §e!start§r\n" +
                    "- Standard speed and balanced gameplay.\n\n" +
                    "§c§lBlitz Mode:§r\n" +
                    "Command: §c!start_b§r\n" +
                    "For quick and chaotic matches!\n\n" +
                    "§e1. Turbo Speed:§r\n" +
                    "- Phase timers are §c1/5th§r of normal.\n" +
                    "  (e.g., Prep Phase: 10m -> 2m)\n\n" +
                    "§a2. Resource Boom:§r\n" +
                    "- Get §ax5 Resources§r from mining OneBlock.\n\n" +
                    "§b3. Shop Sale:§r\n" +
                    "- Items: §e25% OFF§r\n" +
                    "- Movement: §e50% OFF§r", lang
                ); break;

                case 3: this.showRuleDetail(player, isJa ? "フェーズ進行" : "Game Phases", 
                    isJa ?
                    "§lPhase 1: 準備 (10分*)§r\n" +
                    "- PvPは §c無効§r。\n" +
                    "- デス時のアイテムロスト §a無し§r。\n" +
                    "- 中央(Mid)の採掘 §c無効§r。\n\n" +
                    "§lPhase 2: 戦争 (10分*)§r\n" +
                    "- PvPが §a解禁§r。\n" +
                    "- デス時のアイテムロスト §c有り§r。\n" +
                    "- 中央(Mid)の採掘 §a解禁§r。\n" +
                    "※ ルールブックはインベントリから消去されます。\n\n" +
                    "§lPhase 3: 排除 (5分*)§r\n" +
                    "- リスポーン不可。デス = §c敗退§r。\n\n" +
                    "§lPhase 4: サドンデス§r\n" +
                    "- すべてのOneBlockが破壊されます。\n" +
                    "- 決着がつくまで戦え！\n\n" +
                    "§7*時間はBlitzモードの場合 1/5 になります。"
                    :
                    "§lPhase 1: Preparation (10 min*)§r\n" +
                    "- PvP is §cDISABLED§r.\n" +
                    "- Keep Inventory is §aON§r.\n" +
                    "- Mid Mining is §cDISABLED§r.\n\n" +
                    "§lPhase 2: War (10 min*)§r\n" +
                    "- PvP is §aENABLED§r.\n" +
                    "- Keep Inventory is §cOFF§r.\n" +
                    "- Mid Mining is §aENABLED§r.\n" +
                    "※ Rule Book will be removed from inventory.\n\n" +
                    "§lPhase 3: Elimination (5 min*)§r\n" +
                    "- Death = §cELIMINATION§r (No respawn).\n\n" +
                    "§lPhase 4: Sudden Death§r\n" +
                    "- All home blocks are destroyed.\n" +
                    "- Fight to the death!\n\n" +
                    "§7*Times are 1/5th in Blitz Mode.", lang
                ); break;

                case 4: this.showRuleDetail(player, isJa ? "ショップと経済" : "Shop & Economy", 
                    isJa ?
                    "§lお金 (Gold):§r\n" +
                    "- 資源を売却してGoldを得ます。\n" +
                    "- §aShop Menu§r (エメラルド) からアイテムを買えます。\n" +
                    "※ Blitzモードではアイテムが割引されます。\n\n" +
                    "§lOneBlockアップグレード:§r\n" +
                    "- 自陣のOneBlockをアップグレードして、より良い資源を出せます。\n\n" +
                    "§lキルボーナス:§r\n" +
                    "- 敵を倒すと、相手の所持金の §650%§r を奪えます。"
                    :
                    "§lMoney (Gold):§r\n" +
                    "- Sell blocks/items for Gold.\n" +
                    "- Use the §aShop Menu§r (Emerald) to buy items.\n" +
                    "※ Items are discounted in Blitz Mode.\n\n" +
                    "§lOneBlock Upgrade:§r\n" +
                    "- Upgrade your Home OneBlock for better resources.\n\n" +
                    "§lKill Bonus:§r\n" +
                    "- Killing a player grants §650% of their Gold§r.", lang
                ); break;

                case 5: this.showRuleDetail(player, isJa ? "特殊アイテム" : "Special Items", 
                    isJa ?
                    "§bAuto Miner:§r\n" +
                    "- 6秒ごとに自動でOneBlockからアイテムを出します。\n\n" +
                    "§eGenerator:§r\n" +
                    "- 10秒ごとに$50のお金が入ります。\n\n" +
                    "§cFireball:§r\n" +
                    "- 投げると爆発を起こします。\n\n" +
                    "§fBridge Egg:§r\n" +
                    "- 投げた軌跡に羊毛の橋を作ります。\n\n" +
                    "§bKnockback Sword:§r\n" +
                    "- ダメージは低いですが、大きくノックバックさせます。\n\n" +
                    "§cSilverfish Egg:§r\n" +
                    "- 敵を妨害するシルバーフィッシュを召喚します。"
                    :
                    "§bAuto Miner:§r\n" +
                    "- Automatically mines your OneBlock every 6s.\n\n" +
                    "§eGenerator:§r\n" +
                    "- Passive income ($50 every 10s).\n\n" +
                    "§cFireball:§r\n" +
                    "- Throw to cause explosion.\n\n" +
                    "§fBridge Egg:§r\n" +
                    "- Creates a wool bridge path.\n\n" +
                    "§bKnockback Sword:§r\n" +
                    "- Low damage, High knockback.\n\n" +
                    "§cSilverfish Egg:§r\n" +
                    "- Spawns a Silverfish to distract enemies.", lang
                ); break;

                case 6:
                    // 言語切り替え処理
                    this.openRuleBook(player, isJa ? "en" : "ja");
                    break;
                case 7:
                    // 閉じる
                    break;
            }
        });
    }

    showRuleDetail(player, title, content, lang) {
        const form = new ActionFormData()
            .title(title)
            .body(content)
            .button(lang === "ja" ? "§l<< 戻る" : "§l<< Back")
            .button(lang === "ja" ? "§c閉じる" : "§cClose");

        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === 0) {
                this.openRuleBook(player, lang);
            }
        });
    }

    // =========================================
    //  メインメニュー群
    // =========================================

    openMainMenu(player) {
        const form = new ActionFormData()
            .title("§lOne Block Shop")
            .body(`§eYour Gold: §6$${this.economy.getMoney(player)}`)
            .button("§aBuy Items", "textures/ui/store_home_icon")
            .button("§bSell Resources", "textures/items/diamond")
            .button("§cSell Junk (All)", "textures/items/bucket_empty")
            .button("§5Lapis Upgrades", "textures/items/dye_powder_blue")
            .button("§6OneBlock Upgrade", "textures/blocks/gold_block");

        form.show(player).then(response => {
            if (response.canceled) return;
            switch (response.selection) {
                case 0: this.openBuyCategoryMenu(player); break;
                case 1: this.openSellResourceMenu(player); break;
                case 2: this.sellJunk(player); break;
                case 3: this.openUpgradeMenu(player); break;
                case 4: this.openBlockUpgradeMenu(player); break;
            }
        });
    }

    openBuyCategoryMenu(player) {
        const form = new ActionFormData()
            .title("Buy Items")
            .body("Select a category:")
            .button("Blocks", "textures/blocks/dirt")
            .button("Armor", "textures/items/iron_chestplate")
            .button("Weapons & Tools", "textures/items/diamond_sword")
            .button("Machines & Utility", "textures/items/redstone_dust")
            .button("§l<< Back");

        form.show(player).then(res => {
            if (res.canceled) return;
            switch (res.selection) {
                case 0: this.openBuyList(player, ["minecraft:dirt", "minecraft:oak_planks", "minecraft:end_stone", "minecraft:obsidian"]); break;
                case 1: this.openArmorList(player); break;
                case 2: 
                    const weaponItems = [
                        "obw:knockback_sword",
                        "minecraft:stone_sword", "minecraft:bow", "minecraft:arrow", "minecraft:mace", 
                        "minecraft:anvil", "minecraft:netherite_upgrade_smithing_template",
                        "book:sharpness", "book:punch", "book:protection", "book:efficiency", "book:flame"
                    ];
                    if (this.oneBlockSystem?.phaseManager?.gameMode === "blitz") {
                        weaponItems.unshift("minecraft:iron_pickaxe");
                    }
                    this.openBuyList(player, weaponItems); 
                    break;
                case 3: this.openBuyList(player, [
                    "obw:auto_miner", "obw:generator", 
                    "obw:fireball", "obw:bridge_egg", "minecraft:silverfish_spawn_egg",
                    "minecraft:wind_charge", "minecraft:ender_pearl",
                    "minecraft:experience_bottle", "minecraft:ender_chest"
                ]); break;
                case 4: this.openMainMenu(player); break;
            }
        });
    }

    openArmorList(player) {
        const items = [
            "minecraft:leather_helmet", "minecraft:leather_chestplate", "minecraft:leather_leggings", "minecraft:leather_boots",
            "minecraft:chainmail_helmet", "minecraft:chainmail_chestplate", "minecraft:chainmail_leggings", "minecraft:chainmail_boots",
            "minecraft:iron_helmet", "minecraft:iron_chestplate", "minecraft:iron_leggings", "minecraft:iron_boots"
        ];
        this.openBuyList(player, items);
    }

    openBuyList(player, itemIds) {
        const form = new ActionFormData().title("Purchase");
        const money = this.economy.getMoney(player);
        const validItems = [];

        const isBlitz = (this.oneBlockSystem?.phaseManager?.gameMode === "blitz");
        if (isBlitz) {
            form.body("§c§lBLITZ SALE!\n§eItems: 25% OFF\n§bMovement: 50% OFF");
        }

        for (const id of itemIds) {
            const basePrice = Prices.buy[id];
            if (!basePrice) continue;

            const price = this.getAdjustedPrice(basePrice, id);

            let name = id.replace("minecraft:", "").replace("obw:", "").replace("book:", "Enchant: ").replace(/_/g, " ");
            name = name.charAt(0).toUpperCase() + name.slice(1);
            
            if (id.includes("dirt") || id.includes("planks") || id.includes("end_stone")) name += " (x16)";
            if (id === "minecraft:arrow") name += " (x8)";
            if (id === "minecraft:wind_charge") name += " (x1)";
            if (id === "book:punch") name = "Enchant: Punch (Bow)";
            if (id.includes("template")) name = "Netherite Upgrade Template";
            if (id === "minecraft:experience_bottle") name += " (x8)";
            if (id === "minecraft:silverfish_spawn_egg") name = "Silverfish Egg";

            const icon = this.getIconPath(id);

            let suffix = "";
            if (id === "obw:auto_miner" && player.hasTag("obw_bought_miner")) suffix = " §c(Sold Out)";
            if (id === "obw:generator" && player.hasTag("obw_bought_generator")) suffix = " §c(Sold Out)";

            const priceColor = isBlitz ? "§e" : (money >= price ? "§a" : "§c");
            form.button(`${name}${suffix}\n${priceColor}$${price}`, icon);
            validItems.push(id);
        }
        
        form.button("§l<< Back");

        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === validItems.length) {
                this.openBuyCategoryMenu(player);
                return;
            }

            const selectedId = validItems[res.selection];
            this.processPurchase(player, selectedId, itemIds);
        });
    }

    processPurchase(player, itemId, currentCategoryItems) {
        if (itemId === "obw:auto_miner" && player.hasTag("obw_bought_miner")) {
            player.sendMessage("§cYou can only buy Auto Miner once per game!");
            return;
        }
        if (itemId === "obw:generator" && player.hasTag("obw_bought_generator")) {
            player.sendMessage("§cYou can only buy Generator once per game!");
            return;
        }

        const basePrice = Prices.buy[itemId];
        const price = this.getAdjustedPrice(basePrice, itemId);
        
        if (this.economy.subtractMoney(player, price)) {
            try {
                if (itemId === "obw:auto_miner") {
                    player.addTag("obw_bought_miner");
                    if (this.automation) this.automation.activateAutoMiner(player);
                    player.sendMessage(`§aPurchased Auto Miner for $${price}`);
                    this.playSound(player, "random.orb");
                }
                else if (itemId === "obw:generator") {
                    player.addTag("obw_bought_generator");
                    if (this.automation) this.automation.activateGenerator(player);
                    player.sendMessage(`§aPurchased Generator for $${price}`);
                    this.playSound(player, "random.orb");
                }
                else if (this.isArmor(itemId)) {
                    this.processArmorPurchase(player, itemId, price);
                }
                else {
                    const inv = player.getComponent("inventory").container;
                    let itemStack;
                    
                    if (itemId.startsWith("book:")) {
                        itemStack = new ItemStack("minecraft:enchanted_book", 1);
                        const enchantName = itemId.split(":")[1];
                        const typeId = "minecraft:" + enchantName;
                        const enchantType = EnchantmentTypes.get(typeId);
                        if (enchantType) {
                            const enchantable = itemStack.getComponent("minecraft:enchantable");
                            enchantable.addEnchantment({ type: enchantType, level: 1 });
                        }
                    } 
                    else if (itemId === "obw:fireball") {
                        itemStack = new ItemStack("minecraft:fire_charge", 1);
                        itemStack.nameTag = "§cThrowing Fireball";
                        itemStack.setLore(["§7Right-click to throw!"]);
                    }
                    else if (itemId === "obw:bridge_egg") {
                        itemStack = new ItemStack("minecraft:egg", 1);
                        itemStack.nameTag = "§bBridge Egg";
                        itemStack.setLore(["§7Creates a bridge as it flies"]);
                    }
                    else if (itemId === "obw:home_scroll") {
                        itemStack = new ItemStack("minecraft:paper", 1);
                        itemStack.nameTag = "§bHome Teleport Scroll";
                        itemStack.setLore(["§7Right-click to teleport home", "§c(Consumable)"]);
                    }
                    else if (itemId === "obw:knockback_sword") {
                        itemStack = new ItemStack("minecraft:wooden_sword", 1);
                        itemStack.nameTag = "§bKnockback Sword";
                        const enchantable = itemStack.getComponent("minecraft:enchantable");
                        if (enchantable) {
                            enchantable.addEnchantment({ type: EnchantmentTypes.get("knockback"), level: 2 });
                        }
                    }
                    else {
                        let count = 1;
                        if (itemId.includes("dirt") || itemId.includes("planks") || itemId.includes("end_stone")) count = 16;
                        if (itemId === "minecraft:arrow") count = 8;
                        if (itemId === "minecraft:experience_bottle") count = 8;
                        
                        itemStack = new ItemStack(itemId, count);
                    }

                    const remainder = inv.addItem(itemStack);
                    if (remainder && remainder.amount > 0) {
                         player.dimension.spawnItem(remainder, player.location);
                         player.sendMessage("§eInventory full! Item dropped.");
                    }
                    
                    player.sendMessage(`§aPurchased for $${price}`);
                    this.playSound(player, "random.orb");
                }

                this.openBuyList(player, currentCategoryItems);

            } catch (e) {
                console.error(`Purchase Error: ${e}`);
                player.sendMessage("§cError occurred. Refunded.");
                this.economy.addMoney(player, price);
            }
        } else {
            player.sendMessage("§cNot enough money!");
            this.playSound(player, "note.bass");
        }
    }

    isArmor(itemId) {
        return itemId.includes("_helmet") || 
               itemId.includes("_chestplate") || 
               itemId.includes("_leggings") || 
               itemId.includes("_boots");
    }

    processArmorPurchase(player, itemId, price) {
        const equipment = player.getComponent("equippable");
        if (!equipment) {
            const inv = player.getComponent("inventory").container;
            inv.addItem(new ItemStack(itemId, 1));
            return;
        }

        let slot = EquipmentSlot.Head;
        if (itemId.includes("_chestplate")) slot = EquipmentSlot.Chest;
        else if (itemId.includes("_leggings")) slot = EquipmentSlot.Legs;
        else if (itemId.includes("_boots")) slot = EquipmentSlot.Feet;

        const currentArmor = equipment.getEquipment(slot);
        const newArmor = new ItemStack(itemId, 1);

        equipment.setEquipment(slot, newArmor);

        if (currentArmor) {
            const inv = player.getComponent("inventory").container;
            const remainder = inv.addItem(currentArmor);
            if (remainder && remainder.amount > 0) {
                player.dimension.spawnItem(remainder, player.location);
                player.sendMessage("§ePrevious armor dropped at your feet (Inventory full).");
            } else {
                player.sendMessage("§ePrevious armor moved to inventory.");
            }
        }

        player.sendMessage(`§aPurchased and Equipped! (-$${price})`);
        this.playSound(player, "random.anvil_use");
    }

    // =========================================
    //  売却メニュー
    // =========================================

    openSellResourceMenu(player) {
        const form = new ActionFormData()
            .title("Sell Resources")
            .body("Select how you want to sell your resources.")
            .button("§bSell All Resources (Bulk)\n§7Everything in inventory", "textures/ui/refresh_light")
            .button("§eSelect Items to Sell\n§7Choose specific items", "textures/ui/inventory_icon")
            .button("§l<< Back");

        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === 0) {
                this.confirmSellAll(player);
            } else if (res.selection === 1) {
                this.openSellIndividualMenu(player);
            } else {
                this.openMainMenu(player);
            }
        });
    }

    confirmSellAll(player) {
        const form = new MessageFormData()
            .title("Sell All Confirmation")
            .body("§cAre you sure you want to sell ALL valuable resources in your inventory?")
            .button1("§lYes, Sell All")
            .button2("§lNo, Cancel");

        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === 0) { 
                this.sellAllResources(player);
            } else {
                this.openSellResourceMenu(player);
            }
        });
    }

    openSellIndividualMenu(player) {
        const inv = player.getComponent("inventory").container;
        const sellableItems = new Map();

        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (!item) continue;
            if (item.typeId === "minecraft:emerald" && item.nameTag === "§aShop Menu") continue;

            if (Prices.sell[item.typeId]) {
                const current = sellableItems.get(item.typeId) || 0;
                sellableItems.set(item.typeId, current + item.amount);
            }
        }

        if (sellableItems.size === 0) {
            player.sendMessage("§cYou don't have any sellable resources.");
            return;
        }

        const form = new ActionFormData()
            .title("Select Item to Sell")
            .body("Choose an item to sell all of that type:");

        const itemIds = [];
        for (const [id, count] of sellableItems) {
            const unitPrice = Prices.sell[id];
            const totalValue = unitPrice * count;
            let name = id.replace("minecraft:", "").replace(/_/g, " ");
            name = name.charAt(0).toUpperCase() + name.slice(1);
            const icon = this.getIconPath(id);
            form.button(`${name} (x${count})\n§6$${totalValue}`, icon);
            itemIds.push(id);
        }
        
        form.button("§l<< Back");

        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === itemIds.length) {
                this.openSellResourceMenu(player);
                return;
            }
            const selectedId = itemIds[res.selection];
            this.sellSpecificItemType(player, selectedId);
        });
    }

    sellSpecificItemType(player, typeId) {
        const inv = player.getComponent("inventory").container;
        const unitPrice = Prices.sell[typeId];
        let totalSold = 0;

        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (!item) continue;
            if (item.typeId === typeId) {
                totalSold += item.amount;
                inv.setItem(i, undefined);
            }
        }

        if (totalSold > 0) {
            const totalValue = totalSold * unitPrice;
            this.economy.addMoney(player, totalValue);
            player.sendMessage(`§aSold ${totalSold} items for §6$${totalValue}`);
            this.playSound(player, "random.orb");
        } else {
            player.sendMessage("§cItem not found.");
        }
        this.openSellIndividualMenu(player);
    }

    sellAllResources(player) {
        const inv = player.getComponent("inventory").container;
        let totalValue = 0;
        let totalCount = 0;
        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (!item) continue;
            if (item.typeId === "minecraft:emerald" && item.nameTag === "§aShop Menu") continue;
            const unitPrice = Prices.sell[item.typeId];
            if (unitPrice) {
                const value = unitPrice * item.amount;
                totalValue += value;
                totalCount += item.amount;
                inv.setItem(i, undefined);
            }
        }
        if (totalCount > 0) {
            this.economy.addMoney(player, totalValue);
            player.sendMessage(`§aSold ${totalCount} items for §6$${totalValue}`);
            this.playSound(player, "random.orb");
        } else {
            player.sendMessage("§cNo valuable resources found.");
        }
    }

    sellJunk(player) {
        const inv = player.getComponent("inventory").container;
        let totalSold = 0;
        let totalValue = 0;
        const keepItems = [
            "minecraft:emerald",
            "minecraft:iron_ingot", "minecraft:gold_ingot", "minecraft:diamond", "minecraft:netherite_ingot",
            "minecraft:coal", "minecraft:charcoal",
            "minecraft:raw_iron", "minecraft:raw_gold", "minecraft:raw_copper",
            "minecraft:copper_ingot",
            "minecraft:redstone", "minecraft:lapis_lazuli", "minecraft:quartz", "minecraft:amethyst_shard",
            "minecraft:iron_sword", "minecraft:diamond_sword", "minecraft:stone_sword", "minecraft:mace",
            "minecraft:bow", "minecraft:arrow", "minecraft:wind_charge", "obw:home_scroll",
            "minecraft:iron_pickaxe", "minecraft:diamond_pickaxe", "minecraft:golden_pickaxe",
            "minecraft:iron_axe", "minecraft:diamond_axe",
            "minecraft:iron_helmet", "minecraft:iron_chestplate", "minecraft:iron_leggings", "minecraft:iron_boots",
            "minecraft:diamond_helmet", "minecraft:diamond_chestplate", "minecraft:diamond_leggings", "minecraft:diamond_boots",
            "minecraft:chainmail_helmet", "minecraft:chainmail_chestplate", "minecraft:chainmail_leggings", "minecraft:chainmail_boots",
            "minecraft:leather_helmet", "minecraft:leather_chestplate", "minecraft:leather_leggings", "minecraft:leather_boots",
            "minecraft:netherite_upgrade_smithing_template",
            "minecraft:experience_bottle",
            "obw:knockback_sword", 
            "minecraft:silverfish_spawn_egg",
            "minecraft:ender_chest"
        ];
        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (!item) continue;
            const isValuable = keepItems.includes(item.typeId) || item.hasComponent("enchantments");
            const isShopMenu = item.typeId === "minecraft:emerald" && item.nameTag === "§aShop Menu";
            if (!isValuable && !isShopMenu) {
                const count = item.amount;
                totalSold += count;
                totalValue += count * 1;
                inv.setItem(i, undefined);
            }
        }
        if (totalSold > 0) {
            this.economy.addMoney(player, totalValue);
            player.sendMessage(`§aSold ${totalSold} junk items for $${totalValue}`);
            this.playSound(player, "random.orb");
        } else {
            player.sendMessage("§cNo junk items found.");
        }
    }

    // =========================================
    //  アップグレード関連
    // =========================================

    openUpgradeMenu(player) {
        const lapisCount = this.countItem(player, "minecraft:lapis_lazuli");
        const form = new ActionFormData()
            .title("Lapis Upgrades")
            .body(`§9Lapis Lazuli: ${lapisCount}`)
            .button(`Home Teleport (1 use/game)\n§98 Lapis`, "textures/items/paper")
            .button(`Absorption (Passive)\n§916 Lapis`, "textures/items/potion_bottle_absorption")
            .button(`Haste Mining (Passive)\n§910 Lapis`, "textures/items/gold_pickaxe")
            .button(`Jump Boost I (Passive)\n§912 Lapis`, "textures/items/rabbit_foot")
            .button(`Speed I (Passive)\n§912 Lapis`, "textures/items/sugar")
            .button(`§l<< Back`);

        form.show(player).then(res => {
            if (res.canceled) return;
            switch (res.selection) {
                case 0: this.processLapisBuy(player, "obw:home_scroll", 8); break;
                case 1: this.processUpgrade(player, "obw_upgrade_absorption", 16, false); break;
                case 2: this.processUpgrade(player, "obw_upgrade_haste", 10, false); break;
                case 3: this.processUpgrade(player, "obw_upgrade_jump_boost", 12, false); break;
                case 4: this.processUpgrade(player, "obw_upgrade_speed", 12, false); break;
                case 5: this.openMainMenu(player); break;
            }
        });
    }

    processLapisBuy(player, itemId, cost) {
        if (itemId === "obw:home_scroll" && player.hasTag("obw_bought_scroll")) {
            player.sendMessage("§cYou can only buy Home Scroll once per game!");
            return;
        }

        if (this.removeItem(player, "minecraft:lapis_lazuli", cost)) {
            const inv = player.getComponent("inventory").container;
            let itemStack;
            
            if (itemId === "obw:home_scroll") {
                itemStack = new ItemStack("minecraft:paper", 1);
                itemStack.nameTag = "§bHome Teleport Scroll";
                itemStack.setLore(["§7Right-click to teleport home", "§c(Consumable)"]);
                player.addTag("obw_bought_scroll");
            }

            if (itemStack) {
                inv.addItem(itemStack);
                player.sendMessage(`§aPurchased Home Scroll! (-${cost} Lapis)`);
                this.playSound(player, "random.orb");
            }
        } else {
            player.sendMessage("§cNot enough Lapis Lazuli!");
            this.playSound(player, "note.bass");
        }
    }

    processUpgrade(player, tag, cost, isConsumable) {
        if (player.hasTag(tag)) {
            player.sendMessage("§cYou already have this upgrade!");
            return;
        }
        if (this.removeItem(player, "minecraft:lapis_lazuli", cost)) {
            player.addTag(tag);
            player.sendMessage(`§aUpgrade Acquired! (-${cost} Lapis)`);
            this.playSound(player, "random.levelup");
            if (tag === "obw_upgrade_haste") player.runCommand("effect @s haste 100000 1 true");
            if (tag === "obw_upgrade_absorption") player.runCommand("effect @s absorption 100000 0 true");
            if (tag === "obw_upgrade_jump_boost") player.runCommand("effect @s jump_boost 100000 0 true");
            if (tag === "obw_upgrade_speed") player.runCommand("effect @s speed 100000 0 true");
        } else {
            player.sendMessage("§cNot enough Lapis Lazuli!");
            this.playSound(player, "note.bass");
        }
    }

    openBlockUpgradeMenu(player) {
        const blockLoc = this.oneBlockSystem.getNearestHomeBlock(player);
        if (!blockLoc) {
            player.sendMessage("§cCannot find your OneBlock nearby to upgrade.");
            return;
        }
        const currentLevel = this.oneBlockSystem.getBlockLevel(blockLoc);
        const nextLevel = currentLevel + 1;
        let cost = Prices.upgrade_cost[nextLevel];

        if (cost) cost = this.getAdjustedPrice(cost);

        const isBlitz = (this.oneBlockSystem?.phaseManager?.gameMode === "blitz");
        const priceMsg = cost ? `§6$${cost}` + (isBlitz ? " §c(25% OFF!)" : "") : "§aMax Level Reached!";

        const form = new ActionFormData()
            .title("Upgrade OneBlock")
            .body(`Current Level: §eLv ${currentLevel}\n\nUpgrade to Lv ${nextLevel}: ${priceMsg}`)
            .button(cost ? "§aUpgrade!" : "§7Max Level", "textures/blocks/gold_block")
            .button("§l<< Back");
        form.show(player).then(res => {
            if (res.canceled) return;
            if (res.selection === 0 && cost) {
                this.processBlockUpgrade(player, blockLoc, nextLevel, cost);
            } else if (res.selection === 1) {
                this.openMainMenu(player);
            }
        });
    }

    processBlockUpgrade(player, location, nextLevel, cost) {
        if (this.economy.subtractMoney(player, cost)) {
            if (this.oneBlockSystem.upgradeBlock(location)) {
                player.sendMessage(`§aOneBlock upgraded to Level ${nextLevel}!`);
                this.playSound(player, "random.levelup");
                try {
                    player.dimension.runCommand(`playsound random.totem @a ${location.x} ${location.y} ${location.z}`);
                    player.dimension.spawnParticle("minecraft:totem_particle", {x:location.x+0.5, y:location.y+1, z:location.z+0.5});
                } catch(e) {}
            } else {
                this.economy.addMoney(player, cost);
                player.sendMessage("§cUpgrade failed. Refunded.");
            }
        } else {
            player.sendMessage("§cNot enough money!");
            this.playSound(player, "note.bass");
        }
    }

    removeItem(player, itemId, amount) {
        const inv = player.getComponent("inventory").container;
        let has = 0;
        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (item && item.typeId === itemId) has += item.amount;
        }
        if (has < amount) return false;
        let remaining = amount;
        for (let i = 0; i < inv.size; i++) {
            if (remaining <= 0) break;
            const item = inv.getItem(i);
            if (item && item.typeId === itemId) {
                if (item.amount > remaining) {
                    item.amount -= remaining;
                    inv.setItem(i, item);
                    remaining = 0;
                } else {
                    remaining -= item.amount;
                    inv.setItem(i, undefined);
                }
            }
        }
        return true;
    }

    countItem(player, itemId) {
        const inv = player.getComponent("inventory").container;
        let count = 0;
        for (let i = 0; i < inv.size; i++) {
            const item = inv.getItem(i);
            if (item && item.typeId === itemId) count += item.amount;
        }
        return count;
    }
}