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

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

const COMPANION_ABILITIES = {
    dragon: {
        name: "Fire Breath",
        description: "Breathes fire in a cone, dealing area damage",
        cooldown: 10,
        range: 8,
        damage: 12
    },
    phoenix: {
        name: "Flame Burst",
        description: "Creates a burst of healing flames around allies",
        cooldown: 15,
        range: 6,
        healing: 6
    },
    wolf: {
        name: "Pack Howl",
        description: "Howls to summon spectral wolves",
        cooldown: 20,
        range: 10,
        summons: 3
    },
    tiger: {
        name: "Pounce Strike",
        description: "Leaps at enemies with devastating force",
        cooldown: 8,
        range: 5,
        damage: 10
    },
    leopard: {
        name: "Shadow Dash",
        description: "Becomes invisible and strikes from behind",
        cooldown: 12,
        range: 7,
        damage: 8
    },
    elephant: {
        name: "Earthquake Stomp",
        description: "Stomps ground causing area knockback",
        cooldown: 15,
        range: 8,
        knockback: 5
    },
    fox: {
        name: "Illusion Burst",
        description: "Creates mirror images to confuse enemies",
        cooldown: 10,
        range: 6,
        illusions: 4
    },
    panda: {
        name: "Bamboo Shield",
        description: "Creates protective bamboo barrier",
        cooldown: 18,
        range: 5,
        duration: 10
    },
    red_panda: {
        name: "Acrobatic Strike",
        description: "Performs spinning attacks hitting multiple enemies",
        cooldown: 9,
        range: 4,
        damage: 6
    },
    manta_ray: {
        name: "Tidal Wave",
        description: "Summons water waves that push enemies",
        cooldown: 14,
        range: 9,
        knockback: 4
    }
};

let companionCooldowns = new Map();

// 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(() => {
    // Find all companion entities by type ID
    const companionTypes = [
        "aft_soulhunters:dragon", "aft_soulhunters:phoenix", "aft_soulhunters:wolf",
        "aft_soulhunters:tiger", "aft_soulhunters:leopard", "aft_soulhunters:elephant",
        "aft_soulhunters:fox", "aft_soulhunters:panda", "aft_soulhunters:red_panda",
        "aft_soulhunters:manta_ray"
    ];

    for (const companionType of companionTypes) {
        const companions = world.getDimension("overworld").getEntities({
            type: companionType
        });

        for (const companion of companions) {
            try {
                // Only process companions that have the companion tag (from our companion manager)
                if (!companion.hasTag("companion")) continue;
                
                // Check for attack sound triggers
                const attackSound = companion.getProperty("aft_soulhunters:attack_sound");
                if (attackSound === "anvil_use") {
                    companion.runCommand("playsound random.anvil_use @a ~~~ 0.5 1.2");
                    companion.setProperty("aft_soulhunters:attack_sound", "none");
                } else if (attackSound === "dragon_growl") {
                    companion.runCommand("playsound mob.enderdragon.growl @a ~~~ 1.0 0.8");
                    companion.runCommand("particle minecraft:dragon_breath_fire ~~1~");
                    companion.setProperty("aft_soulhunters:attack_sound", "none");
                }

                // Check for special ability trigger
                const specialTrigger = companion.getProperty("aft_soulhunters:special_trigger");
                if (specialTrigger === 1) {
                    handleSpecialAbility(companion);
                    companion.setProperty("aft_soulhunters:special_trigger", 0);
                }

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

            } 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;
        }

        // Show ability used message
        const owner = getCompanionOwner(companion);
        if (owner) {
            owner.sendMessage(`§6${companion.nameTag} used ${ability.name}!`);
        }

    } 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) {
            // Apply knockback
            const dx = enemy.location.x - companion.location.x;
            const dz = enemy.location.z - companion.location.z;
            const distance = Math.sqrt(dx * dx + dz * dz);
            
            if (distance > 0) {
                const knockbackForce = 3.0 / Math.max(distance, 1);
                enemy.applyKnockback(dx / distance, dz / distance, knockbackForce, 0.5);
                
                // Deal minor damage
                enemy.applyDamage(4, {
                    cause: "entityAttack",
                    damagingEntity: companion
                });
            }
        }

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

        const owner = getCompanionOwner(companion);
        if (owner) {
            owner.sendMessage(`§c${companion.nameTag} unleashed a terrifying roar!`);
        }

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

