// Companion Abilities Script
// Handles special abilities for different companion types

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

const COMPANION_ABILITIES = {
    dragon: {
        name: "Fire Breath",
        cooldown: 10,
        range: 8,
        damage: 12
    },
    phoenix: {
        name: "Flame Burst",
        cooldown: 15,
        range: 6,
        healing: 6
    },
    wolf: {
        name: "Pack Call",
        cooldown: 20,
        range: 10,
        summons: 3
    },
    tiger: {
        name: "Pounce Strike",
        cooldown: 8,
        range: 5,
        damage: 10
    },
    leopard: {
        name: "Shadow Dash",
        cooldown: 12,
        range: 7,
        damage: 8
    },
    elephant: {
        name: "Earthquake Stomp",
        cooldown: 15,
        range: 8,
        knockback: 5
    },
    fox: {
        name: "Illusion Burst",
        cooldown: 10,
        range: 6,
        illusions: 4
    },
    panda: {
        name: "Bamboo Shield",
        cooldown: 18,
        range: 5,
        duration: 10
    },
    red_panda: {
        name: "Acrobatic Strike",
        cooldown: 9,
        range: 4,
        damage: 6
    },
    manta_ray: {
        name: "Tidal Wave",
        cooldown: 14,
        range: 9,
        knockback: 4
    }
};

// Global companion abilities and cooldown tracking
const companionCooldowns = new Map();
const activeSpecialAttacks = new Set(); // Track companions currently in special attack state

// Listen for companion ability script events
system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id === "aft_soulhunters:companion_special_ability") {
        handleSpecialAbility(event.sourceEntity);
    } else if (event.id === "aft_soulhunters:companion_scream_ability") {
        handleScreamAbility(event.sourceEntity);
    } else if (event.id === "aft_soulhunters:companion_attack_sound") {
        // Handle attack sound and schedule reset
        if (event.sourceEntity) {
            const attackState = event.sourceEntity.getProperty("aft_soulhunters:attack_state");
            
            // Schedule attack state reset based on attack type
            let resetDelay = 20; // Default 1 second (20 ticks)
            if (attackState === "special") {
                resetDelay = 40; // 2 seconds for special attacks
            } else if (attackState === "scream") {
                resetDelay = 50; // 2.5 seconds for scream
            }
            
            system.runTimeout(() => {
                if (event.sourceEntity && event.sourceEntity.isValid()) {
                    event.sourceEntity.setProperty("aft_soulhunters:attack_state", "none");
                }
            }, resetDelay);
        }
    } else if (event.id === "aft_soulhunters:test_attack") {
        // Test command to trigger attack animations
        if (event.sourceEntity) {
            const attackType = event.message || "attack1";
            event.sourceEntity.setProperty("aft_soulhunters:attack_state", attackType);
            
            const owner = getCompanionOwner(event.sourceEntity);
            if (owner) {
                owner.sendMessage(`§eTest: Triggering ${attackType} animation`);
            }
        }
    }
});

// Monitor property changes for abilities and sounds
system.runInterval(() => {
    try {
        // Get all entities in overworld
        const allEntities = world.getDimension("overworld").getEntities();
        
        for (const entity of allEntities) {
            try {
                // Check if this is a companion entity
                if (!entity.typeId.startsWith("aft_soulhunters:")) continue;
                
                const owner = getCompanionOwner(entity);
                const attackState = entity.getProperty("aft_soulhunters:attack_state");
                const specialTrigger = entity.getProperty("aft_soulhunters:special_trigger");
                const screamTrigger = entity.getProperty("aft_soulhunters:scream_trigger");
                
                // Check for special ability trigger - use attack_state = "special" as trigger
                if (attackState === "special") {
                    const entityId = entity.id;
                    
                    // Only execute if we haven't already executed for this attack cycle
                    if (!activeSpecialAttacks.has(entityId)) {
                        activeSpecialAttacks.add(entityId);
                        handleSpecialAbility(entity);
                        
                        // Immediately reset attack state to prevent looping
                        entity.setProperty("aft_soulhunters:attack_state", "none");
                        
                        // Schedule cleanup of tracking after a delay
                        system.runTimeout(() => {
                            activeSpecialAttacks.delete(entityId);
                        }, 40); // 2 seconds
                    }
                } else {
                    // Reset tracking when not in special state
                    const entityId = entity.id;
                    if (activeSpecialAttacks.has(entityId)) {
                        activeSpecialAttacks.delete(entityId);
                    }
                }

                // Keep the original special_trigger check as backup
                if (specialTrigger === 1) {
                    handleSpecialAbility(entity);
                    entity.setProperty("aft_soulhunters:special_trigger", 0);
                }

                // Check for scream ability trigger using entity properties
                if (screamTrigger === 1) {
                    handleScreamAbility(entity);
                    entity.setProperty("aft_soulhunters:scream_trigger", 0);
                }

                // Check for attack sound triggers using entity properties
                const attackSound = entity.getProperty("aft_soulhunters:attack_sound");
                if (attackSound === "anvil_use") {
                    entity.runCommand("playsound random.anvil_use @a ~~~ 0.5 1.2");
                    entity.setProperty("aft_soulhunters:attack_sound", "none");
                } else if (attackSound === "dragon_growl") {
                    entity.runCommand("playsound mob.enderdragon.growl @a ~~~ 1.0 0.8");
                    entity.runCommand("particle minecraft:basic_flame_particle ~~1~");
                    entity.setProperty("aft_soulhunters:attack_sound", "none");
                }

            } catch (error) {
                // Silently ignore errors for individual entities
            }
        }
    } catch (error) {
        // removed debug log
    }
}, 5); // Check every 5 ticks (0.25 seconds)

