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

export const HoeSystem = {

    config: {
        fertilizeCooldown: 100, // 5 seconds
        harvestCooldown: 120, // 6 seconds
        cropRadius: 4, // 4x4 area for mass operations
        growthBoostChance: 0.60, // 60% chance to boost crop growth
        bonusHarvestChance: 0.35, // 35% chance for bonus harvest
        dustDropChance: 0.20, // 20% chance for dust from farming
        nuggetDropChance: 0.10, // 10% chance for nuggets from farming
    },

    farmingModes: [
        {
            name: 'Crop Accelerator',
            description: 'Instantly grows nearby crops',
            icon: '§a⚡',
            color: '§a'
        },
        {
            name: 'Mass Harvester',
            description: 'Harvests and replants large areas',
            icon: '§6🌾',
            color: '§6'
        },
        {
            name: 'Soil Enricher',
            description: 'Creates super-fertile farmland',
            icon: '§2🌱',
            color: '§2'
        },
        {
            name: 'Nature Communion',
            description: 'Communicates with plant life',
            icon: '§d🍃',
            color: '§d'
        }
    ],

    cropTypes: {
        'minecraft:wheat': {
            seed: 'minecraft:wheat_seeds',
            stages: 7,
            name: 'Wheat',
            bonusDrops: ['myw:mythril_dust']
        },
        'minecraft:carrots': {
            seed: 'minecraft:carrot',
            stages: 7,
            name: 'Carrots',
            bonusDrops: ['myw:mythril_dust']
        },
        'minecraft:potatoes': {
            seed: 'minecraft:potato',
            stages: 7,
            name: 'Potatoes',
            bonusDrops: ['myw:mythril_nugget']
        },
        'minecraft:beetroots': {
            seed: 'minecraft:beetroot_seeds',
            stages: 3,
            name: 'Beetroots',
            bonusDrops: ['myw:mythril_dust']
        },
        'minecraft:pumpkin_stem': {
            seed: 'minecraft:pumpkin_seeds',
            stages: 7,
            name: 'Pumpkins',
            bonusDrops: ['myw:mythril_nugget']
        },
        'minecraft:melon_stem': {
            seed: 'minecraft:melon_seeds',
            stages: 7,
            name: 'Melons',
            bonusDrops: ['myw:mythril_nugget']
        }
    },

    // Utility function for sending styled action bar messages
    sendActionBar(player, message, color = '§2') {
        try {
            player.onScreenDisplay.setActionBar(`${color}${message}`);
        } catch (error) {
            try {
                player.onScreenDisplay.setActionBar(message);
            } catch (e) {
                // Silent fail
            }
        }
    },

    handleHoeUse(player, itemStack, useDuration) {
        try {
            if (player.isSneaking) {
                // Cycle farming modes
                this.cycleFarmingMode(player);
                return;
            } else {
                // Show current mode info
                const currentMode = player.getDynamicProperty('myw:farming_mode') || 0;
                const mode = this.farmingModes[currentMode];
                this.sendActionBar(player, `${mode.icon} Mythril Agricultural Hoe §8▸ §7${mode.description}`, mode.color);
                return;
            }
        } catch (error) {
            this.sendActionBar(player, '⚠ Hoe Error Occurred', '§c');
        }
    },

    handleBlockHoeing(player, itemStack, targetBlock, blockFace) {
        try {
            const currentMode = player.getDynamicProperty('myw:farming_mode') || 0;
            const blockType = targetBlock.typeId;
            const blockLocation = targetBlock.location;

            // Check if it's farmland or a crop
            if (this.isFarmland(blockType) || this.isCrop(blockType)) {
                this.executeSpecialFarmingAction(player, blockLocation, currentMode);
                return;
            }

            // Normal hoeing with mythril enhancement
            this.performEnhancedHoeing(player, blockLocation, blockType);

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

    cycleFarmingMode(player) {
        try {
            const currentMode = player.getDynamicProperty('myw:farming_mode') || 0;
            const newMode = (currentMode + 1) % this.farmingModes.length;
            player.setDynamicProperty('myw:farming_mode', newMode);

            const mode = this.farmingModes[newMode];
            this.sendActionBar(player, `${mode.icon} Mode: ${mode.name} §8▸ §7${mode.description}`, mode.color);

            // Show mode-specific instructions
            system.runTimeout(() => {
                switch (newMode) {
                    case 0:
                        this.sendActionBar(player, '§a⚡ Crop Accelerator §8▸ §7Use on crops to instantly grow them', '§a');
                        break;
                    case 1:
                        this.sendActionBar(player, '§6🌾 Mass Harvester §8▸ §7Use on mature crops to harvest area', '§6');
                        break;
                    case 2:
                        this.sendActionBar(player, '§2🌱 Soil Enricher §8▸ §7Use on dirt/grass to create super farmland', '§2');
                        break;
                    case 3:
                        this.sendActionBar(player, '§d🍃 Nature Communion §8▸ §7Use anywhere to sense plant health', '§d');
                        break;
                }
            }, 40);

            // Visual effect for mode change
            this.createModeChangeEffects(player, mode);

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

    executeSpecialFarmingAction(player, centerLocation, mode) {
        try {
            switch (mode) {
                case 0: // Crop Accelerator
                    this.activateCropAccelerator(player, centerLocation);
                    break;
                case 1: // Mass Harvester
                    this.activateMassHarvester(player, centerLocation);
                    break;
                case 2: // Soil Enricher
                    this.activateSoilEnricher(player, centerLocation);
                    break;
                case 3: // Nature Communion
                    this.activateNatureCommunion(player, centerLocation);
                    break;
            }
        } catch (error) {
            this.sendActionBar(player, '⚠ Special Action Error', '§c');
        }
    },

    activateCropAccelerator(player, centerLocation) {
        try {
            // Check cooldown
            const lastAccelerate = player.getDynamicProperty('myw:last_accelerate') || 0;
            const currentTime = Date.now();

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

            player.setDynamicProperty('myw:last_accelerate', currentTime);

            const dimension = player.dimension;
            const radius = this.config.cropRadius;
            let cropsAccelerated = 0;

            this.sendActionBar(player, '§a⚡ Crop Acceleration §8▸ §eCharging mythril energy...', '§a');

            // Find and grow crops in radius
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const checkLocation = {
                        x: Math.floor(centerLocation.x) + x,
                        y: Math.floor(centerLocation.y),
                        z: Math.floor(centerLocation.z) + z
                    };

                    try {
                        const block = dimension.getBlock(checkLocation);
                        if (block && this.isCrop(block.typeId)) {
                            const cropInfo = this.cropTypes[block.typeId];
                            if (cropInfo && Math.random() < this.config.growthBoostChance) {
                                // Accelerate growth
                                this.accelerateCropGrowth(dimension, checkLocation, block.typeId, cropInfo);
                                cropsAccelerated++;
                            }
                        }
                    } catch (blockError) {
                        continue;
                    }
                }
            }

            // Results
            system.runTimeout(() => {
                if (cropsAccelerated > 0) {
                    this.sendActionBar(player, `§a⚡ Acceleration Complete §8▸ §e${cropsAccelerated} crops accelerated §7| §2Mythril-enhanced growth`, '§a');
                    this.createAccelerationEffects(player, centerLocation, cropsAccelerated);
                    this.attemptMythrilDrops(player, centerLocation, 'accelerate');
                } else {
                    this.sendActionBar(player, '§7⚡ No Crops Found §8▸ §7No suitable crops in range §7| §eTry near growing crops', '§7');
                }
            }, 30);

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

    activateMassHarvester(player, centerLocation) {
        try {
            // Check cooldown
            const lastHarvest = player.getDynamicProperty('myw:last_harvest') || 0;
            const currentTime = Date.now();

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

            player.setDynamicProperty('myw:last_harvest', currentTime);

            const dimension = player.dimension;
            const radius = this.config.cropRadius;
            let cropsHarvested = 0;
            const harvestedTypes = new Set();

            this.sendActionBar(player, '§6🌾 Mass Harvest §8▸ §eAnalyzing crop maturity...', '§6');

            // Find and harvest mature crops
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const checkLocation = {
                        x: Math.floor(centerLocation.x) + x,
                        y: Math.floor(centerLocation.y),
                        z: Math.floor(centerLocation.z) + z
                    };

                    try {
                        const block = dimension.getBlock(checkLocation);
                        if (block && this.isMatureCrop(block)) {
                            const cropType = block.typeId;
                            const cropInfo = this.cropTypes[cropType];

                            if (cropInfo) {
                                // Harvest and replant
                                this.harvestAndReplant(dimension, checkLocation, cropType, cropInfo);
                                cropsHarvested++;
                                harvestedTypes.add(cropInfo.name);
                            }
                        }
                    } catch (blockError) {
                        continue;
                    }
                }
            }

            // Results
            system.runTimeout(() => {
                if (cropsHarvested > 0) {
                    const cropsList = Array.from(harvestedTypes).join(', ');
                    this.sendActionBar(player, `§6🌾 Harvest Complete §8▸ §e${cropsHarvested} crops §7(${cropsList}) §7| §aAuto-replanted`, '§6');
                    this.createHarvestEffects(player, centerLocation, cropsHarvested);
                    this.attemptMythrilDrops(player, centerLocation, 'harvest');
                } else {
                    this.sendActionBar(player, '§7🌾 No Mature Crops §8▸ §7No ready crops in range §7| §eWait for crops to mature', '§7');
                }
            }, 30);

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

    activateSoilEnricher(player, centerLocation) {
        try {
            const dimension = player.dimension;
            const radius = this.config.cropRadius;
            let soilEnriched = 0;

            this.sendActionBar(player, '§2🌱 Soil Enrichment §8▸ §eInfusing mythril nutrients...', '§2');

            // Convert dirt/grass to super farmland
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const checkLocation = {
                        x: Math.floor(centerLocation.x) + x,
                        y: Math.floor(centerLocation.y),
                        z: Math.floor(centerLocation.z) + z
                    };

                    try {
                        const block = dimension.getBlock(checkLocation);
                        if (block && this.canEnrichSoil(block.typeId)) {
                            // Create super farmland
                            dimension.runCommand(`setblock ${checkLocation.x} ${checkLocation.y} ${checkLocation.z} farmland 7`);

                            // Add water source nearby if needed
                            this.addWaterSourceIfNeeded(dimension, checkLocation);

                            soilEnriched++;
                            this.createEnrichmentEffects(dimension, checkLocation);
                        }
                    } catch (blockError) {
                        continue;
                    }
                }
            }

            // Results
            system.runTimeout(() => {
                if (soilEnriched > 0) {
                    this.sendActionBar(player, `§2🌱 Enrichment Complete §8▸ §e${soilEnriched} blocks enriched §7| §aSuper-fertile farmland created`, '§2');
                    this.attemptMythrilDrops(player, centerLocation, 'enrich');
                } else {
                    this.sendActionBar(player, '§7🌱 No Suitable Soil §8▸ §7No dirt/grass blocks found §7| §eUse on natural terrain', '§7');
                }
            }, 20);

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

    activateNatureCommunion(player, centerLocation) {
        try {
            const dimension = player.dimension;
            const radius = this.config.cropRadius * 2; // Larger sensing radius
            const plantInfo = {
                crops: [],
                trees: [],
                flowers: [],
                health: 'excellent'
            };

            this.sendActionBar(player, '§d🍃 Nature Communion §8▸ §eAttuning to plant consciousness...', '§d');

            // Scan area for plant life
            for (let x = -radius; x <= radius; x++) {
                for (let y = -2; y <= 3; y++) {
                    for (let z = -radius; z <= radius; z++) {
                        const checkLocation = {
                            x: Math.floor(centerLocation.x) + x,
                            y: Math.floor(centerLocation.y) + y,
                            z: Math.floor(centerLocation.z) + z
                        };

                        try {
                            const block = dimension.getBlock(checkLocation);
                            if (block) {
                                if (this.isCrop(block.typeId)) {
                                    const cropInfo = this.cropTypes[block.typeId];
                                    if (cropInfo) {
                                        plantInfo.crops.push({
                                            type: cropInfo.name,
                                            location: checkLocation,
                                            mature: this.isMatureCrop(block)
                                        });
                                    }
                                } else if (this.isTree(block.typeId)) {
                                    plantInfo.trees.push({
                                        type: this.getTreeName(block.typeId),
                                        location: checkLocation
                                    });
                                } else if (this.isFlower(block.typeId)) {
                                    plantInfo.flowers.push({
                                        type: this.getFlowerName(block.typeId),
                                        location: checkLocation
                                    });
                                }
                            }
                        } catch (blockError) {
                            continue;
                        }
                    }
                }
            }

            // Provide detailed nature report
            system.runTimeout(() => {
                this.displayNatureReport(player, plantInfo);
                this.createCommunionEffects(player, centerLocation, plantInfo);
            }, 40);

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

    displayNatureReport(player, plantInfo) {
        const totalPlants = plantInfo.crops.length + plantInfo.trees.length + plantInfo.flowers.length;

        if (totalPlants === 0) {
            this.sendActionBar(player, '§d🍃 Nature Silent §8▸ §7No plant life detected §7| §eSeek greener areas', '§d');
            return;
        }

        // Main report
        this.sendActionBar(player, `§d🍃 Nature Speaks §8▸ §e${totalPlants} plants detected §7| §aEcosystem analysis complete`, '§d');

        // Detailed breakdown
        system.runTimeout(() => {
            if (plantInfo.crops.length > 0) {
                const matureCrops = plantInfo.crops.filter(crop => crop.mature).length;
                const cropTypes = [...new Set(plantInfo.crops.map(crop => crop.type))].join(', ');
                this.sendActionBar(player, `§a🌾 Crops: §e${plantInfo.crops.length} total §7(${matureCrops} ready) §8▸ §7${cropTypes}`, '§a');
            }
        }, 60);

        system.runTimeout(() => {
            if (plantInfo.trees.length > 0) {
                const treeTypes = [...new Set(plantInfo.trees.map(tree => tree.type))].join(', ');
                this.sendActionBar(player, `§2🌳 Trees: §e${plantInfo.trees.length} total §8▸ §7${treeTypes}`, '§2');
            }
        }, 120);

        system.runTimeout(() => {
            if (plantInfo.flowers.length > 0) {
                const flowerTypes = [...new Set(plantInfo.flowers.map(flower => flower.type))].join(', ');
                this.sendActionBar(player, `§c🌺 Flowers: §e${plantInfo.flowers.length} total §8▸ §7${flowerTypes}`, '§c');
            }
        }, 180);
    },

    performEnhancedHoeing(player, location, blockType) {
        try {
            // Enhanced mythril drops for farming
            this.attemptMythrilDrops(player, location, 'hoe');

            // Create hoeing effects
            this.createHoeingEffects(player, location, blockType);

            // Show hoeing message
            if (this.canEnrichSoil(blockType)) {
                this.sendActionBar(player, `§2🌱 Soil Prepared §8▸ §eMythril-enhanced farmland §7| §aReady for planting`, '§2');
            } else {
                this.sendActionBar(player, `§7⚡ Block Hoed §8▸ §eMythril Enhanced §7| §bChance for mythril materials`, '§7');
            }

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

    // UTILITY FUNCTIONS
    isFarmland(blockType) {
        return blockType === 'minecraft:farmland';
    },

    isCrop(blockType) {
        return Object.keys(this.cropTypes).includes(blockType);
    },

    isMatureCrop(block) {
        const blockType = block.typeId;
        const cropInfo = this.cropTypes[blockType];

        if (!cropInfo) return false;

        try {
            // Try to get block state for age
            const blockPermutation = block.permutation;
            const age = blockPermutation.getState('age') || 0;
            return age >= cropInfo.stages;
        } catch (error) {
            // If can't get age, assume mature for safety
            return true;
        }
    },

    canEnrichSoil(blockType) {
        const enrichableBlocks = [
            'minecraft:dirt',
            'minecraft:grass_block',
            'minecraft:coarse_dirt',
            'minecraft:podzol',
            'minecraft:mycelium'
        ];
        return enrichableBlocks.includes(blockType);
    },

    isTree(blockType) {
        return blockType.includes('_log') || blockType.includes('_wood');
    },

    isFlower(blockType) {
        const flowers = [
            'minecraft:poppy', 'minecraft:dandelion', 'minecraft:blue_orchid',
            'minecraft:allium', 'minecraft:azure_bluet', 'minecraft:red_tulip',
            'minecraft:orange_tulip', 'minecraft:white_tulip', 'minecraft:pink_tulip',
            'minecraft:oxeye_daisy', 'minecraft:cornflower', 'minecraft:lily_of_the_valley'
        ];
        return flowers.includes(blockType);
    },

    getTreeName(blockType) {
        if (blockType.includes('oak')) return 'Oak';
        if (blockType.includes('birch')) return 'Birch';
        if (blockType.includes('spruce')) return 'Spruce';
        if (blockType.includes('jungle')) return 'Jungle';
        if (blockType.includes('acacia')) return 'Acacia';
        if (blockType.includes('dark_oak')) return 'Dark Oak';
        return 'Tree';
    },

    getFlowerName(blockType) {
        return blockType.replace('minecraft:', '').replace('_', ' ');
    },

    accelerateCropGrowth(dimension, location, cropType, cropInfo) {
        try {
            // Set crop to maximum age
            dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} ${cropType} [age=${cropInfo.stages}]`);
        } catch (error) {
            // Fallback: try without age specification
            try {
                dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} ${cropType}`);
            } catch (fallbackError) {
                // Silent continue
            }
        }
    },

    harvestAndReplant(dimension, location, cropType, cropInfo) {
        try {
            // Harvest crop (destroy and drop items)
            dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);

            // Replant immediately
            system.runTimeout(() => {
                dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} ${cropType} [age=0]`);
            }, 5);

            // Bonus drops chance
            if (Math.random() < this.config.bonusHarvestChance && cropInfo.bonusDrops.length > 0) {
                const bonusItem = cropInfo.bonusDrops[Math.floor(Math.random() * cropInfo.bonusDrops.length)];
                this.spawnMythrilItem(dimension, location, bonusItem);
            }

        } catch (error) {
            // Error with harvesting
        }
    },

    addWaterSourceIfNeeded(dimension, centerLocation) {
        // Check if there's water within 4 blocks
        let hasWater = false;

        for (let x = -4; x <= 4 && !hasWater; x++) {
            for (let z = -4; z <= 4 && !hasWater; z++) {
                try {
                    const checkLocation = {
                        x: centerLocation.x + x,
                        y: centerLocation.y,
                        z: centerLocation.z + z
                    };
                    const block = dimension.getBlock(checkLocation);
                    if (block && block.typeId === 'minecraft:water') {
                        hasWater = true;
                    }
                } catch (error) {
                    continue;
                }
            }
        }

        // Add water source if none found
        if (!hasWater) {
            try {
                const waterLocation = {
                    x: centerLocation.x,
                    y: centerLocation.y,
                    z: centerLocation.z + 2
                };
                dimension.runCommand(`setblock ${waterLocation.x} ${waterLocation.y} ${waterLocation.z} water`);
            } catch (error) {
                // Error adding water
            }
        }
    },

    attemptMythrilDrops(player, location, action) {
        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;

            // Adjust drop chances based on action
            let dustChance = this.config.dustDropChance;
            let nuggetChance = this.config.nuggetDropChance;

            if (action === 'harvest' || action === 'accelerate') {
                dustChance *= 1.5; // Bonus for farming actions
                nuggetChance *= 1.3;
            }

            // Mythril dust drops
            if (Math.random() < dustChance) {
                this.spawnMythrilItem(dimension, dropLocation, 'myw:mythril_dust');
                droppedSomething = true;

                // Farming particles
                for (let i = 0; i < 4; i++) {
                    system.runTimeout(() => {
                        try {
                            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                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);
                }
            }

            // Mythril nugget drops
            if (Math.random() < nuggetChance) {
                this.spawnMythrilItem(dimension, dropLocation, 'myw:mythril_nugget');
                droppedSomething = true;

                // Special agricultural particles for nuggets
                for (let i = 0; i < 6; i++) {
                    system.runTimeout(() => {
                        try {
                            dimension.spawnParticle('myw:mythril_particle', {
                                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);
                }

                system.runTimeout(() => {
                    this.sendActionBar(player, `🌟 Mythril Nugget! §8▸ §eAgricultural blessing received §7| §b${Math.round(nuggetChance * 100)}% chance`, '§6');
                }, 10);
            }

            if (droppedSomething) {
                system.runTimeout(() => {
                    this.sendActionBar(player, `💎 Agricultural Bounty! §8▸ §aMythril rewards from farming §7| §2Keep cultivating`, '§e');
                }, 5);
            }

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

    spawnMythrilItem(dimension, location, itemId) {
        try {
            const itemSpawn = dimension.spawnItem(new ItemStack(itemId, 1), location);
        } catch (error) {
            try {
                dimension.runCommand(`summon item ${location.x} ${location.y} ${location.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"${itemId}","Count":1}}`);
            } catch (cmdError) {
                try {
                    const players = world.getAllPlayers();
                    if (players.length > 0) {
                        dimension.runCommand(`give "${players[0].name}" ${itemId} 1`);
                    }
                } catch (giveError) {
                    world.sendMessage(`§cDebug: Failed to spawn ${itemId}`);
                }
            }
        }
    },

    // VISUAL EFFECTS
    createModeChangeEffects(player, mode) {
        try {
            const location = player.location;
            const particleType = 'myw:mythril_particle_minimalist';

            // Mode change particles
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const radius = 1.5;

                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle(particleType, {
                            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 mode change effects
        }
    },

    createAccelerationEffects(player, location, cropsCount) {
        try {
            // Growth burst particles
            for (let i = 0; i < cropsCount * 2; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + (Math.random() - 0.5) * 8,
                            y: location.y + Math.random() * 2,
                            z: location.z + (Math.random() - 0.5) * 8
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating acceleration effects
        }
    },

    createHarvestEffects(player, location, cropsCount) {
        try {
            // Harvest celebration particles
            for (let i = 0; i < cropsCount * 3; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + (Math.random() - 0.5) * 8,
                            y: location.y + Math.random() * 3,
                            z: location.z + (Math.random() - 0.5) * 8
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 1);
            }
        } catch (error) {
            // Error creating harvest effects
        }
    },

    createEnrichmentEffects(dimension, location) {
        try {
            // Soil enrichment particles
            for (let i = 0; i < 5; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: location.x + 0.5 + (Math.random() - 0.5) * 1.0,
                            y: location.y + 0.1 + Math.random() * 0.5,
                            z: location.z + 0.5 + (Math.random() - 0.5) * 1.0
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating enrichment effects
        }
    },

    createCommunionEffects(player, location, plantInfo) {
        try {
            const totalPlants = plantInfo.crops.length + plantInfo.trees.length + plantInfo.flowers.length;
            const particleCount = Math.min(totalPlants, 20);

            // Nature communion aura
            for (let i = 0; i < particleCount; i++) {
                const angle = Math.random() * Math.PI * 2;
                const radius = Math.random() * 4;

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

    createHoeingEffects(player, location, blockType) {
        try {
            // Standard hoeing particles
            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.0,
                            y: location.y + 0.5 + (Math.random() - 0.5) * 1.0,
                            z: location.z + 0.5 + (Math.random() - 0.5) * 1.0
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 1);
            }
        } catch (error) {
            // Error creating hoeing effects
        }
    }
};

// Register hoe component
export function registerMythrilHoe(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_hoe', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            HoeSystem.handleHoeUse(source, itemStack, useDuration);
        },

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

        onHitEntity(eventData) {
            const { source, hitEntity } = eventData;
            if (source) {
                HoeSystem.sendActionBar(source, '⚔ Agricultural Warrior - Combat with farming knowledge', '§2');
                HoeSystem.createHoeingEffects(source, source.location, 'entity_hit');
            }
        }
    });
}

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

                if (mainhandItem?.typeId === 'myw:mythril_hoe') {
                    // Create subtle agricultural ambient effects
                    if (Math.random() > 0.97) { // 3% chance per tick
                        HoeSystem.createAgriculturalAmbientEffects(player);
                    }

                    // Show mode status occasionally
                    if (Math.random() > 0.995) { // 0.5% chance per tick
                        const currentMode = player.getDynamicProperty('myw:farming_mode') || 0;
                        const mode = HoeSystem.farmingModes[currentMode];

                        const lastAction = Math.max(
                            player.getDynamicProperty('myw:last_accelerate') || 0,
                            player.getDynamicProperty('myw:last_harvest') || 0
                        );

                        const cooldownTime = Math.max(0, Math.ceil((HoeSystem.config.fertilizeCooldown * 50 - (Date.now() - lastAction)) / 1000));

                        if (cooldownTime > 0) {
                            HoeSystem.sendActionBar(player, `⏱ ${mode.name} Ready In - ${cooldownTime}s | Agricultural systems recharging`, '§8');
                        } else {
                            HoeSystem.sendActionBar(player, `${mode.icon} ${mode.name} Ready - ${mode.description} | Mythril agriculture available`, mode.color);
                        }
                    }
                }
            });
        } catch (error) {
            // Error in passive detection
        }
    }, 20);

    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            HoeSystem.sendActionBar(player, 'Mythril Agricultural Hoe - Online | Advanced Farming & Plant Communion', '§2');
        });
    }, 100);

    world.sendMessage('[OK] Mythril Agricultural Hoe System initialized');
}

// Agricultural ambient effects
HoeSystem.createAgriculturalAmbientEffects = function (player) {
    try {
        if (Math.random() > 0.4) return; // Reduce frequency

        const location = player.location;

        // Subtle agricultural particles
        const particleType = 'myw:mythril_particle_minimalist';

        player.dimension.spawnParticle(particleType, {
            x: location.x + (Math.random() - 0.5) * 3,
            y: location.y + Math.random() * 1.5,
            z: location.z + (Math.random() - 0.5) * 3
        });
    } catch (error) {
        // Error with ambient effects
    }
};