// priority: 1000
// 连锁采集 - 3×3×3范围版本
function chain_destruction(event, maxMultiple) {
    let player = event.getPlayer();
    if (!player) return;

    let centerBlock = event.getBlock();
    let level = centerBlock.getLevel();
    let handItem = player.getMainHandItem();
    let centerBlockId = centerBlock.getId();

    // 使用Set来存储唯一的位置标识
    let processedPositions = new Set();
    let blocksToBreak = [];

    // 添加初始方块
    blocksToBreak.push(centerBlock);
    processedPositions.add(centerBlock.getPos().asLong());

    // 广度优先搜索遍历相同类型的方块
    for (let i = 0; i < blocksToBreak.length && blocksToBreak.length < maxMultiple; i++) {
        let currentBlock = blocksToBreak[i];
        let currentPos = currentBlock.getPos();

        // 遍历3×3×3区域（不包括自身）
        for (let dx = -1; dx <= 1; dx++) {
            for (let dy = -1; dy <= 1; dy++) {
                for (let dz = -1; dz <= 1; dz++) {
                    // 跳过自身
                    if (dx === 0 && dy === 0 && dz === 0) continue;

                    let checkPos = currentPos.offset(dx, dy, dz);
                    let posLong = checkPos.asLong();

                    // 如果已经处理过，跳过
                    if (processedPositions.has(posLong)) continue;

                    processedPositions.add(posLong);

                    let checkBlock = level.getBlock(checkPos);

                    // 检查方块是否与中心方块类型相同
                    if (checkBlock.getId() === centerBlockId) {
                        blocksToBreak.push(checkBlock);

                        // 如果达到最大连锁数量，停止添加
                        if (blocksToBreak.length >= maxMultiple) break;
                    }
                }
                if (blocksToBreak.length >= maxMultiple) break;
            }
            if (blocksToBreak.length >= maxMultiple) break;
        }
    }

    // 破坏所有找到的方块
    blocksToBreak.forEach(block => {
        $EffectHelper.breakBlock(level, player, handItem, block.getPos(), block.getBlockState(), true, false);
        event.entity.getServer().scheduleInTicks(1, () => {
            if (block) {
                block.set('minecraft:air')
            }
        });
    });
}