function handleSpecialAbility(companion) {
    if (!companion) return;

    try {
        const companionType = getCompanionType(companion);
        const ability = COMPANION_ABILITIES[companionType];
        
        if (!ability) return;

        // Check cooldown
        const cooldownKey = `${companion.id}_special`;
        const now = Date.now();
        const lastUse = companionCooldowns.get(cooldownKey) || 0;
        
        if (now - lastUse < ability.cooldown * 1000) {
            return; // Still on cooldown
        }

        companionCooldowns.set(cooldownKey, now);

        // Execute ability based on type
        switch (companionType) {
            case "dragon":
                executeDragonAbility(companion, ability);
                break;
            case "phoenix":
                executePhoenixAbility(companion, ability);
                break;
            case "wolf":
                executeWolfAbility(companion, ability);
                break;
            case "tiger":
                executeTigerAbility(companion, ability);
                break;
            case "leopard":
                executeLeopardAbility(companion, ability);
                break;
            case "elephant":
                executeElephantAbility(companion, ability);
                break;
            case "fox":
                executeFoxAbility(companion, ability);
                break;
            case "panda":
                executePandaAbility(companion, ability);
                break;
            case "red_panda":
                executeRedPandaAbility(companion, ability);
                break;
            case "manta_ray":
                executeMantaRayAbility(companion, ability);
                break;
        }

    } catch (error) {
        // removed debug log
    }
}

function handleScreamAbility(companion) {
    if (!companion) return;

    try {
        // Universal scream ability - knockback nearby enemies
        const enemies = companion.dimension.getEntities({
            location: companion.location,
            maxDistance: 10,
            excludeFamilies: ["player", "companion"]
        });

        for (const enemy of enemies) {
            try {
                if (enemy && enemy.isValid()) {
                    // Deal damage and apply effects instead of knockback
                    enemy.applyDamage(4, {
                        cause: "entityAttack",
                        damagingEntity: companion
                    });
                    
                    // Apply fear effects instead of knockback
                    enemy.runCommand("effect @s slowness 2 3");
                    enemy.runCommand("effect @s weakness 2 1");
                }
            } catch (error) {
                // Skip invalid entities
                continue;
            }
        }

        // Visual and audio effects
        companion.runCommand("particle minecraft:basic_flame_particle ~~1~");
        companion.runCommand("playsound mob.enderdragon.growl @a ~~~ 2.0 0.5");

    } catch (error) {
        // removed debug log
    }
}

function executeDragonAbility(companion, ability) {
    // Fire breath in cone
    companion.runCommand("particle minecraft:basic_flame_particle ~~1~");
    companion.runCommand("playsound mob.enderdragon.fireball @a ~~~ 2.0 0.8");
    
    // Get enemies in cone
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    for (const enemy of enemies) {
        try {
            // Check if enemy is still valid before applying effects
            if (enemy && enemy.isValid()) {
                enemy.applyDamage(ability.damage, {
                    cause: "fire",
                    damagingEntity: companion
                });
                
                // Use effect command instead of setOnFire for better compatibility
                enemy.runCommand("effect @s minecraft:fire_resistance 0 0");
                enemy.runCommand("damage @s 2 fire");
                
                // Create fire particle effect around enemy
                enemy.runCommand("particle minecraft:basic_flame_particle ~~~");
            }
        } catch (error) {
            // Skip invalid entities
            continue;
        }
    }
}

