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

export const AxeSystem = {

    config: {
        forestScanRadius: 8,
        woodEssenceRadius: 6,
        essenceCollectionCooldown: 120, // ticks (6 seconds)
        mythrilDropChance: 0.30, // 30% chance for mythril drops from wood
        dustDropChance: 0.25, // 25% chance for dust
        nuggetDropChance: 0.15 // 15% chance for nuggets
    },

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

    handleAxeUse(player, itemStack, useDuration) {
        try {
            if (player.isSneaking) {
                // Primary ability: Silverweb Essence Extraction
                this.activateSilverwebEssenceExtraction(player);
                return;
            } else {
                // Show axe info when used without sneaking
                this.sendActionBar(player, '§9Mythril Cleaver §8▸ §7Sneak + Use to extract silverweb essence §7| §9Harvest wood for mythril crystals', '§9');
                return;
            }
        } catch (error) {
            this.sendActionBar(player, '§cBlade Malfunction Detected', '§9');
        }
    },

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

            // Check if it's wood-related block
            if (this.isWoodBlock(blockType)) {
                // Arcane wood harvesting with essence absorption
                this.performArcaneHarvest(player, targetBlock);
                return;
            }

            // Regular chopping effects for any block
            this.createChoppingEffects(player, targetBlock.location, blockType);

        } catch (error) {
            this.sendActionBar(player, '§cHarvest Protocol Error', '§9');
        }
    },

    // PRIMARY ABILITY: Silverweb Essence Extraction (Sneak + Use)
    activateSilverwebEssenceExtraction(player) {
        try {
            // Check cooldown
            const lastEssence = player.getDynamicProperty('myw:last_essence') || 0;
            const currentTime = Date.now();

            if (currentTime - lastEssence < this.config.essenceCollectionCooldown * 50) {
                const remainingTime = Math.ceil((this.config.essenceCollectionCooldown * 50 - (currentTime - lastEssence)) / 1000);
                this.sendActionBar(player, `§9Silverweb Protocol Cooldown §8▸ §e${remainingTime}s remaining`, '§9');
                return;
            }

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

            this.sendActionBar(player, '§9Silverweb Essence Extraction §8▸ §aChanneling arcane forest energies...', '§9');
            this.collectSilverwebEssence(player);

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

    collectSilverwebEssence(player) {
        try {
            const playerLocation = player.location;
            const dimension = player.dimension;
            const radius = this.config.woodEssenceRadius;
            const woodBlocks = [];
            const leafBlocks = [];

            // Scan for wood and leaves
            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) {
                                if (this.isWoodBlock(block.typeId)) {
                                    const distance = Math.sqrt(x * x + y * y + z * z);
                                    woodBlocks.push({ location: checkLocation, distance, type: block.typeId });
                                } else if (this.isLeafBlock(block.typeId)) {
                                    const distance = Math.sqrt(x * x + y * y + z * z);
                                    leafBlocks.push({ location: checkLocation, distance, type: block.typeId });
                                }
                            }
                        } catch (blockError) {
                            continue;
                        }
                    }
                }
            }

            const totalNature = woodBlocks.length + leafBlocks.length;

            system.runTimeout(() => {
                if (totalNature > 0) {
                    this.processSilverwebExtraction(player, woodBlocks, leafBlocks);
                } else {
                    this.sendActionBar(player, '§9No Silverweb Sources Detected §8▸ §7Locate ancient trees for extraction', '§9');
                }
            }, 30);

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

    processSilverwebExtraction(player, woodBlocks, leafBlocks) {
        const totalBlocks = woodBlocks.length + leafBlocks.length;
        const essenceGained = Math.min(totalBlocks, 20); // Cap at 20 essence

        // Give mythril items based on essence collected
        this.grantSilverwebRewards(player, essenceGained);

        // Visual effects
        this.createSilverwebExtractionEffects(player, [...woodBlocks, ...leafBlocks]);

        // Messages
        this.sendActionBar(player, `§9Silverweb Extracted §8▸ §e${essenceGained} arcane energy §7| §9Timber: ${woodBlocks.length}, Foliage: ${leafBlocks.length}`, '§9');

        system.runTimeout(() => {
            this.sendActionBar(player, `§9Arcane Transmutation §8▸ §aMythril materials forged from silverweb essence`, '§9');
        }, 60);
    },

    grantSilverwebRewards(player, essenceAmount) {
        try {
            const location = player.location;

            // Guaranteed dust based on essence (1 dust per 3 essence)
            const guaranteedDust = Math.floor(essenceAmount / 3);
            if (guaranteedDust > 0) {
                for (let i = 0; i < guaranteedDust; i++) {
                    this.spawnMythrilItem(player.dimension, location, 'myw:mythril_dust');
                }
            }

            // Chance for nuggets (higher essence = better chance)
            const nuggetChance = Math.min(0.6, essenceAmount * 0.03); // Max 60% chance
            if (Math.random() < nuggetChance) {
                const nuggetCount = Math.floor(essenceAmount / 8) + 1;
                for (let i = 0; i < nuggetCount; i++) {
                    this.spawnMythrilItem(player.dimension, location, 'myw:mythril_nugget');
                }

                system.runTimeout(() => {
                    this.sendActionBar(player, `§9Silverweb Crystallization! §8▸ §ePure nuggets from concentrated essence`, '§9');
                }, 20);
            }

        } catch (error) {
            this.sendActionBar(player, '§cError manifesting rewards', '§9');
        }
    },

    // ARCANE HARVEST: When chopping wood blocks
    performArcaneHarvest(player, targetBlock) {
        try {
            const blockType = targetBlock.typeId;
            const location = targetBlock.location;

            // Always attempt mythril drops from wood
            this.attemptMythrilDrops(player, location);

            // Special wood chopping effects
            this.createArcaneHarvestEffects(player, location, blockType);

            // Check for connected wood and create chain reaction
            if (Math.random() < 0.3) { // 30% chance for chain reaction
                this.triggerSilverwebChainReaction(player, location, blockType);
            }

            const woodName = this.getWoodName(blockType);
            this.sendActionBar(player, `§9${woodName} Severed §8▸ §eMythril-Enhanced §7| §9Silverweb essence absorbed`, '§9');

        } catch (error) {
            // Error with arcane harvest
        }
    },

    triggerSilverwebChainReaction(player, startLocation, blockType) {
        try {
            const dimension = player.dimension;
            const nearbyWood = [];

            // Find nearby wood blocks of the same type
            for (let x = -2; x <= 2; x++) {
                for (let y = -1; y <= 1; y++) {
                    for (let z = -2; z <= 2; z++) {
                        if (x === 0 && y === 0 && z === 0) continue; // Skip center block

                        const checkLocation = {
                            x: startLocation.x + x,
                            y: startLocation.y + y,
                            z: startLocation.z + z
                        };

                        try {
                            const block = dimension.getBlock(checkLocation);
                            if (block && block.typeId === blockType) {
                                nearbyWood.push(checkLocation);
                            }
                        } catch (error) {
                            continue;
                        }
                    }
                }
            }

            if (nearbyWood.length > 0) {
                const woodToBreak = nearbyWood.slice(0, 3); // Limit to 3 blocks

                woodToBreak.forEach((woodLocation, index) => {
                    system.runTimeout(() => {
                        try {
                            this.createSilverwebChainEffects(dimension, woodLocation);
                            this.attemptMythrilDrops(player, woodLocation);
                            dimension.runCommand(`setblock ${woodLocation.x} ${woodLocation.y} ${woodLocation.z} air destroy`);
                        } catch (error) {
                            // Error with chain reaction
                        }
                    }, index * 10);
                });

                system.runTimeout(() => {
                    this.sendActionBar(player, `§9Silverweb Chain Reaction §8▸ §e${woodToBreak.length} extra blocks §7| §9Arcane resonance activated`, '§9');
                }, 30);
            }

        } catch (error) {
            // Error with chain reaction
        }
    },

    // UTILITY FUNCTIONS
    createChoppingEffects(player, location, blockType) {
        try {
            // Always attempt mythril drops for any block chopped with the axe
            this.attemptMythrilDrops(player, location);

            if (this.isWoodBlock(blockType)) {
                // Enhanced effects already handled in performArcaneHarvest
                return;
            } else {
                // Regular block chopping
                this.sendActionBar(player, `§9Block Severed §8▸ §eMythril Enhanced §7| §9Chance for silverweb materials`, '§9');
            }
        } catch (error) {
            // Error with effects
        }
    },

    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;

            // 25% chance for mythril dust
            if (Math.random() < this.config.dustDropChance) {
                this.spawnMythrilItem(dimension, dropLocation, 'myw:mythril_dust');
                droppedSomething = true;

                // Silverweb-themed particles for dust
                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 * 3);
                }
            }

            // 15% chance for mythril nugget
            if (Math.random() < this.config.nuggetDropChance) {
                this.spawnMythrilItem(dimension, dropLocation, 'myw:mythril_nugget');
                droppedSomething = true;

                // Special silverweb 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 * 4);
                }

                system.runTimeout(() => {
                    this.sendActionBar(player, `§9Silverweb Nugget! §8▸ §eTimber essence crystallized §7| §915% chance success`, '§9');
                }, 10);
            }

            if (droppedSomething) {
                system.runTimeout(() => {
                    this.sendActionBar(player, `§9Silverweb Materials Found! §8▸ §aTimber blessed by mythril §7| §9Continue harvesting`, '§9');
                }, 5);
            }

        } catch (error) {
            world.sendMessage('§cDebug: Error in axe 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
    createSilverwebExtractionEffects(player, blocks) {
        const playerLocation = player.location;

        blocks.forEach((block, index) => {
            system.runTimeout(() => {
                try {
                    // Energy beam from block to player
                    this.createSilverwebBeam(player.dimension, block.location, playerLocation);
                } catch (error) {
                    // Error with beam
                }
            }, index * 2);
        });

        // Aura around player
        this.createSilverwebAura(player);
    },

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

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

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

            for (let i = 0; i < 12; i++) {
                const angle = (i / 12) * Math.PI * 2;
                const radius = 2.5;

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

    createArcaneHarvestEffects(dimension, location, blockType) {
        try {
            // Special wood chopping 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.5 + (Math.random() - 0.5) * 1.0,
                            z: location.z + 0.5 + (Math.random() - 0.5) * 1.0
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating effects
        }
    },

    createSilverwebChainEffects(dimension, location) {
        try {
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle', {
                            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 * 1);
            }
        } catch (error) {
            // Error creating chain effects
        }
    },

    // BLOCK TYPE CHECKERS
    isWoodBlock(blockType) {
        const woodBlocks = [
            'minecraft:oak_log', 'minecraft:spruce_log', 'minecraft:birch_log',
            'minecraft:jungle_log', 'minecraft:acacia_log', 'minecraft:dark_oak_log',
            'minecraft:mangrove_log', 'minecraft:cherry_log',
            'minecraft:stripped_oak_log', 'minecraft:stripped_spruce_log',
            'minecraft:stripped_birch_log', 'minecraft:stripped_jungle_log',
            'minecraft:stripped_acacia_log', 'minecraft:stripped_dark_oak_log',
            'minecraft:stripped_mangrove_log', 'minecraft:stripped_cherry_log',
            'minecraft:oak_wood', 'minecraft:spruce_wood', 'minecraft:birch_wood',
            'minecraft:jungle_wood', 'minecraft:acacia_wood', 'minecraft:dark_oak_wood',
            'minecraft:mangrove_wood', 'minecraft:cherry_wood'
        ];
        return woodBlocks.includes(blockType);
    },

    isLeafBlock(blockType) {
        const leafBlocks = [
            'minecraft:oak_leaves', 'minecraft:spruce_leaves', 'minecraft:birch_leaves',
            'minecraft:jungle_leaves', 'minecraft:acacia_leaves', 'minecraft:dark_oak_leaves',
            'minecraft:mangrove_leaves', 'minecraft:cherry_leaves', 'minecraft:azalea_leaves'
        ];
        return leafBlocks.includes(blockType);
    },

    getWoodName(blockType) {
        const names = {
            'minecraft:oak_log': 'Oak',
            'minecraft:spruce_log': 'Spruce',
            'minecraft:birch_log': 'Birch',
            'minecraft:jungle_log': 'Jungle',
            'minecraft:acacia_log': 'Acacia',
            'minecraft:dark_oak_log': 'Dark Oak',
            'minecraft:mangrove_log': 'Mangrove',
            'minecraft:cherry_log': 'Cherry'
        };
        return names[blockType] || 'Wood';
    }
};

