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

export const AncientOwlCombatSystem = {
    config: {
        // Proyectil místico
        mysticBolt: {
            damage: 6,
            cooldown: 60, // 3 segundos
            range: 20,
            speed: 1.5,
            homingStrength: 0.3
        },
        
        // Ataque de viento
        windSlash: {
            damage: 4,
            knockback: 1.5,
            cooldown: 40, // 2 segundos
            radius: 3
        },
        
        // Aura nocturna (de noche)
        nightAura: {
            radius: 8,
            healAmount: 2,
            duration: 100,
            cooldown: 200 // 10 segundos
        },
        
        // Tormenta de plumas
        featherStorm: {
            damage: 3,
            projectileCount: 8,
            cooldown: 100, // 5 segundos
            range: 15
        }
    },

    owlStates: new Map(),
    activeProjectiles: new Set(),

    // Inicializar sistema
    initialize() {
        // Sistema de combate del búho (más frecuente para mejor detección)
        system.runInterval(() => {
            try {
                world.getDimension('overworld').getEntities({
                    type: 'myw:ancient_mythril_owl'
                }).forEach(owl => {
                    this.updateOwlCombat(owl);
                });
            } catch (error) {
                // Error en update
            }
        }, 5); // Cambio de 10 a 5 para mejor respuesta

        // Sistema de proyectiles activos
        system.runInterval(() => {
            this.updateActiveProjectiles();
        }, 1);

        world.sendMessage('§5[ANCIENT OWL] §dCombat System initialized - Mystic abilities ready');
    },

    // Actualizar estado de combate del búho
    updateOwlCombat(owl) {
        try {
            if (!owl.isValid()) return;

            // Verificar si está tameado - TODAS las formas posibles
            const isTamed = owl.hasTag('tamed') || 
                           owl.hasTag('owl_combat') ||
                           this.checkIfTamed(owl) ||
                           this.hasOwner(owl);
            
            if (!isTamed) return;

            const owlId = owl.id;
            let state = this.owlStates.get(owlId) || this.createOwlState(owlId);

            // Obtener objetivo actual con búsqueda más agresiva
            const target = this.findOwlTarget(owl);
            
            if (target && target.isValid()) {
                const distance = this.getDistance(owl.location, target.location);
                const currentTick = system.currentTick;
                
                // Sistema de ataque - Los ataques mágicos son adicionales al melee
                if (distance > 6 && currentTick - state.lastBoltTime > this.config.mysticBolt.cooldown) {
                    // Ataque a distancia: Rayo místico
                    this.shootMysticBolt(owl, target, state);
                    state.lastBoltTime = currentTick;
                } else if (distance > 3 && distance <= 10 && currentTick - state.lastStormTime > this.config.featherStorm.cooldown) {
                    // Ataque medio: Tormenta de plumas
                    this.executeFeatherStorm(owl, target, state);
                    state.lastStormTime = currentTick;
                } else if (distance <= 5 && currentTick - state.lastSlashTime > this.config.windSlash.cooldown) {
                    // Ataque cercano: Corte de viento
                    this.executeWindSlash(owl, target, state);
                    state.lastSlashTime = currentTick;
                }
                // El búho también usará melee_attack del behavior nativo

                // Efectos de combate visual (reducidos)
                if (system.currentTick % 20 === 0) {
                    this.createCombatAura(owl, target);
                }
            }

            // Aura de noche para el dueño
            const isNight = this.isNightTime(owl.dimension);
            if (isNight && system.currentTick - state.lastAuraTime > this.config.nightAura.cooldown) {
                this.activateNightAura(owl, state);
                state.lastAuraTime = system.currentTick;
            }

            this.owlStates.set(owlId, state);

        } catch (error) {
            // Error en combat update
        }
    },

    // ATAQUE 1: Rayo Místico Teledirigido
    shootMysticBolt(owl, target, state) {
        try {
            const dimension = owl.dimension;
            const startLocation = {
                x: owl.location.x,
                y: owl.location.y + 0.5,
                z: owl.location.z
            };

            // Calcular dirección inicial
            const direction = this.getDirectionToTarget(startLocation, target.location);
            
            const projectileData = {
                id: `bolt_${Date.now()}_${Math.random()}`,
                owner: owl,
                target: target,
                location: { ...startLocation },
                velocity: {
                    x: direction.x * this.config.mysticBolt.speed,
                    y: direction.y * this.config.mysticBolt.speed,
                    z: direction.z * this.config.mysticBolt.speed
                },
                damage: this.config.mysticBolt.damage,
                age: 0,
                maxAge: 100,
                dimension: dimension
            };

            this.activeProjectiles.add(projectileData);

            // Efectos de lanzamiento
            this.createBoltLaunchEffects(dimension, startLocation);

            // Sonido místico
            try {
                dimension.playSound('mob.evocation_illager.prepare_attack', startLocation, {
                    volume: 0.5,
                    pitch: 1.5
                });
            } catch (e) { }

        } catch (error) {
            // Error lanzando rayo
        }
    },

    // ATAQUE 2: Corte de Viento (AOE cercano)
    executeWindSlash(owl, target, state) {
        try {
            const dimension = owl.dimension;
            const origin = owl.location;
            const radius = this.config.windSlash.radius;

            // Crear onda de viento en espiral
            for (let ring = 0; ring < 3; ring++) {
                system.runTimeout(() => {
                    const ringRadius = radius * ((ring + 1) / 3);
                    const particleCount = 16 + ring * 8;

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        const particleLocation = {
                            x: origin.x + Math.cos(angle) * ringRadius,
                            y: origin.y + 0.5 + Math.random() * 0.5,
                            z: origin.z + Math.sin(angle) * ringRadius
                        };

                        dimension.spawnParticle('myw:mythril_particle_minimalist', particleLocation);
                    }
                }, ring * 2);
            }

            // Daño y knockback a enemigos cercanos
            const nearbyEntities = dimension.getEntities({
                location: origin,
                maxDistance: radius,
                excludeTypes: ['minecraft:item']
            });

            nearbyEntities.forEach(entity => {
                if (entity.id === owl.id) return;
                if (this.isHostileEntity(entity)) {
                    try {
                        // Daño
                        entity.applyDamage(this.config.windSlash.damage, {
                            cause: EntityDamageCause.magic
                        });

                        // Knockback radial
                        const knockDir = {
                            x: entity.location.x - origin.x,
                            y: 0.5,
                            z: entity.location.z - origin.z
                        };
                        const dist = Math.sqrt(knockDir.x ** 2 + knockDir.z ** 2);
                        if (dist > 0) {
                            entity.applyKnockback(
                                knockDir.x / dist,
                                knockDir.z / dist,
                                this.config.windSlash.knockback,
                                0.5
                            );
                        }

                        // Partículas de impacto
                        this.createWindImpactEffect(dimension, entity.location);
                    } catch (e) { }
                }
            });

            // Sonido
            try {
                dimension.playSound('mob.phantom.flap', origin, {
                    volume: 1.0,
                    pitch: 0.8
                });
            } catch (e) { }

        } catch (error) {
            // Error en wind slash
        }
    },

    // ATAQUE 3: Tormenta de Plumas
    executeFeatherStorm(owl, target, state) {
        try {
            const dimension = owl.dimension;
            const origin = owl.location;
            const projectileCount = this.config.featherStorm.projectileCount;

            // Lanzar múltiples proyectiles en patrón circular
            for (let i = 0; i < projectileCount; i++) {
                system.runTimeout(() => {
                    const angle = (i / projectileCount) * Math.PI * 2;
                    const spread = 0.3;
                    
                    // Dirección hacia el objetivo con spread
                    const baseDir = this.getDirectionToTarget(origin, target.location);
                    const direction = {
                        x: baseDir.x + (Math.cos(angle) * spread),
                        y: baseDir.y + (Math.random() - 0.5) * spread,
                        z: baseDir.z + (Math.sin(angle) * spread)
                    };

                    const featherData = {
                        id: `feather_${Date.now()}_${i}`,
                        owner: owl,
                        location: { ...origin, y: origin.y + 0.5 },
                        velocity: {
                            x: direction.x * 1.2,
                            y: direction.y * 1.2,
                            z: direction.z * 1.2
                        },
                        damage: this.config.featherStorm.damage,
                        age: 0,
                        maxAge: 60,
                        dimension: dimension,
                        isFeather: true
                    };

                    this.activeProjectiles.add(featherData);

                    // Partículas de lanzamiento
                    dimension.spawnParticle('minecraft:critical_hit_emitter', {
                        x: origin.x,
                        y: origin.y + 0.5,
                        z: origin.z
                    });

                }, i * 2);
            }

            // Efecto visual central
            this.createStormCenterEffect(dimension, origin);

            // Sonido
            try {
                dimension.playSound('mob.phantom.bite', origin, {
                    volume: 0.8,
                    pitch: 1.2
                });
            } catch (e) { }

        } catch (error) {
            // Error en feather storm
        }
    },

    // HABILIDAD 4: Aura Nocturna (buff para el dueño de noche)
    activateNightAura(owl, state) {
        try {
            const dimension = owl.dimension;
            const origin = owl.location;
            const radius = this.config.nightAura.radius;

            // Encontrar al dueño
            const owner = this.findOwlOwner(owl);
            if (!owner || !owner.isValid()) return;

            const distance = this.getDistance(owl.location, owner.location);
            if (distance > radius) return;

            // Buffs nocturnos
            owner.addEffect('regeneration', this.config.nightAura.duration, {
                amplifier: 0,
                showParticles: false
            });
            
            owner.addEffect('night_vision', this.config.nightAura.duration, {
                amplifier: 0,
                showParticles: false
            });
            
            owner.addEffect('speed', this.config.nightAura.duration, {
                amplifier: 0,
                showParticles: false
            });

            // Efectos visuales de aura
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const dist = Math.random() * radius;
                    const height = Math.random() * 3;

                    const particleLocation = {
                        x: origin.x + Math.cos(angle) * dist,
                        y: origin.y + height,
                        z: origin.z + Math.sin(angle) * dist
                    };

                    dimension.spawnParticle('myw:mythril_particle_minimalist', particleLocation);
                }, i * 3);
            }

            // Mensaje
            try {
                owner.onScreenDisplay.setActionBar('§5✦ §dNight Aura §8▸ §bOwl protection activated');
            } catch (e) { }

            // Sonido
            try {
                dimension.playSound('beacon.power', origin, {
                    volume: 0.3,
                    pitch: 1.5
                });
            } catch (e) { }

        } catch (error) {
            // Error en night aura
        }
    },

    // Sistema de actualización de proyectiles
    updateActiveProjectiles() {
        const projectilesToRemove = new Set();

        this.activeProjectiles.forEach(projectile => {
            try {
                if (!projectile.dimension) {
                    projectilesToRemove.add(projectile);
                    return;
                }

                projectile.age++;

                // Eliminar proyectiles viejos
                if (projectile.age >= projectile.maxAge) {
                    this.createProjectileExplosion(projectile);
                    projectilesToRemove.add(projectile);
                    return;
                }

                // Actualizar posición
                projectile.location.x += projectile.velocity.x;
                projectile.location.y += projectile.velocity.y;
                projectile.location.z += projectile.velocity.z;

                // Homing para rayos místicos
                if (!projectile.isFeather && projectile.target && projectile.target.isValid()) {
                    this.applyHoming(projectile);
                }

                // Trail de partículas
                this.createProjectileTrail(projectile);

                // Check colisiones
                if (this.checkProjectileCollision(projectile)) {
                    projectilesToRemove.add(projectile);
                }

            } catch (error) {
                projectilesToRemove.add(projectile);
            }
        });

        // Limpiar proyectiles terminados
        projectilesToRemove.forEach(p => this.activeProjectiles.delete(p));
    },

    // Aplicar homing a proyectil
    applyHoming(projectile) {
        try {
            const targetLoc = projectile.target.location;
            const toTarget = {
                x: targetLoc.x - projectile.location.x,
                y: (targetLoc.y + 1) - projectile.location.y,
                z: targetLoc.z - projectile.location.z
            };

            const distance = Math.sqrt(toTarget.x ** 2 + toTarget.y ** 2 + toTarget.z ** 2);
            if (distance > 0) {
                const homingStrength = this.config.mysticBolt.homingStrength;
                projectile.velocity.x += (toTarget.x / distance) * homingStrength;
                projectile.velocity.y += (toTarget.y / distance) * homingStrength;
                projectile.velocity.z += (toTarget.z / distance) * homingStrength;

                // Normalizar velocidad
                const speed = Math.sqrt(
                    projectile.velocity.x ** 2 + 
                    projectile.velocity.y ** 2 + 
                    projectile.velocity.z ** 2
                );
                if (speed > this.config.mysticBolt.speed * 1.5) {
                    const factor = (this.config.mysticBolt.speed * 1.5) / speed;
                    projectile.velocity.x *= factor;
                    projectile.velocity.y *= factor;
                    projectile.velocity.z *= factor;
                }
            }
        } catch (error) {
            // Error en homing
        }
    },

    // Check colisión de proyectil
    checkProjectileCollision(projectile) {
        try {
            const entities = projectile.dimension.getEntities({
                location: projectile.location,
                maxDistance: 1.5,
                excludeTypes: ['minecraft:item']
            });

            for (const entity of entities) {
                if (entity.id === projectile.owner.id) continue;
                
                if (this.isHostileEntity(entity)) {
                    // Aplicar daño
                    entity.applyDamage(projectile.damage, {
                        cause: EntityDamageCause.magic,
                        damagingEntity: projectile.owner
                    });

                    // Efecto de impacto
                    this.createProjectileImpact(projectile, entity.location);
                    
                    return true;
                }
            }

            // Check colisión con bloques
            try {
                const block = projectile.dimension.getBlock(projectile.location);
                if (block && !block.isAir && block.isSolid) {
                    this.createProjectileExplosion(projectile);
                    return true;
                }
            } catch (e) { }

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

        return false;
    },

    // ==================== EFECTOS VISUALES ====================

    createProjectileTrail(projectile) {
        try {
            const particleType = projectile.isFeather ? 
                'minecraft:critical_hit_emitter' : 
                'myw:mythril_particle';

            projectile.dimension.spawnParticle(particleType, projectile.location);

            // Partículas adicionales para rayos místicos
            if (!projectile.isFeather && projectile.age % 3 === 0) {
                projectile.dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: projectile.location.x + (Math.random() - 0.5) * 0.5,
                    y: projectile.location.y + (Math.random() - 0.5) * 0.5,
                    z: projectile.location.z + (Math.random() - 0.5) * 0.5
                });
            }
        } catch (e) { }
    },

    createProjectileImpact(projectile, location) {
        try {
            const dimension = projectile.dimension;
            
            // Explosión de partículas en el impacto
            for (let i = 0; i < 15; i++) {
                const angle = (i / 15) * Math.PI * 2;
                const radius = 1.0;
                
                dimension.spawnParticle('myw:mythril_particle', {
                    x: location.x + Math.cos(angle) * radius,
                    y: location.y + 1,
                    z: location.z + Math.sin(angle) * radius
                });
            }

            // Sonido de impacto
            dimension.playSound('random.explode', location, {
                volume: 0.3,
                pitch: 1.5
            });

        } catch (e) { }
    },

    createProjectileExplosion(projectile) {
        try {
            const dimension = projectile.dimension;
            const location = projectile.location;

            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                dimension.spawnParticle('minecraft:lava_particle', {
                    x: location.x + Math.cos(angle) * 0.5,
                    y: location.y,
                    z: location.z + Math.sin(angle) * 0.5
                });
            }
        } catch (e) { }
    },

    createBoltLaunchEffects(dimension, location) {
        try {
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: location.x + Math.cos(angle) * 0.5,
                    y: location.y,
                    z: location.z + Math.sin(angle) * 0.5
                });
            }
        } catch (e) { }
    },

    createWindImpactEffect(dimension, location) {
        try {
            for (let i = 0; i < 5; i++) {
                dimension.spawnParticle('minecraft:wind_explosion_emitter', {
                    x: location.x + (Math.random() - 0.5),
                    y: location.y + Math.random(),
                    z: location.z + (Math.random() - 0.5)
                });
            }
        } catch (e) { }
    },

    createStormCenterEffect(dimension, location) {
        try {
            for (let i = 0; i < 12; i++) {
                const angle = (i / 12) * Math.PI * 2;
                const radius = 1.5;
                dimension.spawnParticle('myw:mythril_particle', {
                    x: location.x + Math.cos(angle) * radius,
                    y: location.y + 0.5,
                    z: location.z + Math.sin(angle) * radius
                });
            }
        } catch (e) { }
    },

    createCombatAura(owl, target) {
        try {
            // Aura muy reducida
            if (Math.random() > 0.3) return; // 30% de probabilidad solo cuando se llama
            
            const dimension = owl.dimension;
            const location = owl.location;
            
            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                x: location.x + (Math.random() - 0.5) * 0.5,
                y: location.y + Math.random() * 0.5,
                z: location.z + (Math.random() - 0.5) * 0.5
            });
        } catch (e) { }
    },

    // ==================== UTILIDADES ====================

    createOwlState(owlId) {
        return {
            id: owlId,
            lastBoltTime: 0,
            lastSlashTime: 0,
            lastStormTime: 0,
            lastAuraTime: 0,
            comboCount: 0
        };
    },

    findOwlTarget(owl) {
        try {
            // Buscar enemigos más activamente
            const nearbyEntities = owl.dimension.getEntities({
                location: owl.location,
                maxDistance: 25,
                excludeTypes: ['minecraft:item']
            });

            let closestEnemy = null;
            let closestDistance = 999;

            for (const entity of nearbyEntities) {
                if (entity.id === owl.id) continue;
                
                // Verificar si es hostil
                if (this.isHostileEntity(entity)) {
                    const distance = this.getDistance(owl.location, entity.location);
                    if (distance < closestDistance) {
                        closestDistance = distance;
                        closestEnemy = entity;
                    }
                }
            }

            return closestEnemy;
        } catch (e) {
            return null;
        }
    },

    findOwlOwner(owl) {
        try {
            const players = world.getAllPlayers();
            for (const player of players) {
                const distance = this.getDistance(owl.location, player.location);
                if (distance < 30) {
                    return player;
                }
            }
        } catch (e) { }
        return null;
    },

    checkIfTamed(owl) {
        try {
            // Múltiples formas de verificar si está tameado
            const hasTamedProperty = owl.getDynamicProperty('tamed') === true;
            const hasTamedComponent = owl.getComponent('minecraft:is_tamed') !== undefined;
            
            return hasTamedProperty || hasTamedComponent;
        } catch (e) {
            return false;
        }
    },

    hasOwner(owl) {
        try {
            // Ver si tiene el componente is_tamed
            const tamedComponent = owl.getComponent('minecraft:is_tamed');
            return tamedComponent !== undefined;
        } catch (e) {
            return false;
        }
    },

    isHostileEntity(entity) {
        const hostileTypes = [
            'zombie', 'skeleton', 'creeper', 'spider', 'enderman', 'witch',
            'slime', 'magma_cube', 'blaze', 'ghast', 'piglin', 'hoglin',
            'zoglin', 'phantom', 'drowned', 'husk', 'stray', 'wither',
            'evoker', 'vindicator', 'pillager', 'ravager', 'vex'
        ];
        
        // Verificar si el tipo de entidad incluye algún tipo hostil
        const isHostileType = hostileTypes.some(type => entity.typeId.includes(type));
        
        // También verificar familia monster
        try {
            const families = entity.getComponent('minecraft:type_family');
            if (families && families.hasTypeFamily('monster')) {
                return true;
            }
        } catch (e) { }
        
        return isHostileType;
    },

    isNightTime(dimension) {
        try {
            const time = world.getTimeOfDay();
            return time >= 13000 && time < 23000;
        } catch (e) {
            return false;
        }
    },

    getDistance(loc1, loc2) {
        return Math.sqrt(
            (loc1.x - loc2.x) ** 2 +
            (loc1.y - loc2.y) ** 2 +
            (loc1.z - loc2.z) ** 2
        );
    },

    getDirectionToTarget(from, to) {
        const dx = to.x - from.x;
        const dy = to.y - from.y;
        const dz = to.z - from.z;
        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
        
        if (distance === 0) return { x: 0, y: 0, z: 0 };
        
        return {
            x: dx / distance,
            y: dy / distance,
            z: dz / distance
        };
    }
};

// Exportar función de inicialización
export function initializeAncientOwlCombat() {
    AncientOwlCombatSystem.initialize();
    return AncientOwlCombatSystem;
}

