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

// Import tool systems
import { registerMythrilSword, initializeSwordPassiveEffects } from './mythril_sword.js';
import { registerMythrilDrill, initializeDrillSystems } from './mythril_drill.js';
import { registerMythrilPickaxe, initializePickaxeSystems } from './mythril_pickaxe.js';
import { registerMythrilAxe, initializeAxeSystems } from './mythril_axe.js';
import { registerMythrilShovel, initializeShovelSystems } from './mythril_shovel.js';
import { registerMythrilHoe, initializeHoeSystems } from './mythril_hoe.js';

// Import special item systems
import { registerMythrilSimpleSpell, initializeSpellSystems } from './mythril_spell.js';
import { registerMythrilDust, initializeDustSystems } from './mythril_dust.js';
import { registerCarmotDust, initializeCarmotDustSystems } from './carmot_dust.js';

// Import enhanced projectile system
import { initializeMythrilNuggetSystem } from './mythril_nugget_effects.js';

// Import ritual system
import { initializeMythrilRituals } from './mythril_ritual_system.js';

// Import ancient staff
import { registerAncientMythrilStaff, initializeAncientStaffSystems } from './ancient_mythril_staff.js';

// Import ancient summon staff
import { registerAncientMythrilSummonStaff, initializeAncientSummonStaffSystems } from './ancient_mythril_summon_staff.js';

// Import ancient relic
import { registerAncientRelic, initializeAncientRelicSystem } from './ancient_mythril_relic.js';

// Import ancient rune system
import { registerAncientRuneSystem, initializeAncientRuneSystem } from './ancient_rune_system.js';

// Import temple rune system
import { registerTempleRuneSystem, initializeTempleRuneSystem } from './temple_rune_system.js';

// Import ancient essence system
import { registerAncientEssenceSystem, initializeAncientEssenceSystem } from './ancient_essence_system.js';

// Import Mythril armor systems
import {
    registerMythrilBoots,
    registerMythrilLeggings,
    registerMythrilChestplate,
    registerMythrilHelmet,
    registerMythrilCrown,
    initializeMythrilArmorSystems
} from './mythril_armor_system.js';

// Import Carmot armor systems
import {
    registerCarmotBoots,
    registerCarmotLeggings,
    registerCarmotChestplate,
    registerCarmotHelmet,
    registerCarmotCrown,
    initializeCarmotArmorSystems
} from './carmot_armor_system.js';

// Import Carmot sword systems
import { registerCarmotSword, initializeCarmotPassiveEffects } from './carmot_sword.js';

// Import Carmot pickaxe systems
import { registerCarmotPickaxe, initializeCarmotPickaxeSystems } from './carmot_pickaxe.js';

// Import Carmot axe systems
import { registerCarmotAxe, initializeCarmotAxeSystems } from './carmot_axe.js';

// Import Carmot shovel systems
import { registerCarmotShovel, initializeCarmotShovelSystems } from './carmot_shovel.js';

import { initializeMythrilDragonFlight } from './mythril_dragon_flight.js';

// Import Mystical Amulet System
import { registerAmuletsBag, initializeMysticalAmuletSystem } from './mystical_amulet_system.js';

// Import Mythril Fruit System
import { registerMythrilFruitComponents, initializeMythrilFruitSystem } from './mythril_fruit_system.js';

// Import Ancient Owl Combat System
import { initializeAncientOwlCombat } from './ancient_owl_combat.js';

// Import Fairy Constellation System
import { initializeFairyConstellationSystem } from './fairy_constellation_system.js';



