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

export const CarmotAxeSystem = {
    config: {
        gravityVortexRadius: 10,
        shockwaveRadius: 8,
        gravityCooldown: 300, // 15 seconds
        shockwaveCooldown: 450, // 22.5 seconds
        treeFellerRadius: 6,
        carmotDropChance: 0.35, // 35% chance for carmot drops
        singularityDropChance: 0.18, // 18% chance for singularity drops
        vortexDuration: 150 // 7.5 seconds
    },

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

    handleAxeUse(player, itemStack, useDuration) {
        try {
            if (player.isSneaking) {
                // Primary ability: Gravity Vortex
                this.activateGravityVortex(player);
                return;
            } else {
                // Show axe info when used without sneaking
                this.sendActionBar(player, '§6Gravity Cleaver §8▸ §7Sneak + Use to create gravity vortex §7| §6Chop wood for carmot materials', '§6');
                return;
            }
        } catch (error) {
            this.sendActionBar(player, '§cGravitational Anomaly Detected', '§6');
        }
    },

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

            // Check if it's wood-related block
            if (this.isWoodBlock(blockType)) {
                // Gravity-enhanced wood harvesting
                this.performGravityHarvest(player, targetBlock);
                return;
            }

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

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

    // PRIMARY ABILITY: Gravity Vortex (Sneak + Use)
    activateGravityVortex(player) {
        try {
            // Check cooldown
            const lastVortex = player.getDynamicProperty('myw:carmot_last_vortex') || 0;
            const currentTime = Date.now();

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

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

            this.sendActionBar(player, '§6Gravity Vortex §8▸ §aGenerating gravitational singularity...', '§6');
            this.createGravityVortex(player);

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

    createGravityVortex(player) {
        const { x, y, z } = player.location;
        const dimension = player.dimension;
        let vortexTime = 0;

        const vortexInterval = system.runInterval(() => {
            vortexTime++;

            // Create vortex particles
            const radius = 3.0;
            for (let i = 0; i < 16; i++) {
                const angle = (i / 16) * Math.PI * 2 + vortexTime * 0.2;
                const vortexX = x + Math.cos(angle) * radius;
                const vortexZ = z + Math.sin(angle) * radius;
                const vortexY = y + 1.0 + Math.sin(vortexTime * 0.3) * 0.5;

                this.spawnCarmotParticle(dimension, vortexX, vortexY, vortexZ, 'gravity');

                // Add singularity particles occasionally
                if (i % 4 === 0) {
                    this.spawnCarmotParticle(dimension, vortexX, vortexY + 0.3, vortexZ, 'singularity');
                }
            }

            // Attract and damage entities
            dimension.getEntities().forEach(entity => {
                if (entity.id !== player.id && this.isNear(player, entity, this.config.gravityVortexRadius)) {
                    // Strong attraction force
                    this.applyGravitationalForce(entity, x, y + 1.5, z, 0.9);

                    // Damage to mobs
                    if (entity.typeId !== 'minecraft:item' && vortexTime % 10 === 0) {
                        try {
                            entity.applyDamage(4, { cause: EntityDamageCause.magic });
                        } catch (error) {
                            // Ignore if cannot apply damage
                        }
                    }
                }
            });

            // Break nearby wood and leaves
            if (vortexTime % 15 === 0) {
                this.breakNearbyVegetation(dimension, x, y, z, player);
            }

            if (vortexTime >= this.config.vortexDuration) {
                system.clearRun(vortexInterval);
                this.collapseGravityVortex(dimension, x, y, z);
            }
        }, 2);
    },

    collapseGravityVortex(dimension, x, y, z) {
        // Implosion effect
        for (let i = 0; i < 20; i++) {
            system.runTimeout(() => {
                const radius = 4.0 - (i * 0.2);

                for (let j = 0; j < 12; j++) {
                    const angle = (j / 12) * Math.PI * 2;
                    const collapseX = x + Math.cos(angle) * radius;
                    const collapseZ = z + Math.sin(angle) * radius;
                    const collapseY = y + 1.5 + (Math.random() - 0.5);

                    this.spawnCarmotParticle(dimension, collapseX, collapseY, collapseZ, 'singularity');
                }
            }, i * 3);
        }

        // Final message
        system.runTimeout(() => {
            this.sendActionBar(player, '§6Gravity Vortex Collapsed §8▸ §aSingularity dissipated', '§6');
        }, 60);
    },

    breakNearbyVegetation(dimension, centerX, centerY, centerZ, player) {
        for (let x = -this.config.treeFellerRadius; x <= this.config.treeFellerRadius; x++) {
            for (let y = -this.config.treeFellerRadius; y <= this.config.treeFellerRadius; y++) {
                for (let z = -this.config.treeFellerRadius; z <= this.config.treeFellerRadius; z++) {
                    // Check spherical radius
                    const distance = Math.sqrt(x * x + y * y + z * z);
                    if (distance > this.config.treeFellerRadius) continue;

                    const checkLocation = {
                        x: Math.floor(centerX) + x,
                        y: Math.floor(centerY) + y,
                        z: Math.floor(centerZ) + z
                    };

                    try {
                        const block = dimension.getBlock(checkLocation);
                        if (block && (this.isWoodBlock(block.typeId) || this.isLeafBlock(block.typeId))) {
                            // Break the block and attempt drops
                            this.mineBlockWithPlayer(dimension, checkLocation, block.typeId, player);

                            // Create breaking effect
                            this.createGravityBreakEffect(dimension, checkLocation);
                        }
                    } catch (error) {
                        continue;
                    }
                }
            }
        }
    },

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

            // Always attempt carmot drops from wood
            this.attemptCarmotDrops(player, location);

            // Special gravity chopping effects
            this.createGravityHarvestEffects(player, location, blockType);

            // Chance for gravity chain reaction
            if (Math.random() < 0.25) { // 25% chance for chain reaction
                this.triggerGravityChainReaction(player, location, blockType);
            }

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

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

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

            // Find nearby wood blocks of the same type
            for (let x = -3; x <= 3; x++) {
                for (let y = -2; y <= 2; y++) {
                    for (let z = -3; z <= 3; 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, 4); // Limit to 4 blocks

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

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

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

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

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

    attemptCarmotDrops(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;

            // Chance for carmot dust
            if (Math.random() < this.config.carmotDropChance) {
                this.spawnCarmotItem(dimension, dropLocation, 'myw:carmot_dust');
                droppedSomething = true;

                // Gravity particles for dust
                for (let i = 0; i < 5; i++) {
                    system.runTimeout(() => {
                        try {
                            this.spawnCarmotParticle(dimension, {
                                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
                            }, 'gravity');
                        } catch (error) {
                            // Error with particles
                        }
                    }, i * 3);
                }
            }

            // Chance for singularity shard
            if (Math.random() < this.config.singularityDropChance) {
                this.spawnCarmotItem(dimension, dropLocation, 'myw:singularity_shard');
                droppedSomething = true;

                // Singularity particles for shard
                for (let i = 0; i < 7; i++) {
                    system.runTimeout(() => {
                        try {
                            this.spawnCarmotParticle(dimension, {
                                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
                            }, 'singularity');
                        } catch (error) {
                            // Error with particles
                        }
                    }, i * 4);
                }

                system.runTimeout(() => {
                    this.sendActionBar(player, `§5Singularity Shard! §8▸ §dGravitational artifact §7| §518% chance success`, '§5');
                }, 10);
            }

            if (droppedSomething) {
                system.runTimeout(() => {
                    this.sendActionBar(player, `§dGravitational Materials Found! §8▸ §5Check around your feet §7| §6Continue harvesting`, '§d');
                }, 5);
            }

        } catch (error) {
            // Error in drop system
        }
    },

    spawnCarmotItem(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) {
                    // All methods failed
                }
            }
        }
    },

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

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

            // Attempt carmot drops
            this.attemptCarmotDrops(player, location);

            // Break the block
            dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);

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

    // VISUAL EFFECTS
    createGravityHarvestEffects(player, location, blockType) {
        try {
            // Gravity chopping particles
            for (let i = 0; i < 6; i++) {
                system.runTimeout(() => {
                    try {
                        this.spawnCarmotParticle(player.dimension, {
                            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
                        }, 'gravity');
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating effects
        }
    },

    createGravityBreakEffect(dimension, location) {
        try {
            // Particles moving toward center (implosion effect)
            for (let i = 0; i < 8; i++) {
                const angle = Math.random() * Math.PI * 2;
                const radius = 1.2 + Math.random() * 0.5;
                const particleX = location.x + 0.5 + Math.cos(angle) * radius;
                const particleZ = location.z + 0.5 + Math.sin(angle) * radius;
                const particleY = location.y + 0.5 + (Math.random() - 0.5) * 1.2;

                this.spawnCarmotParticle(dimension, particleX, particleY, particleZ, 'gravity');
            }

            // Center implosion
            this.spawnCarmotParticle(dimension, location.x + 0.5, location.y + 0.5, location.z + 0.5, 'singularity');
        } catch (error) {
            // Error with effects
        }
    },

    createGravityChainEffects(dimension, location) {
        try {
            for (let i = 0; i < 10; i++) {
                system.runTimeout(() => {
                    try {
                        this.spawnCarmotParticle(dimension, {
                            x: location.x + 0.5 + (Math.random() - 0.5) * 1.5,
                            y: location.y + 0.5 + (Math.random() - 0.5) * 1.5,
                            z: location.z + 0.5 + (Math.random() - 0.5) * 1.5
                        }, 'gravity');
                    } 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';
    },

    // Utility functions for gravity effects
    isNear(entity1, entity2, maxDistance, maxHeightDiff = 10) {
        const distance = Math.sqrt(
            Math.pow(entity1.location.x - entity2.location.x, 2) +
            Math.pow(entity1.location.y - entity2.location.y, 2) +
            Math.pow(entity1.location.z - entity2.location.z, 2)
        );

        return distance <= maxDistance &&
            Math.abs(entity1.location.y - entity2.location.y) <= maxHeightDiff;
    },

    spawnCarmotParticle(dimension, location, particleType = 'gravity') {
        const particles = {
            'standard': 'myw:carmot_particle',
            'gravity': 'myw:carmot_particle_gravity',
            'serpentine': 'myw:carmot_particle_serpentine',
            'singularity': 'myw:carmot_particle_singularity'
        };

        const fallbacks = {
            'standard': 'minecraft:lava_particle',
            'gravity': 'minecraft:portal_particle',
            'serpentine': 'minecraft:crimson_spore_particle',
            'singularity': 'minecraft:end_rod'
        };

        try {
            // Handle both object and coordinate parameters
            if (typeof location === 'object' && location.x !== undefined) {
                dimension.spawnParticle(particles[particleType] || particles.gravity, location);
            } else {
                // Assume coordinates were passed separately
                dimension.spawnParticle(particles[particleType] || particles.gravity, {
                    x: arguments[0],
                    y: arguments[1],
                    z: arguments[2]
                });
            }
        } catch (error) {
            try {
                if (typeof location === 'object' && location.x !== undefined) {
                    dimension.spawnParticle(fallbacks[particleType] || fallbacks.gravity, location);
                } else {
                    dimension.spawnParticle(fallbacks[particleType] || fallbacks.gravity, {
                        x: arguments[0],
                        y: arguments[1],
                        z: arguments[2]
                    });
                }
            } catch (fallbackError) {
                // Silent fail
            }
        }
    },

    applyGravitationalForce(entity, centerX, centerY, centerZ, strength) {
        const { x, y, z } = entity.location;
        const dx = centerX - x;
        const dy = centerY - y;
        const dz = centerZ - z;

        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
        if (distance < 0.1) return;

        const forceX = (dx / distance) * strength;
        const forceY = (dy / distance) * strength;
        const forceZ = (dz / distance) * strength;

        try {
            entity.applyImpulse({ x: forceX, y: forceY, z: forceZ });
        } catch (error) {
            // Entity might not have physics
        }
    }
};

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

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

        onHitEntity(eventData) {
            const { source, hitEntity } = eventData;
            if (source) {
                CarmotAxeSystem.sendActionBar(source, '§6Gravity Warrior §8▸ §7Combat with gravitational force', '§6');
                CarmotAxeSystem.createGravityHarvestEffects(source.dimension, source.location, 'entity_hit');

                // Apply gravitational knockback
                try {
                    const dx = hitEntity.location.x - source.location.x;
                    const dz = hitEntity.location.z - source.location.z;
                    const distance = Math.sqrt(dx * dx + dz * dz);

                    if (distance > 0) {
                        hitEntity.applyImpulse({
                            x: (dx / distance) * 1.2,
                            y: 0.4,
                            z: (dz / distance) * 1.2
                        });
                    }
                } catch (error) {
                    // Ignore if cannot apply impulse
                }
            }
        }
    });
}

// Initialize axe systems
export function initializeCarmotAxeSystems() {
    // Passive gravity effects 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:carmot_axe') {
                    // Create subtle gravity ambient effects
                    if (Math.random() > 0.92) { // 8% chance per tick
                        CarmotAxeSystem.createGravityAmbientEffects(player);
                    }
                }
            });
        } catch (error) {
            // Error in passive effects
        }
    }, 20);

    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            CarmotAxeSystem.sendActionBar(player, '§6Gravity Cleaver System §8▸ §aOnline §7| §6Gravitational Harvesting & Vortex', '§6');
        });
    }, 40);
}

// Create subtle ambient effects
CarmotAxeSystem.createGravityAmbientEffects = function (player) {
    try {
        const location = player.location;

        // Create orbiting gravity particles
        const angle = Date.now() / 800;
        const radius = 1.8;

        this.spawnCarmotParticle(player.dimension, {
            x: location.x + Math.cos(angle) * radius,
            y: location.y + 1.3,
            z: location.z + Math.sin(angle) * radius
        }, 'gravity');

        // Secondary orbit
        this.spawnCarmotParticle(player.dimension, {
            x: location.x + Math.cos(angle + Math.PI) * (radius * 0.6),
            y: location.y + 1.1,
            z: location.z + Math.sin(angle + Math.PI) * (radius * 0.6)
        }, 'singularity');
    } catch (error) {
        // Error with ambient effects
    }
};