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

export const PickaxeSystem = {

    config: {
        detectionRadius: 12, // Increased from 6 to 12
        maxVeinSize: 8, // Reduced from 15 to 8 to make vein mining less powerful
        detectionCooldown: 80, // Reduced from 100 to 80 ticks (4 seconds)
        veinMineCooldown: 250, // Increased from 200 to 250 ticks (12.5 seconds)
        particleIntensity: 0.7,
        dustDropChance: 0.35, // 35% chance for dust drops
        nuggetDropChance: 0.20 // 20% chance for nugget drops
    },

    // Utility function for sending styled action bar messages (removed title fallback)
    sendActionBar(player, message, color = '§b') {
        try {
            player.onScreenDisplay.setActionBar(`${color}${message}`);
        } catch (error) {
            // If action bar fails, try without formatting
            try {
                player.onScreenDisplay.setActionBar(message);
            } catch (e) {
                // Silent fail - action bar is our only method
            }
        }
    },

    // Modified to only use action bar
    sendTitle(player, title, subtitle = '', color = '§b') {
        // Convert title to action bar message
        const fullMessage = subtitle ? `${title} §8▸ ${subtitle}` : title;
        this.sendActionBar(player, fullMessage, color);
    },

    handlePickaxeUse(player, itemStack, useDuration) {
        try {
            // Check if sneaking for treasure detection
            if (player.isSneaking) {
                this.activateTreasureDetection(player);
                return;
            }

        } catch (error) {
            this.sendActionBar(player, ' Pickaxe Error Occurred', '§c');
        }
    },

    handleBlockMining(player, itemStack, targetBlock, blockFace) {
        try {
            const blockType = targetBlock.typeId;

            // Check if it's a valuable ore and player is sneaking for vein mining
            if (this.isValuableOre(blockType) && player.isSneaking) {
                this.startVeinMining(player, itemStack, targetBlock);
                return;
            }

            // Normal mining effects with mythril drops for ALL blocks
            this.createMiningEffects(player, targetBlock.location, blockType);

        } catch (error) {
            this.sendActionBar(player, 'Mining Error', '§c');
        }
    },

    activateTreasureDetection(player) {
        try {
            const playerId = player.id;

            // Check cooldown
            const lastDetection = player.getDynamicProperty('myw:last_detection') || 0;
            const currentTime = Date.now();

            if (currentTime - lastDetection < this.config.detectionCooldown * 50) {
                const remainingTime = Math.ceil((this.config.detectionCooldown * 50 - (currentTime - lastDetection)) / 1000);
                this.sendActionBar(player, ` §6Treasure Scanner Cooldown §8▸ §e${remainingTime}s remaining`, '§6');
                return;
            }

            // Set cooldown
            player.setDynamicProperty('myw:last_detection', currentTime);

            // Show activation message
            this.sendActionBar(player, ' §bAdvanced Treasure Scanner §8▸ §aInitializing Deep Scan...', '§b');

            // Start detection
            this.scanForTreasures(player);

        } catch (error) {
            // Silent error
        }
    },

    scanForTreasures(player) {
        try {
            const playerLocation = player.location;
            const dimension = player.dimension;
            const radius = this.config.detectionRadius;
            const treasures = [];
            const oreTypes = new Map(); // Track different ore types

            // Show advanced scanning message
            this.sendActionBar(player, ' §bDeep Scanning §8▸ §eAnalyzing ' + (radius * 2 + 1) + '³ block area...', '§b');

            // More comprehensive scan with layered detection
            for (let x = -radius; x <= radius; x++) {
                for (let y = -radius; y <= radius; y++) {
                    for (let z = -radius; z <= radius; z++) {
                        const checkLocation = {
                            x: Math.floor(playerLocation.x) + x,
                            y: Math.floor(playerLocation.y) + y,
                            z: Math.floor(playerLocation.z) + z
                        };

                        try {
                            const block = dimension.getBlock(checkLocation);
                            if (block && this.isValuableOre(block.typeId)) {
                                const distance = Math.sqrt(x * x + y * y + z * z);
                                const oreName = this.getOreName(block.typeId);

                                treasures.push({
                                    location: checkLocation,
                                    type: block.typeId,
                                    distance: distance,
                                    oreName: oreName
                                });

                                // Count ore types
                                oreTypes.set(oreName, (oreTypes.get(oreName) || 0) + 1);
                            }
                        } catch (blockError) {
                            continue;
                        }
                    }
                }
            }

            // Enhanced delay for dramatic effect with more comprehensive results
            system.runTimeout(() => {
                if (treasures.length > 0) {
                    this.displayAdvancedDetectedTreasures(player, treasures, oreTypes);
                    this.createDetectionEffects(player, treasures);
                } else {
                    this.sendActionBar(player, ' §7Advanced Scan Complete §8▸ §7No Valuable Ores in ' + radius + 'm radius', '§7');
                }
            }, 30);

        } catch (error) {
            // Silent error
        }
    },

    displayAdvancedDetectedTreasures(player, treasures, oreTypes) {
        const treasureCount = treasures.length;
        const nearestTreasure = treasures.sort((a, b) => a.distance - b.distance)[0];
        const distance = Math.round(nearestTreasure.distance);

        // Create ore summary
        const oreTypesSummary = Array.from(oreTypes.entries())
            .sort((a, b) => b[1] - a[1]) // Sort by count
            .slice(0, 2) // Show top 2 ore types
            .map(([ore, count]) => `${count} ${ore}`)
            .join(', ');

        // Main detection message via action bar
        this.sendActionBar(player, ` §aScan Complete §8▸ §e${treasureCount} ores found §7(${oreTypesSummary})`, '§a');

        // Detailed info after a delay
        system.runTimeout(() => {
            this.sendActionBar(player, ` §bNearest: §e${nearestTreasure.oreName} §8▸ §a${distance}m away §7| §6${this.config.detectionRadius}m radius scan`, '§b');
        }, 60);

        // Additional message for rich veins
        if (treasureCount >= 5) { // Increased threshold due to larger scan area
            system.runTimeout(() => {
                this.sendActionBar(player, ' §6Rich Mining Area §8▸ §eSneak + Mine for Vein Extraction §7| §bMultiple ore deposits detected', '§6');
            }, 120);
        }
    },

    createDetectionEffects(player, treasures) {
        const playerLocation = player.location;

        treasures.forEach((treasure, index) => {
            system.runTimeout(() => {
                try {
                    // Particles from player to treasure
                    this.createTreasureBeam(player.dimension, playerLocation, treasure.location);

                    // Particles at treasure location
                    player.dimension.spawnParticle('myw:mythril_particle', {
                        x: treasure.location.x + 0.5,
                        y: treasure.location.y + 0.5,
                        z: treasure.location.z + 0.5
                    });

                } catch (error) {
                    // Error with particles, continue
                }
            }, index * 5);
        });

        // Effect on player
        this.createDetectionAura(player);
    },

    createTreasureBeam(dimension, fromLocation, toLocation) {
        try {
            const steps = 8;
            for (let i = 0; i <= steps; i++) {
                const progress = i / steps;
                const beamLocation = {
                    x: fromLocation.x + (toLocation.x - fromLocation.x) * progress,
                    y: fromLocation.y + 1 + (toLocation.y - fromLocation.y) * progress,
                    z: fromLocation.z + (toLocation.z - fromLocation.z) * progress
                };

                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle_serpentine', beamLocation);
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating beam
        }
    },

    createDetectionAura(player) {
        try {
            const location = player.location;

            // Ring of particles around player
            for (let i = 0; i < 16; i++) {
                const angle = (i / 16) * Math.PI * 2;
                const radius = 2;

                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + 1,
                            z: location.z + Math.sin(angle) * radius
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 3);
            }
        } catch (error) {
            // Error creating aura
        }
    },

    startVeinMining(player, itemStack, startBlock) {
        try {
            const playerId = player.id;

            // Check cooldown
            const lastVeinMine = player.getDynamicProperty('myw:last_vein_mine') || 0;
            const currentTime = Date.now();

            if (currentTime - lastVeinMine < this.config.veinMineCooldown * 50) {
                const remainingTime = Math.ceil((this.config.veinMineCooldown * 50 - (currentTime - lastVeinMine)) / 1000);
                this.sendActionBar(player, ` Vein Miner Cooldown: ${remainingTime}s`, '§6');
                return;
            }

            // Set cooldown
            player.setDynamicProperty('myw:last_vein_mine', currentTime);

            // Show activation message
            this.sendActionBar(player, ' §6Vein Miner §7▸ §eAnalyzing...', '§6');

            // Find entire connected vein
            const veinBlocks = this.findConnectedVein(player.dimension, startBlock.location, startBlock.typeId);

            if (veinBlocks.length > 1) {
                const oreName = this.getOreName(startBlock.typeId);
                // Use action bar instead of title
                this.sendActionBar(player, `⛏ §6Vein Mining Activated §8▸ §e${veinBlocks.length} ${oreName} blocks §7| §aSmaller, Precise Extraction`, '§6');
                this.mineVeinWithDelay(player, itemStack, veinBlocks, startBlock.typeId);
            } else {
                this.sendActionBar(player, ' §7No Connected Vein §8▸ §7Single ore block §8| §eNormal mining mode', '§7');
            }

        } catch (error) {
            this.sendActionBar(player, '⚠ Vein Mining Error', '§c');
        }
    },

    findConnectedVein(dimension, startLocation, blockType) {
        const visited = new Set();
        const toVisit = [startLocation];
        const veinBlocks = [];
        const directions = [
            { x: 1, y: 0, z: 0 }, { x: -1, y: 0, z: 0 },
            { x: 0, y: 1, z: 0 }, { x: 0, y: -1, z: 0 },
            { x: 0, y: 0, z: 1 }, { x: 0, y: 0, z: -1 }
        ];

        while (toVisit.length > 0 && veinBlocks.length < this.config.maxVeinSize) {
            const currentLocation = toVisit.pop();
            const locationKey = `${currentLocation.x},${currentLocation.y},${currentLocation.z}`;

            if (visited.has(locationKey)) continue;
            visited.add(locationKey);

            try {
                const block = dimension.getBlock(currentLocation);
                if (block && block.typeId === blockType) {
                    veinBlocks.push(currentLocation);

                    // Search adjacent blocks
                    directions.forEach(dir => {
                        const adjacentLocation = {
                            x: currentLocation.x + dir.x,
                            y: currentLocation.y + dir.y,
                            z: currentLocation.z + dir.z
                        };
                        const adjacentKey = `${adjacentLocation.x},${adjacentLocation.y},${adjacentLocation.z}`;

                        if (!visited.has(adjacentKey)) {
                            toVisit.push(adjacentLocation);
                        }
                    });
                }
            } catch (error) {
                continue;
            }
        }

        return veinBlocks;
    },

    mineVeinWithDelay(player, itemStack, veinBlocks, blockType) {
        let index = 0;
        const dimension = player.dimension;

        const miningInterval = system.runInterval(() => {
            if (index >= veinBlocks.length) {
                system.clearRun(miningInterval);
                this.finishVeinMining(player, veinBlocks.length, blockType);
                return;
            }

            // Mine several blocks per tick for speed
            const batchSize = Math.min(3, veinBlocks.length - index);
            for (let i = 0; i < batchSize; i++) {
                if (index + i < veinBlocks.length) {
                    // Pass player reference for mythril drops
                    this.mineVeinBlockWithPlayer(dimension, veinBlocks[index + i], blockType, player);
                }
            }

            index += batchSize;

            // Progress update via action bar
            const progress = Math.round((index / veinBlocks.length) * 100);
            const progressBar = this.createProgressBar(progress);
            this.sendActionBar(player, `⛏ §6Extracting Vein §8▸ §e${progress}% ${progressBar}`, '§6');

        }, 3);
    },

    mineVeinBlockWithPlayer(dimension, location, blockType, player) {
        try {
            const block = dimension.getBlock(location);
            if (!block || block.typeId !== blockType) return;

            // Effects before mining
            this.createVeinMiningEffects(dimension, location, blockType);

            // IMPORTANT: Attempt mythril drops for each vein block with correct player reference
            this.attemptMythrilDrops(player, location);

            // Use setblock command to properly mine and drop items
            dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);

        } catch (error) {
            // If command fails, try manual mining (won't drop items but won't crash)
            try {
                const block = dimension.getBlock(location);
                if (block) {
                    block.setType('minecraft:air');
                }
            } catch (fallbackError) {
                // Silent continue
            }
        }
    },

    createProgressBar(percentage) {
        const totalBars = 10;
        const filledBars = Math.floor((percentage / 100) * totalBars);
        const emptyBars = totalBars - filledBars;

        return '§a' + '█'.repeat(filledBars) + '§8' + '█'.repeat(emptyBars);
    },

    mineVeinBlock(dimension, location, blockType) {
        try {
            const block = dimension.getBlock(location);
            if (!block || block.typeId !== blockType) return;

            // Effects before mining
            this.createVeinMiningEffects(dimension, location, blockType);

            // IMPORTANT: Attempt mythril drops for each vein block
            // Find the player for drops (get first player as fallback)
            const players = world.getAllPlayers();
            if (players.length > 0) {
                this.attemptMythrilDrops(players[0], location);
            }

            // Use setblock command to properly mine and drop items
            dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);

        } catch (error) {
            // If command fails, try manual mining (won't drop items but won't crash)
            try {
                const block = dimension.getBlock(location);
                if (block) {
                    block.setType('minecraft:air');
                }
            } catch (fallbackError) {
                // Silent continue
            }
        }
    },

    createVeinMiningEffects(dimension, location, blockType) {
        try {
            // Specific particles based on ore type
            let particleType = 'myw:mythril_particle';

            if (blockType.includes('diamond')) {
                particleType = 'myw:mythril_particle_serpentine';
            } else if (blockType.includes('gold') || blockType.includes('iron')) {
                particleType = 'myw:mythril_particle_minimalist';
            }

            // Particles from mined block
            for (let i = 0; i < 2; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle(particleType, {
                            x: location.x + 0.5 + (Math.random() - 0.5) * 0.8,
                            y: location.y + 0.5 + (Math.random() - 0.5) * 0.8,
                            z: location.z + 0.5 + (Math.random() - 0.5) * 0.8
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

        } catch (error) {
            // Error creating effects
        }
    },

    finishVeinMining(player, blocksMinedCount, blockType) {
        try {
            const oreName = this.getOreName(blockType);

            // Clear progress bar and show completion
            this.sendActionBar(player, ` §aVein Complete §8▸ §e${blocksMinedCount} ${oreName} §7| §6Precise Extraction Successful`, '§a');

            // Additional completion stats after delay
            system.runTimeout(() => {
                this.sendActionBar(player, ` §bMythril Enhanced §8▸ §a+${blocksMinedCount} blocks §7| §6Reduced vein size for balance`, '§b');
            }, 80);

            // Completion effects
            this.createVeinCompleteEffects(player);

            // Success sound
            this.playPickaxeSound(player, 'success');

        } catch (error) {
            this.sendActionBar(player, '⚠ §cError displaying results §8▸ §7Vein mining completed', '§c');
        }
    },

    createVeinCompleteEffects(player) {
        try {
            const location = player.location;

            // Celebratory particle explosion
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    try {
                        const angle = Math.random() * Math.PI * 2;
                        const height = Math.random() * 2;
                        const radius = 1 + Math.random() * 2;

                        player.dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + 1 + height,
                            z: location.z + Math.sin(angle) * radius
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

        } catch (error) {
            // Error creating completion effects
        }
    },

    createMiningEffects(player, location, blockType) {
        try {
            // ALWAYS attempt mythril drops for every block mined with the pickaxe
            this.attemptMythrilDrops(player, location);

            // Enhanced visual effects
            if (this.isValuableOre(blockType)) {
                // More particles for valuable ores
                for (let i = 0; i < 3; i++) {
                    system.runTimeout(() => {
                        try {
                            player.dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                x: location.x + 0.5 + (Math.random() - 0.5) * 1.2,
                                y: location.y + 0.5 + (Math.random() - 0.5) * 1.2,
                                z: location.z + 0.5 + (Math.random() - 0.5) * 1.2
                            });
                        } catch (error) {
                            // Error with particles
                        }
                    }, i * 3);
                }

                // Enhanced message for valuable ore mining
                const oreName = this.getOreName(blockType);
                this.sendActionBar(player, ` §b${oreName} Mined §8▸ §eMythril Enhanced §7| §aWatch for bonus drops`, '§b');
            } else if (blockType !== 'entity_hit') {
                // Regular block mining - still has mythril drop chance
                this.sendActionBar(player, ` §7Block Mined §8▸ §eMythril Enhanced §7| §bChance for mythril materials`, '§7');
            }
        } catch (error) {
            // Error with effects
        }
    },

    // Fixed mythril drops function with higher chances and better spawning
    attemptMythrilDrops(player, location) {
        try {
            const dimension = player.dimension;
            const dropLocation = {
                x: Math.floor(location.x) + 0.5,
                y: Math.floor(location.y) + 0.1,
                z: Math.floor(location.z) + 0.5
            };

            let droppedSomething = false;

            // 35% chance for mythril dust
            if (Math.random() < this.config.dustDropChance) {
                try {
                    // Use a more reliable spawn method
                    const dustSpawn = dimension.spawnItem(new ItemStack('myw:mythril_dust', 1), dropLocation);
                    droppedSomething = true;

                    // Extra sparkle particles for dust
                    for (let i = 0; i < 5; i++) {
                        system.runTimeout(() => {
                            try {
                                dimension.spawnParticle('myw:mythril_particle', {
                                    x: dropLocation.x + (Math.random() - 0.5) * 0.8,
                                    y: dropLocation.y + Math.random() * 0.5,
                                    z: dropLocation.z + (Math.random() - 0.5) * 0.8
                                });
                            } catch (error) {
                                // Error with particles
                            }
                        }, i * 2);
                    }
                } catch (error) {
                    // Fallback to command if spawnItem fails
                    try {
                        dimension.runCommand(`summon item ${dropLocation.x} ${dropLocation.y} ${dropLocation.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"myw:mythril_dust","Count":1}}`);
                        droppedSomething = true;
                    } catch (cmdError) {
                        // Try simple setblock method as last resort
                        try {
                            dimension.runCommand(`give "${player.name}" myw:mythril_dust 1`);
                            droppedSomething = true;
                        } catch (giveError) {
                            // All methods failed - log for debugging
                            world.sendMessage('§cDebug: Failed to spawn mythril dust');
                        }
                    }
                }
            }

            // 20% chance for mythril nugget
            if (Math.random() < this.config.nuggetDropChance) {
                try {
                    // Use a more reliable spawn method
                    const nuggetSpawn = dimension.spawnItem(new ItemStack('myw:mythril_nugget', 1), dropLocation);
                    droppedSomething = true;

                    // Special golden particles for nuggets
                    for (let i = 0; i < 8; i++) {
                        system.runTimeout(() => {
                            try {
                                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                                    x: dropLocation.x + (Math.random() - 0.5) * 1.0,
                                    y: dropLocation.y + Math.random() * 0.6,
                                    z: dropLocation.z + (Math.random() - 0.5) * 1.0
                                });
                            } catch (error) {
                                // Error with particles
                            }
                        }, i * 3);
                    }

                    // Special message for nugget drop
                    system.runTimeout(() => {
                        this.sendActionBar(player, ` §6Mythril Nugget! §8▸ §eRare drop obtained §7| §b20% chance success`, '§6');
                    }, 10);
                } catch (error) {
                    // Fallback to command if spawnItem fails
                    try {
                        dimension.runCommand(`summon item ${dropLocation.x} ${dropLocation.y} ${dropLocation.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"myw:mythril_nugget","Count":1}}`);
                        droppedSomething = true;
                    } catch (cmdError) {
                        // Try simple give method as last resort
                        try {
                            dimension.runCommand(`give "${player.name}" myw:mythril_nugget 1`);
                            droppedSomething = true;
                        } catch (giveError) {
                            // All methods failed - log for debugging
                            world.sendMessage('§cDebug: Failed to spawn mythril nugget');
                        }
                    }
                }
            }

            // Show drop success message
            if (droppedSomething) {
                system.runTimeout(() => {
                    this.sendActionBar(player, ` §eMythril Materials Found! §8▸ §aCheck around your feet §7| §bKeep mining`, '§e');
                }, 5);
            }

        } catch (error) {
            world.sendMessage('§cDebug: Error in attemptMythrilDrops - ' + error.message);
        }
    },

    isValuableOre(blockType) {
        const valuableOres = [
            'minecraft:diamond_ore',
            'minecraft:deepslate_diamond_ore',
            'minecraft:gold_ore',
            'minecraft:deepslate_gold_ore',
            'minecraft:iron_ore',
            'minecraft:deepslate_iron_ore',
            'minecraft:emerald_ore',
            'minecraft:deepslate_emerald_ore',
            'minecraft:lapis_ore',
            'minecraft:deepslate_lapis_ore',
            'minecraft:redstone_ore',
            'minecraft:deepslate_redstone_ore',
            'minecraft:copper_ore',
            'minecraft:deepslate_copper_ore',
            'minecraft:ancient_debris'
        ];

        return valuableOres.includes(blockType);
    },

    getOreName(blockType) {
        const names = {
            'minecraft:diamond_ore': 'Diamond',
            'minecraft:deepslate_diamond_ore': 'Diamond',
            'minecraft:gold_ore': 'Gold',
            'minecraft:deepslate_gold_ore': 'Gold',
            'minecraft:iron_ore': 'Iron',
            'minecraft:deepslate_iron_ore': 'Iron',
            'minecraft:emerald_ore': 'Emerald',
            'minecraft:deepslate_emerald_ore': 'Emerald',
            'minecraft:lapis_ore': 'Lapis Lazuli',
            'minecraft:deepslate_lapis_ore': 'Lapis Lazuli',
            'minecraft:redstone_ore': 'Redstone',
            'minecraft:deepslate_redstone_ore': 'Redstone',
            'minecraft:copper_ore': 'Copper',
            'minecraft:deepslate_copper_ore': 'Copper',
            'minecraft:ancient_debris': 'Ancient Debris'
        };

        return names[blockType] || 'Ore';
    },

    playPickaxeSound(player, type) {
        try {
            let soundId = 'dig.stone';

            switch (type) {
                case 'detection':
                    soundId = 'note.pling';
                    break;
                case 'vein_start':
                    soundId = 'random.anvil_use';
                    break;
                case 'success':
                    soundId = 'random.levelup';
                    break;
                case 'mining':
                    soundId = 'dig.stone';
                    break;
            }

            player.dimension.runCommandAsync(`playsound ${soundId} @a ~ ~ ~ 0.4 1.0`);
        } catch (error) {
            // Error with sound
        }
    }
};