function executePhoenixAbility(companion, ability) {
    // Healing flames for allies
    companion.runCommand("particle minecraft:basic_flame_particle ~~1~");
    companion.runCommand("playsound mob.enderdragon.hurt @a ~~~ 1.5 1.5");
    
    // Get the companion owner for healing
    const owner = getCompanionOwner(companion);
    if (owner && owner.isValid()) {
        try {
            // Heal the owner directly
            const healAmount = Math.max(1, Math.floor(ability.healing / 2)); // Ensure at least level 1
            owner.runCommand(`effect @s instant_health 1 ${healAmount}`);
        } catch (error) {
            // removed debug log
        }
    }
    
    // Also heal nearby players (in case of multiplayer)
    const nearbyPlayers = companion.dimension.getPlayers({
        location: companion.location,
        maxDistance: ability.range
    });

    for (const player of nearbyPlayers) {
        try {
            if (player && player.isValid() && player.id !== owner?.id) {
                const healAmount = Math.max(1, Math.floor(ability.healing / 2));
                player.runCommand(`effect @s instant_health 1 ${healAmount}`);
            }
        } catch (error) {
            // Skip invalid players
            continue;
        }
    }
}

function executeWolfAbility(companion, ability) {
    // Summon spectral wolves
    companion.runCommand("particle minecraft:basic_smoke_particle ~~1~");
    companion.runCommand("playsound mob.wolf.howl @a ~~~ 2.0 0.8");
    
    for (let i = 0; i < ability.summons; i++) {
        const angle = (i / ability.summons) * 2 * Math.PI;
        const x = companion.location.x + Math.cos(angle) * 3;
        const z = companion.location.z + Math.sin(angle) * 3;
        
        companion.runCommand(`summon aft_soulhunters:spectral_wolf ${x} ${companion.location.y} ${z}`);
    }
}

function executeTigerAbility(companion, ability) {
    // Pounce at nearest enemy
    companion.runCommand("particle minecraft:critical_hit_emitter ~~1~");
    companion.runCommand("playsound mob.cat.hiss @a ~~~ 1.5 0.7");
    
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    if (enemies.length > 0) {
        const target = enemies[0];
        try {
            if (target && target.isValid()) {
                target.applyDamage(ability.damage, {
                    cause: "entityAttack",
                    damagingEntity: companion
                });
                
                // Teleport companion near target
                const dx = target.location.x - companion.location.x;
                const dz = target.location.z - companion.location.z;
                const distance = Math.sqrt(dx * dx + dz * dz);
                
                if (distance > 2) {
                    const newX = target.location.x - (dx / distance) * 2;
                    const newZ = target.location.z - (dz / distance) * 2;
                    companion.teleport({x: newX, y: target.location.y, z: newZ});
                }
            }
        } catch (error) {
            // Skip if target becomes invalid
        }
    }
}

function executeLeopardAbility(companion, ability) {
    // Shadow dash - invisibility and teleport strike
    companion.runCommand("particle minecraft:portal ~~1~");
    companion.runCommand("playsound mob.endermen.portal @a ~~~ 1.5 1.2");
    
    companion.runCommand("effect @s invisibility 3 0");
    
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    if (enemies.length > 0) {
        const target = enemies[0];
        try {
            if (target && target.isValid()) {
                // Teleport behind target
                const angle = Math.atan2(target.location.z - companion.location.z, target.location.x - companion.location.x);
                const newX = target.location.x - Math.cos(angle) * 2;
                const newZ = target.location.z - Math.sin(angle) * 2;
                
                companion.teleport({x: newX, y: target.location.y, z: newZ});
                
                // Attack from behind
                target.applyDamage(ability.damage, {
                    cause: "entityAttack",
                    damagingEntity: companion
                });
            }
        } catch (error) {
            // Skip if target becomes invalid
        }
    }
}

