import { world, system, EquipmentSlot, GameMode, ItemStack } from '@minecraft/server';


export const DrillSystem = {

    config: {
        maxHeat: 100,
        heatPerUse: 1.5,
        continuousHeatPerUse: 0.3,
        coolingRate: 1.2,
        maxRadius: 3,
        blocksPerTick: 2,
        durabilityUse: 1,
        maxDrillTime: 60,
        breakDelay: 4,
        cooldownThreshold: 85
    },


    activeDrills: new Map(),

    handleDrillUse(player, itemStack, useDuration) {
        try {
            const playerId = player.id;
            const mode = this.getDrillMode(player);
            const currentHeat = this.getDrillHeat(player);


            if (currentHeat >= this.config.maxHeat) {
                this.handleOverheat(player);
                return;
            }

            if (currentHeat >= this.config.cooldownThreshold) {
                player.onScreenDisplay.setActionBar('§e⚠ Drill too hot - Must cool before use ⚠');
                return;
            }


            if (this.activeDrills.has(playerId)) {
                return;
            }


            this.setDrillHeat(player, currentHeat + this.config.heatPerUse);


            this.playDrillSound(player, 'start');


            this.startContinuousDrilling(player, itemStack, mode);

        } catch (error) {
            world.sendMessage('§cDrill error: ' + error.message);
        }
    },

    handleBlockDrilling(player, itemStack, targetBlock, blockFace) {
        try {
            const mode = this.getDrillMode(player);
            const heat = this.getDrillHeat(player);


            if (heat >= this.config.maxHeat) {
                this.handleOverheat(player);
                return;
            }


            if (heat >= this.config.cooldownThreshold) {
                player.onScreenDisplay.setActionBar('§e⚠ Drill too hot - Must cool before use ⚠');
                return;
            }


            const blocksToBreak = this.calculateDrillAreaWithDirection(targetBlock.location, player, mode);


            this.setDrillHeat(player, heat + this.config.heatPerUse);


            this.breakBlocksWithDelay(player, itemStack, blocksToBreak);


            this.createDrillImpactEffects(player.dimension, targetBlock.location);
            this.playDrillSound(player, 'impact');

        } catch (error) {
            world.sendMessage('§cDrilling error: ' + error.message);
        }
    },

    startContinuousDrilling(player, itemStack, mode) {
        const playerId = player.id;
        let drillingTime = 0;
        let lastBlockTime = 0;

        const drillData = {
            intervalId: null,
            startTime: Date.now()
        };

        const drillInterval = system.runInterval(() => {
            try {
                drillingTime++;
                lastBlockTime++;


                const equippableComp = player.getComponent('minecraft:equippable');
                const currentItem = equippableComp?.getEquipment(EquipmentSlot.Mainhand);

                if (!currentItem || currentItem.typeId !== 'myw:mythril_drill') {
                    this.stopDrilling(playerId);
                    return;
                }


                const targetBlock = this.getTargetBlock(player);
                if (!targetBlock) {
                    this.stopDrilling(playerId);
                    return;
                }


                if (lastBlockTime >= this.config.breakDelay) {
                    lastBlockTime = 0;


                    const currentHeat = this.getDrillHeat(player);
                    this.setDrillHeat(player, currentHeat + this.config.heatPerUse);


                    if (currentHeat >= this.config.maxHeat) {
                        this.handleOverheat(player);
                        this.stopDrilling(playerId);
                        return;
                    }


                    const blocksToBreak = this.calculateDrillAreaWithDirection(targetBlock.location, player, 'continuous');


                    const blocksBatch = blocksToBreak.slice(0, this.config.blocksPerTick);
                    this.breakBlocksBatch(player, itemStack, blocksBatch);


                    this.consumeDurability(player, itemStack);
                }


                this.createContinuousDrillEffects(player);
                this.updateDrillDisplay(player, this.getDrillHeat(player), mode);


                if (drillingTime >= this.config.maxDrillTime) {
                    this.stopDrilling(playerId);
                    return;
                }

            } catch (error) {
                this.stopDrilling(playerId);
                world.sendMessage('§cContinuous drilling error: ' + error.message);
            }
        }, 1);

        drillData.intervalId = drillInterval;
        this.activeDrills.set(playerId, drillData);
    },

    stopDrilling(playerId) {
        const drillData = this.activeDrills.get(playerId);
        if (drillData && drillData.intervalId) {
            system.clearRun(drillData.intervalId);
            this.activeDrills.delete(playerId);


            const player = [...world.getPlayers()].find(p => p.id === playerId);
            if (player) {
                this.playDrillSound(player, 'stop');
                this.handleDrillStop(player);
            }
        }
    },

    calculateDrillAreaWithDirection(centerLocation, player, mode) {
        const blocks = [];
        const { x, y, z } = centerLocation;
        const viewDirection = player.getViewDirection();


        const absX = Math.abs(viewDirection.x);
        const absY = Math.abs(viewDirection.y);
        const absZ = Math.abs(viewDirection.z);

        let primaryAxis, secondaryAxis1, secondaryAxis2;


        if (absX > absY && absX > absZ) {

            primaryAxis = 'x';
            secondaryAxis1 = 'y';
            secondaryAxis2 = 'z';
        } else if (absZ > absX && absZ > absY) {

            primaryAxis = 'z';
            secondaryAxis1 = 'x';
            secondaryAxis2 = 'y';
        } else {

            primaryAxis = 'y';
            secondaryAxis1 = 'x';
            secondaryAxis2 = 'z';
        }

        switch (mode) {
            case 'precision': // 1x1
                blocks.push({
                    x: Math.floor(x),
                    y: Math.floor(y),
                    z: Math.floor(z)
                });
                break;

            case 'standard': // 3x3 perpendicular to view direction
                for (let i = -1; i <= 1; i++) {
                    for (let j = -1; j <= 1; j++) {
                        const block = {
                            x: Math.floor(x),
                            y: Math.floor(y),
                            z: Math.floor(z)
                        };

                        block[secondaryAxis1] += i;
                        block[secondaryAxis2] += j;

                        blocks.push(block);
                    }
                }
                break;

            case 'excavation': // 3x3x3 cube
                for (let dx = -1; dx <= 1; dx++) {
                    for (let dy = -1; dy <= 1; dy++) {
                        for (let dz = -1; dz <= 1; dz++) {
                            blocks.push({
                                x: Math.floor(x) + dx,
                                y: Math.floor(y) + dy,
                                z: Math.floor(z) + dz
                            });
                        }
                    }
                }
                break;

            case 'tunnel': // 3x3 tunnel in view direction
                const direction = viewDirection.x > 0 ? 1 : viewDirection.x < 0 ? -1 : 0;
                const directionZ = viewDirection.z > 0 ? 1 : viewDirection.z < 0 ? -1 : 0;
                const directionY = viewDirection.y > 0 ? 1 : viewDirection.y < 0 ? -1 : 0;

                for (let i = -1; i <= 1; i++) {
                    for (let j = -1; j <= 1; j++) {
                        for (let depth = 0; depth <= 3; depth++) {
                            const block = {
                                x: Math.floor(x),
                                y: Math.floor(y),
                                z: Math.floor(z)
                            };

                            if (primaryAxis === 'x') {
                                block.y += i;
                                block.z += j;
                                block.x += depth * (direction || 1);
                            } else if (primaryAxis === 'z') {
                                block.x += i;
                                block.y += j;
                                block.z += depth * (directionZ || 1);
                            } else {
                                block.x += i;
                                block.z += j;
                                block.y += depth * (directionY || 1);
                            }

                            blocks.push(block);
                        }
                    }
                }
                break;

            default: // Continuous
                blocks.push({
                    x: Math.floor(x),
                    y: Math.floor(y),
                    z: Math.floor(z)
                });
                break;
        }

        // Filter duplicates
        return blocks.filter((block, index, self) =>
            index === self.findIndex(b => b.x === block.x && b.y === block.y && b.z === block.z)
        );
    },

    breakBlocksWithDelay(player, itemStack, blockLocations) {
        let index = 0;

        const breakInterval = system.runInterval(() => {
            if (index >= blockLocations.length) {
                system.clearRun(breakInterval);
                return;
            }


            const batchSize = Math.min(2, blockLocations.length - index);
            for (let i = 0; i < batchSize; i++) {
                if (index + i < blockLocations.length) {
                    this.breakSingleBlock(player, blockLocations[index + i]);
                }
            }

            index += batchSize;
        }, 2);
    },

    breakBlocksBatch(player, itemStack, blockLocations) {
        blockLocations.forEach(location => {

            if (Math.random() > 0.3) {
                this.breakSingleBlock(player, location);
            }
        });
    },

    breakSingleBlock(player, location) {
        try {
            const block = player.dimension.getBlock(location);
            if (!block || block.typeId === 'minecraft:air') {
                return;
            }


            if (this.isUnbreakableBlock(block.typeId)) {
                return;
            }


            this.createBlockBreakEffects(player.dimension, location, block.typeId);

            block.setType('minecraft:air');


        } catch (error) {

        }
    },

    createContinuousDrillEffects(player) {
        try {
            const location = player.location;
            const dimension = player.dimension;


            if (Math.random() > 0.85) {
                for (let i = 0; i < 2; i++) {
                    const offsetX = (Math.random() - 0.5) * 2;
                    const offsetY = Math.random() * 2;
                    const offsetZ = (Math.random() - 0.5) * 2;

                    dimension.spawnParticle('minecraft:lava_particle', {
                        x: location.x + offsetX,
                        y: location.y + offsetY,
                        z: location.z + offsetZ
                    });
                }
            }


            if (Math.random() > 0.9) {
                dimension.spawnParticle('minecraft:campfire_smoke_particle', {
                    x: location.x,
                    y: location.y + 1,
                    z: location.z
                });
            }

        } catch (error) {
            // Continue if there's an error with particles
        }
    },

    createDrillEffects(player, targetLocation) {
        const { x, y, z } = targetLocation;
        const dimension = player.dimension;

        try {

            for (let i = 0; i < 3; i++) {
                const offsetX = (Math.random() - 0.5) * 1.5;
                const offsetY = (Math.random() - 0.5) * 1.5;
                const offsetZ = (Math.random() - 0.5) * 1.5;

                dimension.spawnParticle('minecraft:lava_particle', {
                    x: x + 0.5 + offsetX,
                    y: y + 0.5 + offsetY,
                    z: z + 0.5 + offsetZ
                });
            }


            for (let i = 0; i < 2; i++) {
                dimension.spawnParticle('minecraft:critical_hit_emitter', {
                    x: x + Math.random(),
                    y: y + Math.random(),
                    z: z + Math.random()
                });
            }
        } catch (error) {
            // Continue if there are problems with particles
        }
    },

    createBlockBreakEffects(dimension, location, blockType) {
        const { x, y, z } = location;

        try {

            let particleType = 'minecraft:block_destruct';
            let particleCount = 4;

            if (blockType.includes('stone')) {
                particleType = 'minecraft:villager_angry';
                particleCount = 3;
            } else if (blockType.includes('wood') || blockType.includes('log')) {
                particleType = 'minecraft:enchant_table_particle';
                particleCount = 2;
            } else if (blockType.includes('ore')) {
                particleType = 'minecraft:totem_particle';
                particleCount = 5;
            }


            for (let i = 0; i < particleCount; i++) {
                const offsetX = (Math.random() - 0.5) * 1.2;
                const offsetY = (Math.random() - 0.5) * 1.2;
                const offsetZ = (Math.random() - 0.5) * 1.2;

                dimension.spawnParticle(particleType, {
                    x: x + 0.5 + offsetX,
                    y: y + 0.5 + offsetY,
                    z: z + 0.5 + offsetZ
                });
            }
        } catch (error) {

            try {
                dimension.spawnParticle('minecraft:lava_particle', {
                    x: x + 0.5,
                    y: y + 0.5,
                    z: z + 0.5
                });
            } catch (backupError) {
                // Continue silently
            }
        }
    },

    createDrillImpactEffects(dimension, location) {
        const { x, y, z } = location;

        try {

            for (let ring = 1; ring <= 2; ring++) {
                system.runTimeout(() => {
                    const numParticles = ring * 4;
                    for (let i = 0; i < numParticles; i++) {
                        const angle = (i / numParticles) * Math.PI * 2;
                        const radius = ring * 0.3;

                        dimension.spawnParticle('minecraft:sonic_explosion', {
                            x: x + 0.5 + Math.cos(angle) * radius,
                            y: y + 0.5,
                            z: z + 0.5 + Math.sin(angle) * radius
                        });
                    }
                }, ring * 2);
            }
        } catch (error) {
            // Continue if there are problems
        }
    },

    getTargetBlock(player) {
        try {
            const viewDirection = player.getViewDirection();
            const headLocation = player.getHeadLocation();


            for (let distance = 0.5; distance <= 4; distance += 0.5) {
                const checkLocation = {
                    x: Math.floor(headLocation.x + viewDirection.x * distance),
                    y: Math.floor(headLocation.y + viewDirection.y * distance),
                    z: Math.floor(headLocation.z + viewDirection.z * distance)
                };

                try {
                    const block = player.dimension.getBlock(checkLocation);
                    if (block && block.typeId !== 'minecraft:air') {
                        return block;
                    }
                } catch (blockError) {

                    continue;
                }
            }

            return null;
        } catch (error) {
            return null;
        }
    },

    isUnbreakableBlock(blockType) {
        const unbreakable = [
            'minecraft:bedrock',
            'minecraft:barrier',
            'minecraft:structure_block',
            'minecraft:command_block',
            'minecraft:chain_command_block',
            'minecraft:repeating_command_block',
            'minecraft:jigsaw',
            'minecraft:structure_void'
        ];

        return unbreakable.includes(blockType);
    },

    playDrillSound(player, type) {
        try {
            let soundId = 'random.anvil_use';

            switch (type) {
                case 'start':
                    soundId = 'random.anvil_use';
                    break;
                case 'impact':
                    soundId = 'dig.stone';
                    break;
                case 'stop':
                    soundId = 'random.break';
                    break;
                case 'overheat':
                    soundId = 'random.fizz';
                    break;
            }


            player.dimension.runCommandAsync(`playsound ${soundId} @a ~ ~ ~ 0.5 1.2`);
        } catch (error) {

        }
    },

    // Drill heat system
    getDrillHeat(player) {
        try {
            return player.getDynamicProperty('myw:drill_heat') || 0;
        } catch (error) {
            return 0;
        }
    },

    setDrillHeat(player, heat) {
        try {
            const clampedHeat = Math.max(0, Math.min(heat, this.config.maxHeat));
            player.setDynamicProperty('myw:drill_heat', clampedHeat);
        } catch (error) {

        }
    },

    // Drill mode system
    getDrillMode(player) {
        try {
            return player.getDynamicProperty('myw:drill_mode') || 'standard';
        } catch (error) {
            return 'standard';
        }
    },

    setDrillMode(player, mode) {
        try {
            player.setDynamicProperty('myw:drill_mode', mode);
        } catch (error) {

        }
    },

    // Replace the cycleDrillMode function with this improved version:
    cycleDrillMode(player) {
        const modes = ['precision', 'standard', 'excavation', 'tunnel'];
        const currentMode = this.getDrillMode(player);
        const currentIndex = modes.indexOf(currentMode);
        const nextIndex = (currentIndex + 1) % modes.length;
        const newMode = modes[nextIndex];

        this.setDrillMode(player, newMode);

        // Improved messages with icons and colors
        const modeInfo = {
            'precision': {
                name: '§b§lPRECISION MODE',
                description: '§f1x1 - Drills single block',
                icon: '⚡',
                color: '§b'
            },
            'standard': {
                name: '§a§lSTANDARD MODE',
                description: '§f3x3 - Medium area',
                icon: '⚡',
                color: '§a'
            },
            'excavation': {
                name: '§6§lEXCAVATION MODE',
                description: '§f3x3x3 - Full cube',
                icon: '⚡',
                color: '§6'
            },
            'tunnel': {
                name: '§d§lTUNNEL MODE',
                description: '§f3x3 Directional - Deep tunnel',
                icon: '⚡',
                color: '§d'
            }
        };

        const info = modeInfo[newMode];

        // Message for action bar - only this one, no intrusions
        const actionBarMessage = `${info.icon} ${info.name} ${info.icon} - ${info.description}`;

        try {
            // Only show in action bar
            player.onScreenDisplay.setActionBar(actionBarMessage);

            // Show the message for a bit longer by repeating
            system.runTimeout(() => {
                player.onScreenDisplay.setActionBar(actionBarMessage);
            }, 20);

            system.runTimeout(() => {
                player.onScreenDisplay.setActionBar(actionBarMessage);
            }, 40);

        } catch (error) {
            // Minimal fallback if it fails
            world.sendMessage(`§b${player.name} §fchanged drill to ${info.name}`);
        }

        // Confirmation sound
        this.playDrillSound(player, 'start');

        // Visual mode change effects (subtle)
        this.createModeChangeEffects(player, newMode);
    },

    // New function for visual effects when changing mode
    createModeChangeEffects(player, mode) {
        const location = player.location;
        const dimension = player.dimension;

        const modeParticles = {
            'precision': 'minecraft:endrod',
            'standard': 'minecraft:villager_happy',
            'excavation': 'minecraft:lava_particle',
            'tunnel': 'minecraft:portal_directional'
        };

        try {
            const particleType = modeParticles[mode] || 'minecraft:totem_particle';

            // Create particle circle around player
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const radius = 1.5;

                dimension.spawnParticle(particleType, {
                    x: location.x + Math.cos(angle) * radius,
                    y: location.y + 1,
                    z: location.z + Math.sin(angle) * radius
                });
            }
        } catch (error) {
            // Continue if there's an error with particles
        }
    },

    displayModeChange(player, mode) {
        const modeMessages = {
            'precision': '§l§b⚡ PRECISION MODE ACTIVATED §f(1x1) ⚡',
            'standard': '§l§a⚡ STANDARD MODE ACTIVATED §f(3x3) ⚡',
            'excavation': '§l§6⚡ EXCAVATION MODE ACTIVATED §f(3x3x3) ⚡',
            'tunnel': '§l§d⚡ TUNNEL MODE ACTIVATED §f(3x3 Directional) ⚡'
        };

        const shortMessages = {
            'precision': '§b⚡ Precision §f(1x1)',
            'standard': '§a⚡ Standard §f(3x3)',
            'excavation': '§6⚡ Excavation §f(3x3x3)',
            'tunnel': '§d⚡ Tunnel §f(3x3 Dir.)'
        };

        try {

            const bigMessage = modeMessages[mode] || '§l§7⚡ UNKNOWN MODE ⚡';
            player.onScreenDisplay.setActionBar(bigMessage);


            system.runTimeout(() => {
                const shortMessage = shortMessages[mode] || '§7⚡ Unknown';
                try {
                    player.onScreenDisplay.setActionBar(shortMessage);
                } catch (error) {

                }
            }, 40);

        } catch (error) {

        }
    },

    updateDrillDisplay(player, heat, mode) {
        try {
            const heatPercentage = (heat / this.config.maxHeat) * 100;
            let heatColor = '§a';

            if (heatPercentage > 70) heatColor = '§c';
            else if (heatPercentage > 40) heatColor = '§e';

            const heatBar = this.createProgressBar(heatPercentage, 10);
            const modeDisplay = this.getModeDisplay(mode);

            const displayText = `§l${modeDisplay} §r| ${heatColor}Heat: ${heatBar} §f${Math.round(heatPercentage)}%`;

            player.onScreenDisplay.setActionBar(displayText);
        } catch (error) {

        }
    },

    getModeDisplay(mode) {
        const displays = {
            'precision': '§b⚡ PRECISION',
            'standard': '§a⚡ STANDARD',
            'excavation': '§6⚡ EXCAVATION',
            'tunnel': '§d⚡ TUNNEL'
        };

        return displays[mode] || '§7⚡ NORMAL';
    },

    createProgressBar(percentage, length) {
        const filled = Math.round((percentage / 100) * length);
        const empty = length - filled;

        let color = '§a';
        if (percentage > 70) color = '§c';
        else if (percentage > 40) color = '§e';

        return color + '█'.repeat(filled) + '§8' + '░'.repeat(empty);
    },

    handleOverheat(player) {
        try {

            this.stopDrilling(player.id);


            player.onScreenDisplay.setActionBar('§c§l⚠ DRILL OVERHEATED - COOLING ⚠');


            player.addEffect('slowness', 40, { amplifier: 0, showParticles: false });


            const { x, y, z } = player.location;
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('minecraft:lava_particle', {
                            x: x + (Math.random() - 0.5) * 2,
                            y: y + Math.random() * 2,
                            z: z + (Math.random() - 0.5) * 2
                        });
                    } catch (particleError) {

                    }
                }, i * 2);
            }


            this.playDrillSound(player, 'overheat');


            system.runTimeout(() => {
                this.setDrillHeat(player, this.config.maxHeat * 0.3);
            }, 60);

        } catch (error) {

        }
    },

    handleDrillStop(player) {
        try {
            player.onScreenDisplay.setActionBar('§7⚡ Drill stopped - Cooling...');
        } catch (error) {

        }
    },

    consumeDurability(player, itemStack) {
        try {
            if (player.getGameMode() !== GameMode.survival) return;

            const durabilityComponent = itemStack.getComponent('minecraft:durability');
            if (!durabilityComponent) return;

            const currentDamage = durabilityComponent.damage || 0;
            const maxDurability = durabilityComponent.maxDurability;
            const newDamage = currentDamage + this.config.durabilityUse;

            if (newDamage >= maxDurability) {
                // Broken drill
                this.handleDrillBreak(player);
                const equippableComp = player.getComponent('minecraft:equippable');
                if (equippableComp) {
                    equippableComp.setEquipment(EquipmentSlot.Mainhand, undefined);
                }
            } else {
                durabilityComponent.damage = newDamage;
            }
        } catch (error) {

        }
    },

    handleDrillBreak(player) {
        try {

            this.stopDrilling(player.id);

            const { x, y, z } = player.location;


            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('minecraft:totem_particle', {
                            x: x + (Math.random() - 0.5) * 3,
                            y: y + Math.random() * 2.5,
                            z: z + (Math.random() - 0.5) * 3
                        });
                    } catch (particleError) {
                        // Continue
                    }
                }, i * 3);
            }

            player.onScreenDisplay.setActionBar('§c§l THE MYTHRIL DRILL HAS BROKEN! ');
            world.sendMessage(`§b${player.name}§f's Mythril Drill has broken from overuse!`);


            this.playDrillSound(player, 'stop');

        } catch (error) {

        }
    }
};


