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

export function initializeMythrilDragonFlight() {
    // Variables para controlar el estado de vuelo y ataque
    const flightData = new Map();
    const attackCooldowns = new Map();

    // Sistema principal de vuelo del dragón
    system.runInterval(() => {
        const allPlayers = world.getAllPlayers();

        for (const player of allPlayers) {
            const ridingEntity = player.getComponent("riding")?.entityRidingOn;

            // Solo procesar si está montando un dragón Mythril
            if (ridingEntity?.typeId === "myw:mythril_dragon") {
                const entityId = ridingEntity.id;

                // Inicializar datos de vuelo si no existen
                if (!flightData.has(entityId)) {
                    flightData.set(entityId, {
                        verticalSpeed: 0,
                        isAscending: false,
                        lastJumpState: false,
                        lastAttackTime: 0
                    });
                }

                const data = flightData.get(entityId);
                const currentJumping = player.isJumping;

                // Detectar cambio en el estado de salto
                if (currentJumping && !data.lastJumpState) {
                    // Iniciar ascenso
                    data.isAscending = true;
                } else if (!currentJumping && data.lastJumpState) {
                    // Detener ascenso
                    data.isAscending = false;
                }

                data.lastJumpState = currentJumping;

                // Control de velocidad vertical
                if (data.isAscending) {
                    // Ascender suavemente
                    data.verticalSpeed = Math.min(data.verticalSpeed + 0.01, 0.1);
                } else {
                    // Descender suavemente
                    data.verticalSpeed = Math.max(data.verticalSpeed - 0.01, -0.06);
                }

                // Control de dirección basado en la mirada del jugador
                const viewDirection = player.getViewDirection();

                // Aplicar impulso en la dirección de la mirada (solo horizontal)
                const horizontalMultiplier = 0.08;
                ridingEntity.applyImpulse({
                    x: viewDirection.x * horizontalMultiplier,
                    y: data.verticalSpeed,
                    z: viewDirection.z * horizontalMultiplier
                });

                // Rotar el dragón para que mire en la misma dirección que el jugador
                try {
                    ridingEntity.rotation = {
                        x: player.rotation.x,
                        y: player.rotation.y
                    };
                } catch (error) {
                    // Fallback en caso de error
                    console.error("Error al rotar el dragón:", error);
                }

                // Sistema de ataque con click izquierdo
                const currentTime = Date.now();
                if (player.isSneaking && currentTime - data.lastAttackTime > 2000) {
                    data.lastAttackTime = currentTime;

                    // Lanzar proyectil de mythril
                    const projectilePos = {
                        x: ridingEntity.location.x + viewDirection.x * 2,
                        y: ridingEntity.location.y + 1,
                        z: ridingEntity.location.z + viewDirection.z * 2
                    };

                    try {
                        const projectile = player.dimension.spawnEntity("myw:mythril_ball", projectilePos);
                        if (projectile) {
                            // Aplicar velocidad al proyectil
                            const projectileVelocity = {
                                x: viewDirection.x * 2,
                                y: viewDirection.y * 2,
                                z: viewDirection.z * 2
                            };
                            projectile.applyImpulse(projectileVelocity);

                            // Efectos de sonido y partículas
                            player.dimension.playSound("random.explode", ridingEntity.location);

                            // Efectos visuales de ataque
                            for (let i = 0; i < 5; i++) {
                                const attackParticlePos = {
                                    x: projectilePos.x + (Math.random() - 0.5),
                                    y: projectilePos.y + (Math.random() - 0.5),
                                    z: projectilePos.z + (Math.random() - 0.5)
                                };

                                try {
                                    player.dimension.spawnParticle("myw:mythril_attack", attackParticlePos);
                                } catch (error) {
                                    player.dimension.spawnParticle("minecraft:explosion_emitter", attackParticlePos);
                                }
                            }
                        }
                    } catch (error) {
                        // Fallback si el proyectil no existe
                        player.dimension.spawnParticle("minecraft:explosion_emitter", projectilePos);
                    }
                }

                // Efectos visuales de vuelo mejorados
                if (!ridingEntity.isOnGround) {
                    // Partículas de vuelo principales
                    const mainParticleLocation = {
                        x: ridingEntity.location.x,
                        y: ridingEntity.location.y - 1.0,
                        z: ridingEntity.location.z
                    };

                    try {
                        // Partículas de estela
                        for (let i = 0; i < 3; i++) {
                            const trailPos = {
                                x: mainParticleLocation.x + (Math.random() - 0.5) * 3,
                                y: mainParticleLocation.y + (Math.random() - 0.5) * 1.5,
                                z: mainParticleLocation.z + (Math.random() - 0.5) * 3
                            };
                            player.dimension.spawnParticle("myw:mythril_flight_particle", trailPos);
                        }

                        // Partículas de alas
                        const wingOffset = Math.sin(currentTime / 200) * 0.3;
                        const leftWingLocation = {
                            x: ridingEntity.location.x - 1.5,
                            y: ridingEntity.location.y - 0.5 + wingOffset,
                            z: ridingEntity.location.z
                        };
                        const rightWingLocation = {
                            x: ridingEntity.location.x + 1.5,
                            y: ridingEntity.location.y - 0.5 + wingOffset,
                            z: ridingEntity.location.z
                        };

                        player.dimension.spawnParticle("myw:mythril_particle", leftWingLocation);
                        player.dimension.spawnParticle("myw:mythril_particle", rightWingLocation);

                        // Partículas de respiración
                        const breathLocation = {
                            x: ridingEntity.location.x + viewDirection.x * 3,
                            y: ridingEntity.location.y + 0.5,
                            z: ridingEntity.location.z + viewDirection.z * 3
                        };

                        try {
                            player.dimension.spawnParticle("myw:mythril_breath", breathLocation);
                        } catch (error) {
                            player.dimension.spawnParticle("minecraft:dragon_breath", breathLocation);
                        }
                    } catch (error) {
                        // Partículas por defecto
                        player.dimension.spawnParticle("minecraft:dragon_breath", mainParticleLocation);
                    }
                }

                flightData.set(entityId, data);
            }
        }
    }, 1);

    // Sistema de efectos especiales
    system.runInterval(() => {
        const allPlayers = world.getAllPlayers();

        for (const player of allPlayers) {
            const ridingEntity = player.getComponent("riding")?.entityRidingOn;

            if (ridingEntity?.typeId === "myw:mythril_dragon") {
                // Efecto de regeneración mientras se vuela
                if (!ridingEntity.isOnGround) {


                    // Efecto de aura mítica
                    const auraLocation = {
                        x: ridingEntity.location.x,
                        y: ridingEntity.location.y - 0.5,
                        z: ridingEntity.location.z
                    };

                    try {
                        player.dimension.spawnParticle("myw:mythril_aura", auraLocation);
                    } catch (error) {
                        player.dimension.spawnParticle("minecraft:enchanted_hit", auraLocation);
                    }
                }

                // Efecto de resistencia constante
                player.addEffect("resistance", 5, { amplifier: 0, showParticles: false });
            }
        }
    }, 20);

    // Limpiar datos de entidades que ya no existen
    system.runInterval(() => {
        const allEntities = world.getDimension("overworld").getEntities({ type: "myw:mythril_dragon" });
        const existingIds = new Set(allEntities.map(e => e.id));

        for (const [id] of flightData) {
            if (!existingIds.has(id)) {
                flightData.delete(id);
            }
        }
    }, 200);

    world.sendMessage('§6[Mythril Dragon Flight] Sistema de vuelo mejorado con rotación y ataque');
}