// Register axe component
export function registerMythrilAxe(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_axe', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            AxeSystem.handleAxeUse(source, itemStack, useDuration);
        },

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

        onHitEntity(eventData) {
            const { source, hitEntity } = eventData;
            if (source) {
                AxeSystem.sendActionBar(source, '§9Silverweb Warrior §8▸ §7Combat with arcane power', '§9');
                AxeSystem.createArcaneHarvestEffects(source.dimension, source.location, 'entity_hit');
            }
        }
    });
}

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

                if (mainhandItem?.typeId === 'myw:mythril_axe') {
                    // Create subtle silverweb ambient effects
                    if (Math.random() > 0.97) { // 3% chance per tick
                        AxeSystem.createSilverwebAmbientEffects(player);
                    }

                    // Show silverweb sensing occasionally
                    if (Math.random() > 0.995) { // 0.5% chance per tick
                        AxeSystem.showSilverwebSensing(player);
                    }
                }
            });
        } catch (error) {
            // Error in passive detection
        }
    }, 20);

    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            AxeSystem.sendActionBar(player, '§9Mythril Cleaver System §8▸ §aOnline §7| §9Silverweb Arcana & Essence Extraction', '§9');
        });
    }, 40);

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

// Silverweb ambient effects
AxeSystem.createSilverwebAmbientEffects = function (player) {
    try {
        if (Math.random() > 0.4) return; // Reduce frequency

        const location = player.location;
        const particleType = Math.random() > 0.5 ? 'myw:mythril_particle_minimalist' : 'myw:mythril_particle_serpentine';

        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
    }
};

// Silverweb sensing display
AxeSystem.showSilverwebSensing = function (player) {
    try {
        const location = player.location;
        const dimension = player.dimension;
        let woodNearby = 0;
        let leavesNearby = 0;

        // Quick scan around player
        for (let x = -3; x <= 3; x++) {
            for (let y = -2; y <= 2; y++) {
                for (let z = -3; z <= 3; z++) {
                    const checkLocation = {
                        x: Math.floor(location.x) + x,
                        y: Math.floor(location.y) + y,
                        z: Math.floor(location.z) + z
                    };

                    try {
                        const block = dimension.getBlock(checkLocation);
                        if (block) {
                            if (this.isWoodBlock(block.typeId)) {
                                woodNearby++;
                            } else if (this.isLeafBlock(block.typeId)) {
                                leavesNearby++;
                            }
                        }
                    } catch (error) {
                        continue;
                    }
                }
            }
        }

        // Show sensing result if any nature found
        if (woodNearby > 0 || leavesNearby > 0) {
            this.sendActionBar(player, `§9Silverweb Sense §8▸ §aTimber: ${woodNearby} §7| §aFoliage: ${leavesNearby}`, '§9');
        }

    } catch (error) {
        // Error with silverweb sensing
    }
};