export function registerMythrilDrill(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_drill', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            DrillSystem.handleDrillUse(source, itemStack, useDuration);
        },

        onUseOn(eventData) {
            const { itemStack, source, block, blockFace, faceLocation } = eventData;
            DrillSystem.handleBlockDrilling(source, itemStack, block, blockFace);
        },

        onHitEntity(eventData) {

            const { source } = eventData;
            if (source) {
                source.onScreenDisplay.setActionBar('§c⚠ Drill should not be used on entities ⚠');
            }
        }
    });
}


export function initializeDrillSystems() {

    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                const currentHeat = DrillSystem.getDrillHeat(player);
                if (currentHeat > 0) {

                    const newHeat = Math.max(0, currentHeat - DrillSystem.config.coolingRate);
                    DrillSystem.setDrillHeat(player, newHeat);


                    if (currentHeat >= DrillSystem.config.cooldownThreshold && newHeat < DrillSystem.config.cooldownThreshold) {
                        player.onScreenDisplay.setActionBar('§a✓ Drill ready to use again');
                    }
                }
            });
        } catch (error) {
            // Cooling error, continue
        }
    }, 20);

    // Cleanup active drills from disconnected players
    system.runInterval(() => {
        try {
            const activePlayers = new Set([...world.getAllPlayers()].map(p => p.id));

            for (const [playerId, drillData] of DrillSystem.activeDrills.entries()) {
                if (!activePlayers.has(playerId)) {
                    if (drillData.intervalId) {
                        system.clearRun(drillData.intervalId);
                    }
                    DrillSystem.activeDrills.delete(playerId);
                }
            }
        } catch (error) {

        }
    }, 100); // Every 5 seconds

    world.beforeEvents.itemUse.subscribe(eventData => {
        if (eventData.itemStack?.typeId === 'myw:mythril_drill') {
            const player = eventData.source;

            try {
                // Check if sneaking
                if (player.isSneaking) {
                    // Cancel the event FIRST to avoid conflicts
                    eventData.cancel = true;

                    // Then execute mode change
                    system.run(() => {
                        DrillSystem.cycleDrillMode(player);
                    });
                }
            } catch (error) {
                world.sendMessage('§cError changing mode: ' + error.message);
            }
        }
    });


    world.afterEvents.itemStopUse.subscribe(eventData => {
        if (eventData.itemStack?.typeId === 'myw:mythril_drill') {
            const player = eventData.source;
            DrillSystem.stopDrilling(player.id);
        }
    });


    world.afterEvents.playerLeave.subscribe(eventData => {
        DrillSystem.stopDrilling(eventData.playerId);
    });
}