function executeElephantAbility(companion, ability) {
    // Earthquake stomp
    companion.runCommand("particle minecraft:huge_explosion_emitter ~~~");
    companion.runCommand("playsound random.explode @a ~~~ 2.0 0.5");
    
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    for (const enemy of enemies) {
        try {
            if (enemy && enemy.isValid()) {
                // Deal damage instead of knockback for unsupported entities
                enemy.applyDamage(6, {
                    cause: "entityAttack",
                    damagingEntity: companion
                });
                
                // Apply slowness effect to simulate being stunned by earthquake
                enemy.runCommand("effect @s slowness 3 2");
                enemy.runCommand("effect @s weakness 3 1");
            }
        } catch (error) {
            // Skip invalid entities
            continue;
        }
    }
}

function executeFoxAbility(companion, ability) {
    // Create illusion copies
    companion.runCommand("particle minecraft:portal ~~1~");
    companion.runCommand("playsound mob.fox.ambient @a ~~~ 1.5 1.3");
    
    for (let i = 0; i < ability.illusions; i++) {
        const angle = (i / ability.illusions) * 2 * Math.PI;
        const x = companion.location.x + Math.cos(angle) * 2;
        const z = companion.location.z + Math.sin(angle) * 2;
        
        // Create visual illusions with particles - using portal particles instead
        companion.runCommand(`particle minecraft:portal ${x} ${companion.location.y + 1} ${z}`);
    }
}

function executePandaAbility(companion, ability) {
    // Bamboo shield barrier
    companion.runCommand("particle minecraft:villager_happy ~~1~");
    companion.runCommand("playsound block.bamboo.place @a ~~~ 1.5 1.0");
    
    // Grant resistance to nearby allies
    const allies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        families: ["player", "companion"]
    });

    for (const ally of allies) {
        try {
            if (ally && ally.isValid() && ally.typeId === "minecraft:player") {
                ally.runCommand(`effect @s resistance ${ability.duration} 1`);
            }
        } catch (error) {
            // Skip invalid entities
            continue;
        }
    }
}

function executeRedPandaAbility(companion, ability) {
    // Spinning acrobatic attack
    companion.runCommand("particle minecraft:critical_hit_emitter ~~1~");
    companion.runCommand("playsound mob.fox.bite @a ~~~ 1.5 1.1");
    
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    for (const enemy of enemies) {
        try {
            if (enemy && enemy.isValid()) {
                enemy.applyDamage(ability.damage, {
                    cause: "entityAttack",
                    damagingEntity: companion
                });
                
                // Apply dizziness effect instead of knockback
                enemy.runCommand("effect @s nausea 3 1");
                enemy.runCommand("effect @s slowness 2 1");
            }
        } catch (error) {
            // Skip invalid entities
            continue;
        }
    }
}

function executeMantaRayAbility(companion, ability) {
    // Tidal wave effect
    companion.runCommand("particle minecraft:water_drip_particle ~~1~");
    companion.runCommand("playsound ambient.weather.rain @a ~~~ 2.0 0.8");
    
    const enemies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        excludeFamilies: ["player", "companion"]
    });

    for (const enemy of enemies) {
        try {
            if (enemy && enemy.isValid()) {
                // Deal minor damage and apply water effects
                enemy.applyDamage(3, {
                    cause: "drowning",
                    damagingEntity: companion
                });
                
                // Apply water-based effects instead of knockback
                enemy.runCommand("effect @s slowness 5 2");
                enemy.runCommand("effect @s weakness 3 1");
                
                // Create visual water effect around enemy
                enemy.runCommand("particle minecraft:water_drip_particle ~~~");
            }
        } catch (error) {
            // Skip invalid entities
            continue;
        }
    }
}

function getCompanionType(companion) {
    const identifier = companion.typeId;
    return identifier.replace("aft_soulhunters:", "");
}

function getCompanionOwner(companion) {
    // Get owner ID from companion's dynamic property
    const ownerId = companion.getDynamicProperty("ownerId");
    if (!ownerId) return null;
    
    // Find player with matching ID
    const players = world.getAllPlayers();
    return players.find(player => player.id === ownerId) || null;
}

// Export abilities info for UI display
export function getAbilityInfo(companionType) {
    return COMPANION_ABILITIES[companionType] || null;
}

export function getAbilityCooldown(companionId, abilityType = "special") {
    const cooldownKey = `${companionId}_${abilityType}`;
    const lastUse = companionCooldowns.get(cooldownKey) || 0;
    const now = Date.now();
    
    // Default 10 seconds cooldown
    const cooldownTime = 10000;
    
    return Math.max(0, (lastUse + cooldownTime) - now);
}
