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

// 亮度方块刷新
const glowingDummyBlock = {
    onTick(event) {
        const block = event.block;
        let glowingState = block.permutation.getState('pm_mock:glowing_state');
        if (glowingState < 4) {
            glowingState++;
            block.setPermutation(block.permutation.withState('pm_mock:glowing_state', glowingState));
        }
        else {
            block.setType('minecraft:air');
        }

        // console.warn(`方块 (${block.location.x}, ${block.location.y}, ${block.location.z}) 状态: ${glowingState}`);
    }
};

// 注册自定义组件
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(
        "pm_mock:glowing_dummy_block", glowingDummyBlock
    );
});


// 装备
const ancientArmors = {
    Head: "pm_mock:ancient_armors_helmet",
    Chest: "pm_mock:ancient_armors_chestplate",
    Legs: "pm_mock:ancient_armors_leggings",
    Feet: "pm_mock:ancient_armors_boots"
};

// 全局定时器，检查是不是穿了全套装备
system.runInterval(() => {
    const players = world.getAllPlayers();
    for (const player of players) {
        const equipmentComp = player.getComponent('minecraft:equippable');
        if (equipmentComp) {
            let isFullSet = true;

            for (const slot in ancientArmors) {
                const item = equipmentComp.getEquipment(slot);
                if (!item || item.typeId !== ancientArmors[slot]) {
                    isFullSet = false;
                    break;
                }
            }

            if (isFullSet) {
                let block = player.dimension.getBlock(player.location);
                let processed = false;
                let attempts = 0;
                const maxAttempts = 3;

                while (attempts < maxAttempts && !processed) {
                    if (block && (block.typeId === 'pm_mock:glowing_dummy_block' || block.typeId === 'minecraft:air')) {
                        if (block.typeId === 'pm_mock:glowing_dummy_block') {
                            block.setPermutation(block.permutation.withState('pm_mock:glowing_state', 0));
                        } else {
                            block.setType('pm_mock:glowing_dummy_block');
                        }
                        processed = true;
                    } else {
                        block = block.above();
                        attempts++;
                    }
                }
            }
        }
    }
}, 5);