// Component registration
world.beforeEvents.worldInitialize.subscribe(eventData => {
    // Register Mythril tools
    registerMythrilSword(eventData.itemComponentRegistry);
    registerMythrilDrill(eventData.itemComponentRegistry);
    registerMythrilPickaxe(eventData.itemComponentRegistry);
    registerMythrilAxe(eventData.itemComponentRegistry);
    registerMythrilShovel(eventData.itemComponentRegistry);
    registerMythrilHoe(eventData.itemComponentRegistry);

    // Register Mythril special items
    registerMythrilSimpleSpell(eventData.itemComponentRegistry);
    registerMythrilDust(eventData.itemComponentRegistry);
    registerCarmotDust(eventData.itemComponentRegistry);

    // Register Mythril armor
    registerMythrilBoots(eventData.itemComponentRegistry);
    registerMythrilLeggings(eventData.itemComponentRegistry);
    registerMythrilChestplate(eventData.itemComponentRegistry);
    registerMythrilHelmet(eventData.itemComponentRegistry);
    registerMythrilCrown(eventData.itemComponentRegistry);

    // Register ancient staff
    registerAncientMythrilStaff(eventData.itemComponentRegistry);

    // Register ancient summon staff
    registerAncientMythrilSummonStaff(eventData.itemComponentRegistry);
    
    // Register ancient relic
    registerAncientRelic(eventData.itemComponentRegistry);
    
    // Register ancient rune system
    registerAncientRuneSystem();
    
    // Register temple rune system
    registerTempleRuneSystem();
    
    // Register ancient essence system
    registerAncientEssenceSystem();

    // Register Carmot armor
    registerCarmotBoots(eventData.itemComponentRegistry);
    registerCarmotLeggings(eventData.itemComponentRegistry);
    registerCarmotChestplate(eventData.itemComponentRegistry);
    registerCarmotHelmet(eventData.itemComponentRegistry);
    registerCarmotCrown(eventData.itemComponentRegistry);

    // Register Carmot tools
    registerCarmotSword(eventData.itemComponentRegistry);
    registerCarmotPickaxe(eventData.itemComponentRegistry);
    registerCarmotAxe(eventData.itemComponentRegistry);
    registerCarmotShovel(eventData.itemComponentRegistry);

    // Register Mystical Amulet System
    registerAmuletsBag(eventData.itemComponentRegistry);

    // Register Mythril Fruit System
    registerMythrilFruitComponents(eventData.itemComponentRegistry);



    world.sendMessage('[OK] Mythril & Carmot - Components registered');
});