// Register pickaxe component
export function registerMythrilPickaxe(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_pickaxe', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            PickaxeSystem.handlePickaxeUse(source, itemStack, useDuration);
        },

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

        onHitEntity(eventData) {
            // Pickaxe can be used as basic weapon
            const { source } = eventData;
            if (source) {
                PickaxeSystem.createMiningEffects(source, source.location, 'entity_hit');
                PickaxeSystem.sendActionBar(source, ' §bMythril Strike §8▸ §7Combat Mode', '§b');
            }
        }
    });
}

// Initialize pickaxe systems
export function initializePickaxeSystems() {
    // Passive ambient effects when holding pickaxe
    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                const equippableComp = player.getComponent('minecraft:equippable');
                const mainhandItem = equippableComp?.getEquipment(EquipmentSlot.Mainhand);

                if (mainhandItem?.typeId === 'myw:mythril_pickaxe') {
                    // Create subtle particles if there are ores nearby
                    if (Math.random() > 0.95) { // 5% chance per tick
                        PickaxeSystem.createDetectionAmbientEffects(player);
                    }
                }
            });
        } catch (error) {
            // Error in passive detection
        }
    }, 20);

    // Show initialization message with style
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            PickaxeSystem.sendActionBar(player, ' §bMythril Pickaxe System §8▸ §aOnline §7| §eAdvanced Scanner & Balanced Vein Mining', '§b');
        });
    }, 20);
}

// Create subtle ambient effects
PickaxeSystem.createDetectionAmbientEffects = function (player) {
    try {
        if (Math.random() > 0.3) return; // Reduce frequency

        const location = player.location;
        player.dimension.spawnParticle('myw:mythril_particle_minimalist', {
            x: location.x + (Math.random() - 0.5) * 2,
            y: location.y + Math.random() * 0.5,
            z: location.z + (Math.random() - 0.5) * 2
        });
    } catch (error) {
        // Error with ambient effects
    }
};