function executeDragonAbility(companion, ability) {
    // Fire breath in cone
    companion.runCommand("particle minecraft:dragon_breath_fire ~~1~ 2 1 2 0.2 100");
    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) {
        enemy.applyDamage(ability.damage, {
            cause: "fire",
            damagingEntity: companion
        });
        enemy.setOnFire(5, true);
    }
}

function executePhoenixAbility(companion, ability) {
    // Healing flames for allies
    companion.runCommand("particle minecraft:flame ~~1~ 3 1 3 0.1 80");
    companion.runCommand("playsound mob.enderdragon.hurt @a ~~~ 1.5 1.5");
    
    const allies = companion.dimension.getEntities({
        location: companion.location,
        maxDistance: ability.range,
        families: ["player", "companion"]
    });

    for (const ally of allies) {
        if (ally.typeId === "minecraft:player") {
            ally.runCommand(`effect @s instant_health 1 ${Math.floor(ability.healing / 4)}`);
        }
    }
}

function executeWolfAbility(companion, ability) {
    // Summon spectral wolves
    companion.runCommand("particle minecraft:soul ~~1~ 2 1 2 0.3 60");
    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:crit ~~1~ 1 1 1 0.3 40");
    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];
        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});
        }
    }
}

function executeLeopardAbility(companion, ability) {
    // Shadow dash - invisibility and teleport strike
    companion.runCommand("particle minecraft:portal ~~1~ 2 1 2 0.5 50");
    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];
        // 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
        });
    }
}

function executeElephantAbility(companion, ability) {
    // Earthquake stomp
    companion.runCommand("particle minecraft:block_break_stone ~~~ 4 0 4 0.5 100");
    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) {
        const dx = enemy.location.x - companion.location.x;
        const dz = enemy.location.z - companion.location.z;
        const distance = Math.sqrt(dx * dx + dz * dz);
        
        if (distance > 0) {
            const knockbackForce = ability.knockback / Math.max(distance, 1);
            enemy.applyKnockback(dx / distance, dz / distance, knockbackForce, 1.0);
        }
    }
}

function executeFoxAbility(companion, ability) {
    // Create illusion copies
    companion.runCommand("particle minecraft:enchanted_hit ~~1~ 2 1 2 0.3 60");
    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
        companion.runCommand(`particle minecraft:portal ${x} ${companion.location.y + 1} ${z} 0.5 1 0.5 0.1 20`);
    }
}

function executePandaAbility(companion, ability) {
    // Bamboo shield barrier
    companion.runCommand("particle minecraft:villager_happy ~~1~ 2 1 2 0.2 50");
    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) {
        if (ally.typeId === "minecraft:player") {
            ally.runCommand(`effect @s resistance ${ability.duration} 1`);
        }
    }
}

function executeRedPandaAbility(companion, ability) {
    // Spinning acrobatic attack
    companion.runCommand("particle minecraft:crit ~~1~ 2 1 2 0.4 80");
    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) {
        enemy.applyDamage(ability.damage, {
            cause: "entityAttack",
            damagingEntity: companion
        });
        
        // Small knockback
        const dx = enemy.location.x - companion.location.x;
        const dz = enemy.location.z - companion.location.z;
        const distance = Math.sqrt(dx * dx + dz * dz);
        
        if (distance > 0) {
            enemy.applyKnockback(dx / distance, dz / distance, 1.0, 0.3);
        }
    }
}

function executeMantaRayAbility(companion, ability) {
    // Tidal wave effect
    companion.runCommand("particle minecraft:splash ~~1~ 4 1 4 0.5 120");
    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) {
        const dx = enemy.location.x - companion.location.x;
        const dz = enemy.location.z - companion.location.z;
        const distance = Math.sqrt(dx * dx + dz * dz);
        
        if (distance > 0) {
            const knockbackForce = ability.knockback / Math.max(distance, 1);
            enemy.applyKnockback(dx / distance, dz / distance, knockbackForce, 0.8);
        }
        
        // Apply slowness
        if (enemy.typeId === "minecraft:player") {
            enemy.runCommand("effect @s slowness 5 1");
        }
    }
}

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();
    return Math.max(0, (lastUse + 10000) - now); // Default 10 second cooldown
}
