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

export const ShovelSystem = {

    config: {
        relicDetectionCooldown: 80, // 4 seconds
        relicExcavationRadius: 4, // 4x4 area for relic sites
        excavationCooldown: 150, // 7.5 seconds
        dustDropChance: 0.35, // 35% chance for dust while digging
        nuggetDropChance: 0.20, // 20% chance for nuggets
        simpleRelicChance: 0.15, // 15% chance to find simple relic (reduced from higher)
        detectionRadius: 8 // Radius for simple relic detection
    },

    simpleRelics: [
        {
            name: 'Ancient Coin',
            rarity: 'common',
            reward: 'myw:mythril_dust',
            message: 'Ancient coin discovered',
            chance: 0.60 // 60% of simple relic finds
        },
        {
            name: 'Worn Jewelry',
            rarity: 'uncommon',
            reward: 'myw:mythril_nugget',
            message: 'Worn jewelry fragment found',
            chance: 0.30 // 30% of simple relic finds
        },
        {
            name: 'Mythril Shard',
            rarity: 'rare',
            reward: 'myw:mythril_nugget',
            message: 'Pure mythril shard unearthed',
            chance: 0.10 // 10% of simple relic finds
        }
    ],

    excavationRelics: [
        {
            name: 'Ancient Burial',
            rarity: 'common',
            rewards: ['myw:mythril_dust', 'myw:mythril_dust', 'myw:mythril_dust'], // More rewards
            message: 'Ancient burial site excavated',
            particles: 'myw:mythril_particle_minimalist'
        },
        {
            name: 'Lost Treasure Cache',
            rarity: 'uncommon',
            rewards: ['myw:mythril_dust', 'myw:mythril_dust', 'myw:mythril_nugget', 'myw:mythril_nugget'], // More rewards
            message: 'Lost treasure cache unearthed',
            particles: 'myw:mythril_particle'
        },
        {
            name: 'Mythril Artifact Vault',
            rarity: 'rare',
            rewards: ['myw:mythril_nugget', 'myw:mythril_nugget', 'myw:mythril_nugget', 'myw:mythril_dust', 'myw:mythril_dust'], // Much more rewards
            message: 'Ancient mythril artifact vault discovered',
            particles: 'myw:mythril_particle_serpentine'
        }
    ],

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

    handleShovelUse(player, itemStack, useDuration) {
        try {
            if (player.isSneaking) {
                // Simple Relic Detection
                this.activateSimpleRelicDetection(player);
                return;
            } else {
                // Show shovel info
                this.sendActionBar(player, 'Mythril Archaeological Shovel | §7Sneak + Use for relic detection | §aDig for ancient treasures', '§b');
                return;
            }
        } catch (error) {
            this.sendActionBar(player, 'Shovel Error Occurred', '§c');
        }
    },

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

            // Check if player is sneaking for Archaeological Excavation
            if (player.isSneaking && this.isExcavatableGround(blockType)) {
                this.startArchaeologicalExcavation(player, targetBlock.location);
                return;
            }

            // Normal digging with relic discovery chance
            this.performArchaeologicalDig(player, targetBlock.location, blockType);

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

    // PRIMARY ABILITY: Simple Relic Detection (Sneak + Use)
    activateSimpleRelicDetection(player) {
        try {
            // Check cooldown
            const lastDetection = player.getDynamicProperty('myw:last_relic_detection') || 0;
            const currentTime = Date.now();

            if (currentTime - lastDetection < this.config.relicDetectionCooldown * 50) {
                const remainingTime = Math.ceil((this.config.relicDetectionCooldown * 50 - (currentTime - lastDetection)) / 1000);
                this.sendActionBar(player, `Relic Detection Cooldown | §e${remainingTime}s remaining`, '§9');
                return;
            }

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

            this.sendActionBar(player, 'Relic Detection | §aSensing nearby ancient artifacts...', '§b');
            this.performSimpleRelicDetection(player);

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

    performSimpleRelicDetection(player) {
        try {
            const playerLocation = player.location;

            // Check if relic is found
            if (Math.random() < this.config.simpleRelicChance) {
                // Determine relic type
                const randomValue = Math.random();
                let selectedRelic = this.simpleRelics[0]; // Default to common

                let cumulativeChance = 0;
                for (const relic of this.simpleRelics) {
                    cumulativeChance += relic.chance;
                    if (randomValue <= cumulativeChance) {
                        selectedRelic = relic;
                        break;
                    }
                }

                system.runTimeout(() => {
                    this.processSimpleRelicFind(player, selectedRelic, playerLocation);
                }, 30);

            } else {
                // No relic found
                system.runTimeout(() => {
                    this.sendActionBar(player, 'Detection Complete | §7No relics detected nearby | §eTry different areas', '§9');
                    this.createFailedDetectionEffects(player);
                }, 30);
            }

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

    processSimpleRelicFind(player, relic, location) {
        // Spawn the relic reward near player
        const spawnLocation = {
            x: location.x + (Math.random() - 0.5) * 2,
            y: location.y + 0.5,
            z: location.z + (Math.random() - 0.5) * 2
        };

        this.spawnMythrilItem(player.dimension, spawnLocation, relic.reward);

        // Success message
        this.sendActionBar(player, `${relic.name} | §e${relic.message} | §a${relic.rarity} relic`, '§b');

        // Effects
        this.createSimpleRelicEffects(player, spawnLocation, relic);

        system.runTimeout(() => {
            this.sendActionBar(player, `Archaeological Instinct | §aMythril-enhanced senses guide you to ancient artifacts`, '§3');
        }, 60);
    },

    // SECONDARY ABILITY: Archaeological Excavation (Sneak + Dig)
    startArchaeologicalExcavation(player, centerLocation) {
        try {
            // Check cooldown
            const lastExcavation = player.getDynamicProperty('myw:last_excavation') || 0;
            const currentTime = Date.now();

            if (currentTime - lastExcavation < this.config.excavationCooldown * 50) {
                const remainingTime = Math.ceil((this.config.excavationCooldown * 50 - (currentTime - lastExcavation)) / 1000);
                this.sendActionBar(player, `Excavation Cooldown | §e${remainingTime}s remaining`, '§9');
                return;
            }

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

            this.sendActionBar(player, 'Major Archaeological Excavation | §aSearching for significant ancient sites...', '§b');
            this.performMajorExcavation(player, centerLocation);

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

    performMajorExcavation(player, centerLocation) {
        try {
            const dimension = player.dimension;
            const radius = this.config.relicExcavationRadius;

            // Clear excavation area
            this.createExcavationSite(dimension, centerLocation, radius);

            // Higher chance to find something in major excavation
            const discoveryChance = Math.random();
            let discovery = null;

            if (discoveryChance < 0.25) { // 25% rare (increased)
                discovery = this.excavationRelics.find(site => site.rarity === 'rare');
            } else if (discoveryChance < 0.60) { // 35% uncommon (increased)
                discovery = this.excavationRelics.find(site => site.rarity === 'uncommon');
            } else if (discoveryChance < 0.90) { // 30% common (increased)
                discovery = this.excavationRelics.find(site => site.rarity === 'common');
            }
            // Only 10% chance of nothing (reduced from 25%)

            system.runTimeout(() => {
                if (discovery) {
                    this.processMajorRelicDiscovery(player, centerLocation, discovery);
                } else {
                    this.sendActionBar(player, `Excavation Complete | §7No major sites found | §eThis area has been thoroughly searched`, '§9');
                    this.createExcavationEffects(player, centerLocation, null);
                }
            }, 40);

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

    createExcavationSite(dimension, centerLocation, radius) {
        try {
            // Create a shallow excavated area
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= radius) {
                        const excavateLocation = {
                            x: Math.floor(centerLocation.x) + x,
                            y: Math.floor(centerLocation.y),
                            z: Math.floor(centerLocation.z) + z
                        };

                        // Remove surface block to create excavated look
                        dimension.runCommand(`setblock ${excavateLocation.x} ${excavateLocation.y} ${excavateLocation.z} air`);
                    }
                }
            }
        } catch (error) {
            // Error creating excavation site
        }
    },

    processMajorRelicDiscovery(player, location, discovery) {
        // Grant all rewards with delays
        discovery.rewards.forEach((itemId, index) => {
            system.runTimeout(() => {
                this.spawnMythrilItem(player.dimension, location, itemId);
            }, index * 8);
        });

        // Discovery message
        this.sendActionBar(player, `${discovery.name} | §e${discovery.message} | §a${discovery.rewards.length} valuable artifacts recovered`, '§b');

        // Discovery effects
        this.createMajorRelicDiscoveryEffects(player, location, discovery);

        // Delayed completion message
        system.runTimeout(() => {
            this.sendActionBar(player, `Major Archaeological Success | §aSignificant mythril cache catalogued | §2Exceptional discovery`, '§3');
        }, discovery.rewards.length * 8 + 20);
    },

    // NORMAL DIGGING: Enhanced mythril drops
    performArchaeologicalDig(player, location, blockType) {
        try {
            // Enhanced mythril drops for archaeological digging
            this.attemptArchaeologicalMythrilDrops(player, location, blockType);

            // Create digging effects
            this.createDigEffects(player, location, blockType);

            // Messages based on block type
            if (this.isExcavatableGround(blockType)) {
                this.sendActionBar(player, `Ground Excavated | §aSneak + Dig for major excavation | §eMythril-enhanced archaeology`, '§b');
            } else {
                this.sendActionBar(player, `Block Dug | §eMythril enhanced digging | §bChance for ancient materials`, '§9');
            }

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

    attemptArchaeologicalMythrilDrops(player, location, blockType) {
        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;

            // Enhanced chances for archaeological digging
            let dustChance = this.config.dustDropChance;
            let nuggetChance = this.config.nuggetDropChance;

            // Bonus for excavatable ground
            if (this.isExcavatableGround(blockType)) {
                dustChance *= 1.3;
                nuggetChance *= 1.4;
            }

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

                // Archaeological 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 archaeological 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, `Archaeological Nugget | §eAncient mythril fragment unearthed | §b${Math.round(nuggetChance * 100)}% chance`, '§b');
                }, 10);
            }

            if (droppedSomething) {
                system.runTimeout(() => {
                    this.sendActionBar(player, `Ancient Materials Found | §aMythril blessed by time | §2Continue archaeological work`, '§3');
                }, 5);
            }

        } catch (error) {
            world.sendMessage('§cDebug: Error in archaeological 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
    createSimpleRelicEffects(player, location, relic) {
        try {
            const particleCount = relic.rarity === 'rare' ? 12 : relic.rarity === 'uncommon' ? 8 : 5;
            const particleType = relic.rarity === 'rare' ? 'myw:mythril_particle_serpentine' :
                relic.rarity === 'uncommon' ? 'myw:mythril_particle' :
                    'myw:mythril_particle_minimalist';

            // Relic discovery particles
            for (let i = 0; i < particleCount; i++) {
                const angle = (i / particleCount) * Math.PI * 2;
                const radius = 1.5;

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

            // Upward burst
            for (let i = 0; i < 6; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle(particleType, {
                            x: location.x + (Math.random() - 0.5) * 0.6,
                            y: location.y + Math.random() * 2,
                            z: location.z + (Math.random() - 0.5) * 0.6
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

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

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

            // Subtle detection attempt particles
            for (let i = 0; i < 6; i++) {
                const angle = (i / 6) * Math.PI * 2;
                const radius = 1;

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

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

    createExcavationEffects(player, location, discovery) {
        try {
            const particleType = discovery ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';
            const particleCount = discovery ? 16 : 8;

            // Excavation dust cloud
            for (let i = 0; i < particleCount; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle(particleType, {
                            x: location.x + (Math.random() - 0.5) * 6,
                            y: location.y + Math.random() * 2,
                            z: location.z + (Math.random() - 0.5) * 6
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }
        } catch (error) {
            // Error creating excavation effects
        }
    },

    createMajorRelicDiscoveryEffects(player, location, discovery) {
        try {
            // Massive discovery particle burst
            for (let i = 0; i < 30; i++) {
                const angle = Math.random() * Math.PI * 2;
                const radius = Math.random() * 4;

                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle(discovery.particles, {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + Math.random() * 4,
                            z: location.z + Math.sin(angle) * radius
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

            // Central pillar effect
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    try {
                        player.dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + (Math.random() - 0.5) * 0.5,
                            y: location.y + i * 0.5,
                            z: location.z + (Math.random() - 0.5) * 0.5
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 5);
            }

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

    createDigEffects(player, location, blockType) {
        try {
            // Standard archaeological dig 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 dig effects
        }
    },

    // UTILITY FUNCTIONS
    isExcavatableGround(blockType) {
        const excavatableBlocks = [
            'minecraft:dirt', 'minecraft:grass_block', 'minecraft:coarse_dirt',
            'minecraft:sand', 'minecraft:red_sand', 'minecraft:gravel',
            'minecraft:clay', 'minecraft:podzol', 'minecraft:mycelium'
        ];
        return excavatableBlocks.includes(blockType);
    }
};

// Register shovel component
export function registerMythrilShovel(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_shovel', {
        onUse(eventData) {
            const { itemStack, source, useDuration } = eventData;
            ShovelSystem.handleShovelUse(source, itemStack, useDuration);
        },

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

        onHitEntity(eventData) {
            const { source, hitEntity } = eventData;
            if (source) {
                ShovelSystem.sendActionBar(source, 'Archaeological Warrior | §7Combat with ancient knowledge', '§b');
                ShovelSystem.createDigEffects(source, source.location, 'entity_hit');
            }
        }
    });
}

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

                if (mainhandItem?.typeId === 'myw:mythril_shovel') {
                    // Create subtle archaeological ambient effects
                    if (Math.random() > 0.97) { // 3% chance per tick
                        ShovelSystem.createArchaeologicalAmbientEffects(player);
                    }

                    // Show detection status occasionally
                    if (Math.random() > 0.995) { // 0.5% chance per tick
                        const lastDetection = player.getDynamicProperty('myw:last_relic_detection') || 0;
                        const detectionCooldown = Math.max(0, Math.ceil((ShovelSystem.config.relicDetectionCooldown * 50 - (Date.now() - lastDetection)) / 1000));
                        if (detectionCooldown > 0) {
                            ShovelSystem.sendActionBar(player, `Detection Ready In | §e${detectionCooldown}s | §bArchaeological senses recharging`, '§9');
                        } else {
                            ShovelSystem.sendActionBar(player, `Detection Ready | §aSneak + Use for relic detection | §bMythril archaeology available`, '§3');
                        }
                    }
                }
            });
        } catch (error) {
            // Error in passive detection
        }
    }, 20);

    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            ShovelSystem.sendActionBar(player, 'Mythril Archaeological Shovel | §aOnline | §eRelic Detection & Major Excavation', '§b');
        });
    }, 100);

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

// Archaeological ambient effects
ShovelSystem.createArchaeologicalAmbientEffects = function (player) {
    try {
        if (Math.random() > 0.4) return; // Reduce frequency

        const location = player.location;

        // Subtle archaeological 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
    }
};