// System initialization
world.afterEvents.worldInitialize.subscribe(() => {
    // Initialize Mythril tool systems
    initializeSwordPassiveEffects();
    initializeDrillSystems();
    initializePickaxeSystems();
    initializeAxeSystems();
    initializeShovelSystems();
    initializeHoeSystems();

    // Initialize Mythril special item systems
    initializeSpellSystems();
    initializeDustSystems();
    initializeCarmotDustSystems();

    // Initialize Mythril armor systems
    initializeMythrilArmorSystems();

    // Initialize enhanced projectile effects
    initializeMythrilNuggetSystem();

    // Initialize ritual system
    initializeMythrilRituals();

    // Initialize ancient staff
    initializeAncientStaffSystems();

    // Initialize ancient summon staff
    initializeAncientSummonStaffSystems();
    
    // Initialize ancient relic
    initializeAncientRelicSystem();
    
    // Initialize ancient rune system
    initializeAncientRuneSystem();
    
    // Initialize temple rune system
    initializeTempleRuneSystem();
    
    // Initialize ancient essence system
    initializeAncientEssenceSystem();

    // Initialize Carmot armor systems
    initializeCarmotArmorSystems();

    // Initialize Carmot tool systems
    initializeCarmotPassiveEffects();
    initializeCarmotPickaxeSystems();
    initializeCarmotAxeSystems();
    initializeCarmotShovelSystems();

    initializeMythrilDragonFlight();

    // Initialize Mystical Amulet System
    initializeMysticalAmuletSystem();

    // Initialize Mythril Fruit System
    initializeMythrilFruitSystem();

    // Initialize Ancient Owl Combat System
    initializeAncientOwlCombat();

    // Initialize Fairy Constellation System
    initializeFairyConstellationSystem();

    world.sendMessage('§b═══════════════════════════════════════');
    world.sendMessage('§6     MYTHRIL & CARMOT SYSTEMS v2.5    ');
    world.sendMessage('§b═══════════════════════════════════════');
    world.sendMessage('§f[MYTHRIL] Traditional magic & power');
    world.sendMessage('§d[CARMOT] Gravitational manipulation');
    world.sendMessage('§3[MYTHRIL DRAGON] Enhanced tamed system');
    world.sendMessage('§e  • Advanced flight controls');
    world.sendMessage('§e  • Combat abilities while mounted');
    world.sendMessage('§e  • Special attacks & regeneration');
    world.sendMessage('§5[MYSTICAL AMULETS] Independent slot system');
    world.sendMessage('§e  • 2 mystical amulet slots');
    world.sendMessage('§e  • Access with Mystical Amulets Bag');
    world.sendMessage('§e  • Completely independent from other addons');
    world.sendMessage('§2[MEGA TREE SYSTEM] Ancient Mythril Tree Growth');
    world.sendMessage('§e  • Use bone meal on Ancient Mythril Sapplign');
    world.sendMessage('§e  • Creates spectacular mega tree');
    world.sendMessage('§e  • Native Minecraft Bedrock system');
    world.sendMessage('§a[MYTHRIL FRUITS] Consumable Ancient Fruits');
    world.sendMessage('§e  • Ancient Mythril Fruit: Nature & Healing powers');
    world.sendMessage('§e  • Golden Ancient Mythril Fruit: Divine & Power effects');
    world.sendMessage('§e  • Spectacular visual effects and transformations');
    world.sendMessage('§5[ANCIENT OWL] Combat Companion System');
    world.sendMessage('§e  • Mystic Bolt: Homing projectile attack');
    world.sendMessage('§e  • Wind Slash: AOE knockback ability');
    world.sendMessage('§e  • Feather Storm: Multi-projectile barrage');
    world.sendMessage('§e  • Night Aura: Buff allies during night');
    world.sendMessage('§d[FAIRY CONSTELLATIONS] Magical Formation System');
    world.sendMessage('§e  • Trinity/Harmony/Divine Constellations');
    world.sendMessage('§e  • Blessing Trails: Heal & buff players');
    world.sendMessage('§e  • Item Transformation: Magical alchemy');
    world.sendMessage('§e  • Dynamic Light Beams & Particle Effects');
    world.sendMessage('§aAll systems initialized successfully!');
    world.sendMessage('§b═══════════════════════════════════════');
});
// Enhanced API for both armor systems
export const ArmorSystemsAPI = {
    // Check Mythril power level
    getMythrilPowerLevel(player) {
        let powerLevel = 0;
        try {
            const equipment = player.getComponent('minecraft:equippable');

            const armorSlots = [
                EquipmentSlot.Head,
                EquipmentSlot.Chest,
                EquipmentSlot.Legs,
                EquipmentSlot.Feet
            ];

            armorSlots.forEach(slot => {
                const item = equipment?.getEquipment(slot);
                if (item && item.typeId.startsWith('myw:mythril_')) {
                    powerLevel++;

                    // Crown gives extra power
                    if (item.typeId === 'myw:mythril_crown') {
                        powerLevel++;
                    }
                }
            });

            // Check mainhand for tools/weapons
            const mainhand = equipment?.getEquipment(EquipmentSlot.Mainhand);
            if (mainhand && mainhand.typeId.startsWith('myw:mythril_')) {
                powerLevel++;
            }

        } catch (error) {
            // Error checking equipment
        }

        return powerLevel;
    },

    // Check Carmot energy level
    getCarmotEnergyLevel(player) {
        let energyLevel = 0;
        try {
            const equipment = player.getComponent('minecraft:equippable');

            const armorSlots = [
                EquipmentSlot.Head,
                EquipmentSlot.Chest,
                EquipmentSlot.Legs,
                EquipmentSlot.Feet
            ];

            armorSlots.forEach(slot => {
                const item = equipment?.getEquipment(slot);
                if (item && item.typeId.startsWith('myw:carmot_')) {
                    energyLevel++;

                    // Crown gives extra energy
                    if (item.typeId === 'myw:carmot_crown') {
                        energyLevel += 2;
                    }
                }
            });

        } catch (error) {
            // Error checking equipment
        }

        return energyLevel;
    },

    // Check which armor type player is wearing
    getArmorType(player) {
        try {
            const equipment = player.getComponent('minecraft:equippable');
            const chest = equipment?.getEquipment(EquipmentSlot.Chest);

            if (chest) {
                if (chest.typeId.includes('mythril')) return 'mythril';
                if (chest.typeId.includes('carmot')) return 'carmot';
            }
        } catch { }

        return 'none';
    },

    // Check for mixed armor (not recommended)
    hasMixedArmor(player) {
        try {
            const equipment = player.getComponent('minecraft:equippable');
            let hasMythril = false;
            let hasCarmot = false;

            const armorSlots = [
                EquipmentSlot.Head,
                EquipmentSlot.Chest,
                EquipmentSlot.Legs,
                EquipmentSlot.Feet
            ];

            armorSlots.forEach(slot => {
                const item = equipment?.getEquipment(slot);
                if (item) {
                    if (item.typeId.includes('mythril')) hasMythril = true;
                    if (item.typeId.includes('carmot')) hasCarmot = true;
                }
            });

            return hasMythril && hasCarmot;
        } catch {
            return false;
        }
    },

    // Get combined power rating
    getTotalPowerRating(player) {
        return this.getMythrilPowerLevel(player) + this.getCarmotEnergyLevel(player);
    }
};

