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

export const CarmotPickaxeSystem = {
    config: {
        gravityRadius: 8,
        implosionPower: 1.2,
        gravityCooldown: 300, // 15 seconds
        implosionCooldown: 600, // 30 seconds
        particleIntensity: 0.8,
        gravityDropChance: 0.40, // 40% chance for carmot drops
        singularityDropChance: 0.15, // 15% chance for singularity drops
        gravityWellDuration: 200 // 10 seconds
    },

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

    handlePickaxeUse(player, itemStack, useDuration) {
        try {
            // Check if sneaking for gravity implosion
            if (player.isSneaking) {
                this.activateGravityImplosion(player);
                return;
            }

            // Regular use activates gravity well
            this.activateGravityWell(player);

        } 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 gravity fracture
            if (this.isValuableOre(blockType) && player.isSneaking) {
                this.startGravityFracture(player, itemStack, targetBlock);
                return;
            }

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

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

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

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

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

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

            // Show activation message
            this.sendActionBar(player, ' §6Gravity Implosion §8▸ §aGenerating Singularity...', '§6');

            // Create gravity implosion
            this.createGravityImplosion(player);

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

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

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

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

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

            // Show activation message
            this.sendActionBar(player, ' §6Gravity Well §8▸ §aCreating Distortion Field...', '§6');

            // Create gravity well
            this.createGravityWell(player);

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

    createGravityImplosion(player) {
        const { x, y, z } = player.location;
        const dimension = player.dimension;

        // Create implosion effect
        for (let i = 0; i < 20; i++) {
            system.runTimeout(() => {
                const radius = 8 - (i * 0.4);

                // Create implosion ring
                for (let j = 0; j < 16; j++) {
                    const angle = (j / 16) * Math.PI * 2;
                    const particleX = x + Math.cos(angle) * radius;
                    const particleZ = z + Math.sin(angle) * radius;

                    // Gravity particles moving toward center
                    this.spawnCarmotParticle(dimension, particleX, y + 1, particleZ, 'gravity');

                    // Singularity particles
                    if (j % 4 === 0) {
                        this.spawnCarmotParticle(dimension, particleX, y + 1.5, particleZ, 'singularity');
                    }
                }

                // Apply force to nearby entities
                dimension.getEntities().forEach(entity => {
                    if (entity.id !== player.id && this.isNear({ location: { x, y, z } }, entity, 8)) {
                        this.applyGravitationalForce(entity, x, y + 1, z, 0.8);

                        // Damage from implosion
                        if (i % 5 === 0) {
                            try {
                                entity.applyDamage(3, { cause: EntityDamageCause.magic });
                            } catch (error) {
                                // Ignore if cannot apply damage
                            }
                        }
                    }
                });

                // Break nearby ores
                if (i % 3 === 0) {
                    this.implodeNearbyOres(dimension, x, y, z, radius, player);
                }
            }, i * 2);
        }

        // Final explosion
        system.runTimeout(() => {
            for (let i = 0; i < 30; i++) {
                const angle = Math.random() * Math.PI * 2;
                const strength = 1.5 + Math.random() * 1.2;
                const particleX = x + Math.cos(angle) * strength;
                const particleZ = z + Math.sin(angle) * strength;
                const particleY = y + 1 + (Math.random() - 0.5) * 2;

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

            // Final damage to nearby entities
            dimension.getEntities().forEach(entity => {
                if (this.isNear({ location: { x, y, z } }, entity, 6)) {
                    try {
                        entity.applyDamage(10, { cause: EntityDamageCause.magic });
                    } catch (error) {
                        // Ignore if cannot apply damage
                    }
                }
            });
        }, 40);
    },

    implodeNearbyOres(dimension, centerX, centerY, centerZ, radius, player) {
        for (let x = -radius; x <= radius; x++) {
            for (let y = -2; y <= 2; y++) {
                for (let z = -radius; z <= radius; z++) {
                    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.isValuableOre(block.typeId)) {
                            // Break the ore and attempt drops
                            this.mineVeinBlockWithPlayer(dimension, checkLocation, block.typeId, player);

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

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

        const wellInterval = system.runInterval(() => {
            wellTime++;

            // Create gravity well particles
            for (let ring = 1; ring <= 3; ring++) {
                const radius = ring * 2.5;
                const particles = ring * 12;

                for (let i = 0; i < particles; i++) {
                    const angle = (i / particles) * Math.PI * 2 + wellTime * 0.1;
                    const ringX = x + Math.cos(angle) * radius;
                    const ringZ = z + Math.sin(angle) * radius;
                    const ringY = y + 0.5 + Math.sin(wellTime * 0.2 + angle) * 0.5;

                    this.spawnCarmotParticle(dimension, ringX, ringY, ringZ, 'gravity');
                }
            }

            // Attract items and entities
            dimension.getEntities().forEach(entity => {
                if (entity.id !== player.id && this.isNear(player, entity, 10)) {
                    // Attract items and mobs
                    this.applyGravitationalForce(entity, x, y + 1, z, 0.4);

                    // Special effect for items
                    if (entity.typeId === 'minecraft:item') {
                        this.applyGravitationalForce(entity, x, y + 0.5, z, 0.6);
                    }
                }
            });

            if (wellTime >= this.config.gravityWellDuration) {
                system.clearRun(wellInterval);
                this.collapseGravityWell(dimension, x, y, z);
            }
        }, 2);
    },

    collapseGravityWell(dimension, x, y, z) {
        // Implosion effect
        for (let i = 0; i < 15; i++) {
            system.runTimeout(() => {
                const radius = 7.5 - (i * 0.5);

                for (let j = 0; j < 20; j++) {
                    const angle = (j / 20) * 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, 'gravity');
                }
            }, i * 3);
        }
    },

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

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

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

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

            // Show activation message
            this.sendActionBar(player, ' §6Gravity Fracture §7▸ §eCharging...', '§6');

            // Find nearby ores in a spherical area
            const fractureBlocks = this.findNearbyOres(player.dimension, startBlock.location, startBlock.typeId);

            if (fractureBlocks.length > 0) {
                const oreName = this.getOreName(startBlock.typeId);
                this.sendActionBar(player, `⛏ §6Gravity Fracture Activated §8▸ §e${fractureBlocks.length} ${oreName} blocks §7| §aGravitational Extraction`, '§6');
                this.fractureBlocksWithDelay(player, itemStack, fractureBlocks, startBlock.typeId);
            } else {
                this.sendActionBar(player, ' §7No Nearby Ores §8▸ §7Try different location §8| §eGravity scan complete', '§7');
            }

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

    findNearbyOres(dimension, centerLocation, blockType) {
        const ores = [];
        const radius = 5;

        for (let x = -radius; x <= radius; x++) {
            for (let y = -radius; y <= radius; y++) {
                for (let z = -radius; z <= radius; z++) {
                    // Check if within spherical radius
                    const distance = Math.sqrt(x * x + y * y + z * z);
                    if (distance > radius) continue;

                    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 && this.isValuableOre(block.typeId)) {
                            ores.push(checkLocation);
                        }
                    } catch (error) {
                        continue;
                    }
                }
            }
        }

        return ores;
    },

    fractureBlocksWithDelay(player, itemStack, fractureBlocks, blockType) {
        let index = 0;
        const dimension = player.dimension;

        const fractureInterval = system.runInterval(() => {
            if (index >= fractureBlocks.length) {
                system.clearRun(fractureInterval);
                this.finishGravityFracture(player, fractureBlocks.length, blockType);
                return;
            }

            // Mine several blocks per tick
            const batchSize = Math.min(4, fractureBlocks.length - index);
            for (let i = 0; i < batchSize; i++) {
                if (index + i < fractureBlocks.length) {
                    this.mineVeinBlockWithPlayer(dimension, fractureBlocks[index + i], blockType, player);

                    // Create gravity fracture effect
                    this.createGravityFractureEffect(dimension, fractureBlocks[index + i]);
                }
            }

            index += batchSize;

            // Progress update
            const progress = Math.round((index / fractureBlocks.length) * 100);
            const progressBar = this.createProgressBar(progress);
            this.sendActionBar(player, `⛏ §6Gravity Fracture §8▸ §e${progress}% ${progressBar}`, '§6');

        }, 2);
    },

    createGravityFractureEffect(dimension, location) {
        try {
            // Create implosion effect at block location
            for (let i = 0; i < 5; i++) {
                const angle = Math.random() * Math.PI * 2;
                const radius = Math.random() * 1.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.5;

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

    mineVeinBlockWithPlayer(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
            }
        }
    },

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

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

    createGravityBreakEffect(dimension, location) {
        try {
            // Particles moving toward center
            for (let i = 0; i < 8; i++) {
                const angle = Math.random() * Math.PI * 2;
                const radius = 1.0 + 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.0;

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

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

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

            // Completion effects
            this.createFractureCompleteEffects(player);

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

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

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

            // Gravitational celebration effect
            for (let i = 0; i < 25; i++) {
                system.runTimeout(() => {
                    try {
                        const angle = Math.random() * Math.PI * 2;
                        const height = Math.random() * 2;
                        const radius = 1.5 + Math.random() * 2;

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

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

    createGravityMiningEffects(player, location, blockType) {
        try {
            // ALWAYS attempt carmot drops for every block mined
            this.attemptCarmotDrops(player, location);

            // Enhanced visual effects for valuable ores
            if (this.isValuableOre(blockType)) {
                // Gravity particles for valuable ores
                for (let i = 0; i < 4; i++) {
                    system.runTimeout(() => {
                        try {
                            this.spawnCarmotParticle(player.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 * 3);
                }

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

    // Carmot drops function
    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.gravityDropChance) {
                try {
                    dimension.spawnItem(new ItemStack('myw:carmot_dust', 1), dropLocation);
                    droppedSomething = true;

                    // Gravity particles for dust
                    for (let i = 0; i < 6; 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 * 2);
                    }
                } catch (error) {
                    // Fallback to command
                    try {
                        dimension.runCommand(`summon item ${dropLocation.x} ${dropLocation.y} ${dropLocation.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"myw:carmot_dust","Count":1}}`);
                        droppedSomething = true;
                    } catch (cmdError) {
                        try {
                            dimension.runCommand(`give "${player.name}" myw:carmot_dust 1`);
                            droppedSomething = true;
                        } catch (giveError) {
                            // All methods failed
                        }
                    }
                }
            }

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

                    // Singularity particles for shard
                    for (let i = 0; i < 10; 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 * 3);
                    }

                    // Special message for singularity drop
                    system.runTimeout(() => {
                        this.sendActionBar(player, ` §5Singularity Shard! §8▸ §dRare gravitational artifact §7| §515% chance success`, '§5');
                    }, 10);
                } catch (error) {
                    // Fallback to command
                    try {
                        dimension.runCommand(`summon item ${dropLocation.x} ${dropLocation.y} ${dropLocation.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"myw:singularity_shard","Count":1}}`);
                        droppedSomething = true;
                    } catch (cmdError) {
                        try {
                            dimension.runCommand(`give "${player.name}" myw:singularity_shard 1`);
                            droppedSomething = true;
                        } catch (giveError) {
                            // All methods failed
                        }
                    }
                }
            }

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

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

    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 'implosion':
                    soundId = 'ambient.basalt_deltas.additions';
                    break;
                case 'fracture_start':
                    soundId = 'random.orb';
                    break;
                case 'success':
                    soundId = 'random.levelup';
                    break;
                case 'mining':
                    soundId = 'dig.stone';
                    break;
            }

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

    // 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 pickaxe component
export function registerCarmotPickaxe(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_pickaxe', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            CarmotPickaxeSystem.handlePickaxeUse(source, itemStack, useDuration);
        },

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

        onHitEntity(eventData) {
            // Pickaxe can be used as basic weapon with gravity effect
            const { source, hitEntity } = eventData;
            if (source) {
                CarmotPickaxeSystem.createGravityMiningEffects(source, source.location, 'entity_hit');
                CarmotPickaxeSystem.sendActionBar(source, ' §6Gravity Strike §8▸ §7Combat Mode', '§6');

                // Apply knockback to hit entity
                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) * 0.8,
                            y: 0.3,
                            z: (dz / distance) * 0.8
                        });
                    }
                } catch (error) {
                    // Ignore if cannot apply impulse
                }
            }
        }
    });
}

// Initialize pickaxe systems
export function initializeCarmotPickaxeSystems() {
    // 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:carmot_pickaxe') {
                    // Create subtle gravity particles
                    if (Math.random() > 0.9) { // 10% chance per tick
                        CarmotPickaxeSystem.createGravityAmbientEffects(player);
                    }
                }
            });
        } catch (error) {
            // Error in passive effects
        }
    }, 20);

    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            CarmotPickaxeSystem.sendActionBar(player, ' §6Carmot Pickaxe System §8▸ §aOnline §7| §eGravity Implosion & Fracture Mining', '§6');
        });
    }, 20);
}

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

        // Create orbiting gravity particles
        const angle = Date.now() / 1000;
        const radius = 1.5;

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

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