// Synergy system for combining armors (optional)
const ArmorSynergySystem = {
    checkSynergy(player) {
        const api = ArmorSystemsAPI;

        if (api.hasMixedArmor(player)) {
            // Mixed armor penalty
            player.addEffect('weakness', 100, {
                amplifier: 0,
                showParticles: false
            });

            if (world.getAbsoluteTime() % 100 === 0) {
                this.showWarning(player);
            }
        } else {
            const armorType = api.getArmorType(player);

            if (armorType === 'mythril') {
                const power = api.getMythrilPowerLevel(player);
                if (power >= 5) {
                    // Full Mythril set bonus
                    player.setDynamicProperty('armor:bonus_type', 'mythril_complete');
                }
            } else if (armorType === 'carmot') {
                const energy = api.getCarmotEnergyLevel(player);
                if (energy >= 6) {
                    // Full Carmot set bonus
                    player.setDynamicProperty('armor:bonus_type', 'carmot_complete');
                }
            }
        }
    },

    showWarning(player) {
        try {
            player.onScreenDisplay.setActionBar(
                '§c⚠ WARNING: Mixed armor types detected! Synergy compromised ⚠'
            );
        } catch { }
    }
};

// Global armor interaction system
system.runInterval(() => {
    try {
        world.getAllPlayers().forEach(player => {
            // Check for armor synergy/conflicts
            ArmorSynergySystem.checkSynergy(player);

            // Special interaction: Mythril vs Carmot nearby
            const nearbyPlayers = player.dimension.getEntities({
                location: player.location,
                maxDistance: 20,
                families: ['player']
            });

            nearbyPlayers.forEach(other => {
                if (other.id !== player.id) {
                    const myArmor = ArmorSystemsAPI.getArmorType(player);
                    const theirArmor = ArmorSystemsAPI.getArmorType(other);

                    // Resonance between same armor types
                    if (myArmor === theirArmor && myArmor !== 'none') {
                        if (world.getAbsoluteTime() % 100 === 0) {
                            player.addEffect('regeneration', 100, {
                                amplifier: 0,
                                showParticles: false
                            });
                        }
                    }

                    // Dimensional interference between different types
                    if (myArmor === 'mythril' && theirArmor === 'carmot') {
                        if (world.getAbsoluteTime() % 200 === 0) {
                            // Create interference effect
                            const midpoint = {
                                x: (player.location.x + other.location.x) / 2,
                                y: (player.location.y + other.location.y) / 2 + 1,
                                z: (player.location.z + other.location.z) / 2
                            };

                            player.dimension.spawnParticle('minecraft:dragon_breath_trail', midpoint);
                        }
                    }
                }
            });
        });
    } catch (error) {
        // Handle errors silently
    }
}, 100); // Every 5 seconds

// Performance monitoring
let performanceCounter = 0;
system.runInterval(() => {
    performanceCounter++;

    if (performanceCounter >= 1200) { // Every minute
        performanceCounter = 0;

        const playerCount = world.getAllPlayers().length;
        let mythrilUsers = 0;
        let carmotUsers = 0;

        world.getAllPlayers().forEach(player => {
            const armorType = ArmorSystemsAPI.getArmorType(player);
            if (armorType === 'mythril') mythrilUsers++;
            if (armorType === 'carmot') carmotUsers++;
        });

        if (playerCount > 0) {
            world.sendMessage(`§7[System Status] Players: ${playerCount} | Mythril: ${mythrilUsers} | Carmot: ${carmotUsers}`);
        }
    }
}, 20); // Every second


// Export the enhanced API
export { ArmorSystemsAPI as default };