import {EasingType, EntityComponentTypes, InputPermissionCategory, system, world, ItemStack } from "@minecraft/server";
import { POKEMONS_DATA } from "../data/pokemon.js";
import { POKEBALLS_CAPTURE_RATE } from "../data/item.js"; 
import { StringUtils } from "../utils/stringUtils.js";
import { pokemonUtils } from "../utils/pokemonUtils.js";
import { Debugger } from "../api/debugger.js";
const debug = Debugger.getInstance();
// --- Pokéball refund logic ---
// Goal:
//  - If a thrown ball MISSES (hits a block), refund 1 ball to the thrower.
//  - If the capture FAILS (Pokémon escapes), refund 1 ball to the thrower.
//  - If the capture SUCCEEDS, do NOT refund (ball is consumed).
function refundBallToPlayer(player, projectileId, reason = "") {
    try {
        if (!player || !projectileId) return;

        // Prefer inventory API (works even when cheats/commands are off)
        try {
            const inv = player.getComponent("minecraft:inventory")?.container;
            if (inv) {
                inv.addItem(new ItemStack(projectileId, 1));
            } else {
                // Fallback to command if inventory isn't available
                player.runCommandAsync?.(`give @s ${projectileId} 1`);
            }
        } catch {
            // Final fallback to command
            try { player.runCommandAsync?.(`give @s ${projectileId} 1`); } catch {}
        }

        if (reason) {
            try { player.onScreenDisplay?.setActionBar?.(reason); } catch {}
        }
    } catch {}
}

// Refund when a ball hits a BLOCK (miss)
world.afterEvents.projectileHitBlock.subscribe((event) => {
    try {
        const { projectile, source } = event;
        if (!projectile || !source)
            return;
        const projectileId = projectile.typeId;
        if (!(projectileId.startsWith("pr:") && projectileId.includes("ball")))
            return;
        if (!("runCommandAsync" in source))
            return; // not a player
        refundBallToPlayer(source, projectileId, "§7Miss! Pokéball returned.");
        // remove the projectile so it can't trigger more refunds
        try { projectile.triggerEvent("remove"); } catch { }
        try { projectile.clearVelocity(); } catch { }
    }
    catch { }
});
// --- End Pokéball refund logic ---

// Wild Pokémon refresh: clears ONLY wild Pokémon (tagged pr:wild) every 1 hour 30 minutes.
// Safe: player Pokémon are pr:tamed=true and are never tagged pr:wild; NPCs are not tagged either.
const WILD_REFRESH_INTERVAL_TICKS = 20 * 60 * 90; // 90 minutes
system.runInterval(() => {
    try {
        const dims = [world.getDimension("overworld"), world.getDimension("nether"), world.getDimension("the_end")];
        for (const dim of dims) {
            // Kill only entities we tagged as wild Pokémon
            dim.runCommand('kill @e[tag=pr:wild]');
        }
    } catch (err) {
        // Ignore command errors (e.g., no entities) to avoid spam/crashes
    }
}, WILD_REFRESH_INTERVAL_TICKS);


world.afterEvents.projectileHitEntity.subscribe((event) => {
    const { dimension, source, projectile } = event;
    const entity = event.getEntityHit().entity;
    if (!entity || !projectile || !source || !dimension)
        return;
    const projectileId = projectile.typeId;
    debug.log(`Projectile Hit: ${projectileId} on Entity: ${entity.typeId} by Source: ${source.nameTag}`, source);
    if (projectileId.startsWith("pr:") && projectileId.includes("ball")) {
        debug.log(`Pokeball detected: ${projectileId}`, source);
        const pokemonData = POKEMONS_DATA.find(pokemon => pokemon.id == entity.typeId);
        const scale = entity.getComponent("scale");
        const capturing = entity.getDynamicProperty("pr:capturing");
        const tamed = entity.getDynamicProperty("pr:tamed");
        debug.log(`Pokemon data found: ${!!pokemonData}, Scale: ${scale?.value}, Capturing: ${capturing}, Tamed: ${tamed}`, source);
        if (scale?.value != 0 && !capturing && !tamed) {
            debug.log(`Initial checks passed - proceeding with capture logic`, source);
            if (pokemonData) {
                debug.log(`Pokemon data exists for ${entity.typeId}`, source);
                const healthComponent = entity.getComponent("minecraft:health");
                if (!healthComponent) {
                    debug.log(`No health component found`, source);
                    return;
                }
                if (!("playSound" in source)) {
                    debug.log(`Source is not a player`, source);
                    return;
                }
                const currentHealthValue = healthComponent.currentValue;
                const maxHealthValue = healthComponent.effectiveMax;
                debug.log(`Health values - Current: ${currentHealthValue}, Max: ${maxHealthValue}`, source);
                const catchRate = pokemonData.catchRate ?? 45;
                const pokemonLevel = entity.getDynamicProperty("pr:level") || 1;
                const ballBonus = getBallBonus(projectileId, entity);
                debug.log(`Catch calculations - Rate: ${catchRate}, Level: ${pokemonLevel}, Ball Bonus: ${ballBonus}`, source);
                const currentAttempts = safeEntityAction(entity, (e) => e.getDynamicProperty("pr:capture_attempts") || 0, () => 0) || 0;
                safeEntityAction(entity, (e) => e.setDynamicProperty("pr:capture_attempts", currentAttempts + 1));
                // Master Ball e Dream Ball sempre capturam
                const isMasterBall = projectileId === "pr:master_ball" || projectileId === "pr:dream_ball";
                const captured = isMasterBall || tryCatch(currentHealthValue, maxHealthValue, catchRate, ballBonus, pokemonLevel, entity.typeId);
                debug.log(`Capture result - Is Master Ball: ${isMasterBall}, Captured: ${captured}`, source);
                // Mostra dica sobre efetividade da Pokébola (apenas na primeira tentativa)
                if (currentAttempts === 0) {
                    showBallEffectivenessTip(source, projectileId, entity);
                }
                // Debug para verificar se chegou até aqui
                debug.log(`Calling catchingDisplay - Source: ${source.nameTag}, Captured: ${captured}`, source);
                catchingDisplay(source, captured, entity, projectile);
                debug.log(`Triggering pokemon events and effects`, source);
                entity.triggerEvent("onPoke");
                projectile.triggerEvent("remove");
                projectile.clearVelocity();
                projectile.playAnimation("catch");
                source?.playSound?.("pr:pokeball");
                entity.addEffect("invisibility", 6 * 20, {
                    amplifier: 1,
                    showParticles: false
                });
                entity.addEffect("slowness", 6 * 20, {
                    amplifier: 255,
                    showParticles: false
                });
                entity.setDynamicProperty("pr:capturing", true);
                debug.log(`Setting timeout for capture result handling`, source);
                system.runTimeout(() => {
                    if (!entity.isValid) {
                        debug.log(`Entity is no longer valid in timeout`, source);
                        if ("inputPermissions" in source) {
                            source.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, true);
                            source.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, true);
                            source.camera.clear();
                            source.removeTag("pr:capturing");
                        }
                        return;
                    }
                    debug.log(`Processing capture result in timeout - captured: ${captured}`, source);
                    if (captured) {
                        const pokemonTypeId = entity.typeId;
                        const pokemonLevel = entity.getDynamicProperty("pr:level");
                        if (pokemonTypeId && typeof pokemonTypeId === 'string') {
                            debug.log(`Capturing pokemon: ${pokemonTypeId} at level ${pokemonLevel}`, source);
                            pokemonUtils.capturePokemon(source, pokemonTypeId, pokemonLevel);
                        }
                        else {
                            console.error(`TypeId inválido para captura: ${pokemonTypeId}`);
                            source.sendMessage("§cCapture failed: invalid Pokémon.");
                        }
                        entity.remove();
                    }
                    else {
                        debug.log(`Pokemon escaped, setting capturing to false`, source);
                        // Capture failed => refund the ball to the thrower
                        refundBallToPlayer(source, projectileId, "§7Capture failed! Pokéball returned.");
                        try {
                            entity.setDynamicProperty("pr:capturing", false);
                        }
                        catch (error) {
                            console.warn("Erro ao definir propriedade pr:capturing:", error);
                        }
                    }
                }, 6 * 20);
            }
            else {
                debug.log(`No pokemon data found for ${entity.typeId}`, source);
            }
        }
        else {
            debug.log(`Checks failed - Scale: ${scale?.value}, Capturing: ${capturing}, Tamed: ${tamed}`, source);
            // Not a valid catch target => treat as a miss and refund.
            refundBallToPlayer(source, projectileId, "§7Pokéball returned.");
            try { projectile.triggerEvent("remove"); } catch { }
            try { projectile.clearVelocity(); } catch { }
        }
    }
    else {
        debug.log(`Not a pokeball projectile: ${projectileId}`, source);
    }
});
world.afterEvents.entityDie.subscribe((event) => {
    const { damageSource, deadEntity } = event;
    if (!deadEntity || !damageSource)
        return;
    try {
        const typeFamily = deadEntity.getComponent("minecraft:type_family");
        const tamed = deadEntity.getDynamicProperty("pr:tamed");
        if (typeFamily.hasTypeFamily("pokemon") && tamed) {
            const player = world.getEntity(deadEntity.getDynamicProperty("pr:owner"));
            if (!player)
                return;
            const pokemonSlotData = pokemonUtils.getPokemonFromSlot(player, player.getDynamicProperty("pr:selectedSlot") || 0);
            if (!pokemonSlotData)
                return;
            // Define o health como 0 explicitamente para Pokémon derrotado
            pokemonUtils.returnPokemonToSlot(player, {
                typeId: pokemonSlotData.typeId,
                level: pokemonSlotData.level,
                health: 0, // Sempre 0 quando o Pokémon morre
                owner: pokemonSlotData.owner,
                name: pokemonSlotData.name,
                attack: pokemonSlotData.attack,
                defense: pokemonSlotData.defense,
                speed: pokemonSlotData.speed,
                spAttack: pokemonSlotData.spAttack,
                spDefense: pokemonSlotData.spDefense,
                xp: pokemonSlotData.xp,
                move1: pokemonSlotData.move1,
                move2: pokemonSlotData.move2,
                move3: pokemonSlotData.move3,
                move4: pokemonSlotData.move4,
            });
            player.sendMessage(`§c${StringUtils.toTitleCaseEntityName(deadEntity.nameTag.split('\n')[0])} §rhas been defeated!`);
        }
    }
    catch (error) {
        debug.log(`Error processing entity death: ${error}`);
    }
});
world.afterEvents.entityHurt.subscribe((event) => {
    const { hurtEntity } = event;
    if (!hurtEntity)
        return;
    pokemonUtils.updatePokemonDataHealth(hurtEntity);
});
world.afterEvents.entitySpawn.subscribe((event) => {
    const { entity, cause } = event;
    if (entity.typeId == "pr:storage_pc" || entity.typeId == "pr:pokecenter_healer_machinery") {
        // Corrige a rotação do storage PC para ficar alinhado com as direções cardeais
        const currentRotation = entity.getRotation();
        // Normaliza o Y para estar entre 0 e 360
        let yRotation = currentRotation.y % 360;
        if (yRotation < 0)
            yRotation += 360;
        // Arredonda para a direção cardinal mais próxima
        let targetY;
        if (yRotation >= 315 || yRotation < 45) {
            targetY = 0; // Norte
        }
        else if (yRotation >= 45 && yRotation < 135) {
            targetY = 90; // Leste
        }
        else if (yRotation >= 135 && yRotation < 225) {
            targetY = 180; // Sul
        }
        else {
            targetY = 270; // Oeste
        }
        // Define a rotação corrigida (X sempre 0 para ficar reto)
        entity.setRotation({ x: 0, y: targetY });
    }
    const tameableComponent = entity.getComponent(EntityComponentTypes.Tameable);
    if (!tameableComponent)
        return;
    const owner = tameableComponent?.tamedToPlayer;
    if (owner)
        return;
    const pokemonData = POKEMONS_DATA.find(pokemon => pokemon.id === entity.typeId);
    if (!pokemonData)
        return;
    // Usa a função utilitária para configurações seguras
    safeEntityAction(entity, (e) => {
        e.setDynamicProperty("pr:tamed", false);
        // Mark as wild so cleanup systems never affect player-owned Pokémon or NPCs
        e.addTag("pr:wild");
        const healthComp = e.getComponent("minecraft:health");
        if (healthComp) {
            healthComp.setCurrentValue(pokemonData.maxHealth);
        }
        const level = randomValue(pokemonData.minSpawnLevel, pokemonData.maxSpawnLevel);
        e.setDynamicProperty("pr:level", level);
        e.nameTag = `${StringUtils.toTitleCaseEntityName(e.typeId)} Wild\nLvl: §a${level}§r`;
    });
});
function safeEntityAction(entity, action, fallback) {
    if (entity?.isValid) {
        try {
            return action(entity);
        }
        catch (error) {
            console.warn("Erro ao executar ação na entidade:", error);
            return fallback?.();
        }
    }
    else {
        return fallback?.();
    }
}
function randomValue(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function catchingDisplay(source, captured, pokemon, pokeball) {
    debug.log(`catchingDisplay called - source: ${source?.nameTag}, captured: ${captured}, pokemon: ${pokemon?.typeId}, pokeball: ${pokeball?.typeId}`, source);
    if (!source || !pokemon || !pokeball) {
        debug.log(`Missing parameters in catchingDisplay`, source);
        return;
    }
    if (!("camera" in source)) {
        debug.log(`Source is not a player in catchingDisplay`, source);
        return;
    }
    // Se já tem a tag, remove primeiro para garantir que a captura funcione
    if (source.hasTag("pr:capturing")) {
        debug.log(`Player already has pr:capturing tag - removing it first`, source);
        source.removeTag("pr:capturing");
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, true);
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, true);
        source.camera.clear();
    }
    debug.log(`Setting up camera for capturing display`, source);
    try {
        source.camera.setCamera("minecraft:free", {
            location: {
                x: pokemon?.location.x - (source.getViewDirection().x * 1),
                y: pokemon.location.y + 1.5,
                z: pokemon?.location.z - (source.getViewDirection().z * 1),
            },
            rotation: pokemon.getRotation(),
            easeOptions: {
                easeTime: 0.25,
                easeType: EasingType.Linear,
            },
            facingEntity: pokeball,
        });
        source.addTag("pr:capturing");
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, false);
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, false);
        debug.log(`Camera and permissions set successfully`, source);
        // Mensagens mais dinâmicas baseadas no tipo de Pokébola
        const ballType = pokeball.typeId;
        let messages = ["Capturing", "Capturing.", "Capturing..", "Capturing...", "Capturing", "Capturing.", "Capturing..", "Capturing..."];
        if (ballType === "pr:master_ball" || ballType === "pr:dream_ball") {
            messages = ["Capturing", "Success!", "Success!", "Success!"]; // Master Ball sempre captura
        }
        else if (ballType === "pr:quick_ball") {
            messages = ["Quick Catch", "Quick Catch.", "Quick Catch..", "Quick Catch..."]; // Quick Ball é rápida
        }
        const delay = 0.75 * 20;
        // Captura informações antes de iniciar a animação
        const pokemonLevel = pokemon.getDynamicProperty("pr:level") || 1;
        const pokemonAttempts = pokemon.getDynamicProperty("pr:capture_attempts") || 1;
        const pokemonName = StringUtils.toTitleCaseEntityName(pokemon.typeId);
        debug.log(`Starting capturing steps with ${messages.length} messages`, source);
        showCapturingStep(messages, 0, delay, source, pokemon, captured, ballType, pokemonLevel, pokemonAttempts, pokemonName);
    }
    catch (error) {
        debug.log(`Error in catchingDisplay: ${error}`, source);
        console.error("Error in catchingDisplay:", error);
    }
}
function showCapturingStep(messages, index, delay, source, pokemon, captured, ballType, pokemonLevel, pokemonAttempts, pokemonName) {
    debug.log(`showCapturingStep called - index: ${index}/${messages.length}, message: ${messages[index] || 'undefined'}`, source);
    if (index < messages.length) {
        source.onScreenDisplay.setActionBar(messages[index]);
        source.playSound("random.orb");
        system.runTimeout(() => showCapturingStep(messages, index + 1, delay, source, pokemon, captured, ballType, pokemonLevel, pokemonAttempts, pokemonName), delay);
    }
    else {
        debug.log(`Capture sequence complete - captured: ${captured}`, source);
        if (captured) {
            const name = pokemonName || StringUtils.toTitleCaseEntityName(pokemon.typeId);
            const level = pokemonLevel || 1;
            const attempts = pokemonAttempts || 1;
            // Mensagem de captura personalizada
            let captureMessage = `§a${name}§r Captured!`;
            if (ballType === "pr:master_ball" || ballType === "pr:dream_ball") {
                captureMessage = `§6${name}§r was caught with certainty!`;
            }
            else if (attempts > 3) {
                captureMessage = `§a${name}§r finally caught after ${attempts} attempts!`;
            }
            else if (level >= 30) {
                captureMessage = `§a${name}§r (Lv.${level}) was difficult but caught!`;
            }
            source.onScreenDisplay.setActionBar(captureMessage);
            source.playSound("random.levelup");
        }
        else {
            const name = pokemonName || StringUtils.toTitleCaseEntityName(pokemon.typeId);
            let escapeMessage = `${name} escaped!`;
            // Verifica se o Pokémon ainda existe antes de acessar suas propriedades
            if (pokemon.isValid) {
                try {
                    const healthComp = pokemon.getComponent("minecraft:health");
                    const pokemonData = POKEMONS_DATA.find(p => p.id === pokemon.typeId);
                    if (!healthComp || !pokemonData) {
                        escapeMessage = `${name} escaped!`;
                        debug.log(`Health component or Pokémon data not found for ${name}`, source);
                        return;
                    }
                    if (healthComp) {
                        const hpPercent = Math.round(healthComp.currentValue / pokemonData.maxHealth * 100);
                        if (hpPercent > 75) {
                            escapeMessage = `${name} broke free easily! (HP: ${hpPercent}%)`;
                        }
                        else if (hpPercent > 25) {
                            escapeMessage = `${name} escaped! (HP: ${hpPercent}%)`;
                        }
                        else {
                            escapeMessage = `${name} barely escaped! (HP: ${hpPercent}%)`;
                        }
                    }
                }
                catch (error) {
                    // Se houver erro ao acessar o componente, usa mensagem simples
                    escapeMessage = `${name} escaped!`;
                }
            }
            source.onScreenDisplay.setActionBar(escapeMessage);
            source.playSound("random.pop2");
        }
        debug.log(`Restoring camera and permissions`, source);
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Camera, true);
        source.inputPermissions.setPermissionCategory(InputPermissionCategory.Movement, true);
        source.camera.clear();
        source.removeTag("pr:capturing");
        // Limpa tentativas de captura se foi capturado ou se falhou muitas vezes
        // Só tenta limpar se o Pokémon ainda existe
        if (pokemon.isValid) {
            try {
                if (captured || (pokemon.getDynamicProperty("pr:capture_attempts") || 0) > 5) {
                    pokemon.setDynamicProperty("pr:capture_attempts", 0);
                }
            }
            catch (error) {
                // Ignora erro se não conseguir acessar propriedades dinâmicas
            }
        }
    }
}
function tryCatch(currentHP, maxHP, catchRate, ballBonus, pokemonLevel = 1, pokemonTypeId = "") {
    // Fórmula baseada na mecânica oficial de Pokémon com melhorias
    // 1. Cálculo base da captura com HP atual
    const hpFactor = (3 * maxHP - 2 * currentHP) / (3 * maxHP);
    // 2. Modificador de status (simulado baseado em HP baixo)
    let statusBonus = 1.0;
    const hpPercentage = currentHP / maxHP;
    if (hpPercentage <= 0.1) {
        statusBonus = 2.5; // Pokémon quase desmaiado = muito mais fácil
    }
    else if (hpPercentage <= 0.25) {
        statusBonus = 2.0; // HP baixo
    }
    else if (hpPercentage <= 0.5) {
        statusBonus = 1.5; // HP médio
    }
    // 3. Modificador de nível (Pokémon de nível mais baixo são mais fáceis)
    let levelModifier = 1.0;
    if (pokemonLevel <= 5) {
        levelModifier = 1.3;
    }
    else if (pokemonLevel <= 10) {
        levelModifier = 1.2;
    }
    else if (pokemonLevel <= 20) {
        levelModifier = 1.1;
    }
    else if (pokemonLevel >= 50) {
        levelModifier = 0.8; // Pokémon de alto nível são mais difíceis
    }
    // 4. Modificadores especiais para certas Pokébolas
    let specialBallBonus = ballBonus;
    if (pokemonTypeId.includes("water") && ballBonus === 3.5) {
        // Dive Ball tem bônus extra para Pokémon aquáticos
        specialBallBonus = ballBonus * 1.2;
    }
    else if (pokemonLevel <= 10 && ballBonus === 4.0 && pokemonTypeId.includes("nest")) {
        // Nest Ball é mais efetiva em Pokémon de baixo nível
        specialBallBonus = ballBonus * (1 + (10 - pokemonLevel) * 0.1);
    }
    // 5. Cálculo final com múltiplos estágios de verificação
    const baseChance = (hpFactor * catchRate * specialBallBonus * statusBonus * levelModifier) / 255;
    // 6. Sistema de múltiplas tentativas (4 shakes como no jogo original)
    const shakeChance = Math.min(baseChance, 1);
    // Primeira verificação - se falhar aqui, escape imediato
    if (Math.random() > shakeChance) {
        return false;
    }
    // Sistema de 4 shakes
    let successfulShakes = 0;
    for (let i = 0; i < 4; i++) {
        if (Math.random() < shakeChance) {
            successfulShakes++;
        }
        else {
            break; // Pokémon escapa
        }
    }
    // Precisa de todos os 4 shakes para capturar
    return successfulShakes === 4;
}
function getBallBonus(typeId, pokemon) {
    const ball = POKEBALLS_CAPTURE_RATE.find(entry => Object.keys(entry)[0] === typeId);
    let baseBonus = ball ? Object.values(ball)[0] : 1.0;
    // Lógica especial para Pokébolas específicas
    if (pokemon) {
        const pokemonLevel = pokemon.getDynamicProperty("pr:level") || 1;
        const pokemonData = POKEMONS_DATA.find(p => p.id === pokemon.typeId);
        switch (typeId) {
            case "pr:timer_ball":
                // Timer Ball fica mais efetiva com o tempo (simulamos com tentativas)
                const attempts = pokemon.getDynamicProperty("pr:capture_attempts") || 0;
                baseBonus = Math.min(baseBonus + (attempts * 0.5), 8.0);
                break;
            case "pr:level_ball":
                // Level Ball é mais efetiva se o jogador tem Pokémon de nível maior
                // Por simplicidade, assumimos que é efetiva para Pokémon de nível baixo
                if (pokemonLevel <= 15) {
                    baseBonus = baseBonus * 1.5;
                }
                break;
            case "pr:repeat_ball":
                // Repeat Ball seria mais efetiva se já capturou esse Pokémon antes
                // Por simplicidade, damos um pequeno bônus
                baseBonus = baseBonus * 1.2;
                break;
            case "pr:nest_ball":
                // Nest Ball é mais efetiva para Pokémon de baixo nível
                if (pokemonLevel <= 20) {
                    const levelBonus = Math.max(1.0, (20 - pokemonLevel) * 0.1);
                    baseBonus = baseBonus * (1 + levelBonus);
                }
                break;
            case "pr:net_ball":
                // Net Ball é mais efetiva para Pokémon Bug e Water
                if (pokemonData?.types.some(type => type === "bug" || type === "water")) {
                    baseBonus = baseBonus * 1.5;
                }
                break;
            case "pr:dive_ball":
                // Dive Ball é mais efetiva para Pokémon aquáticos
                if (pokemonData?.types.includes("water")) {
                    baseBonus = baseBonus * 1.3;
                }
                break;
            case "pr:dusk_ball":
                // Dusk Ball é mais efetiva em lugares escuros ou à noite
                // Simulamos verificando a hora do mundo
                const timeOfDay = world.getTimeOfDay();
                if (timeOfDay > 13000 || timeOfDay < 1000) { // Noite
                    baseBonus = baseBonus * 1.2;
                }
                break;
            case "pr:quick_ball":
                // Quick Ball é mais efetiva no primeiro turno
                const captureAttempts = pokemon.getDynamicProperty("pr:capture_attempts") || 0;
                if (captureAttempts === 0) {
                    baseBonus = baseBonus * 1.0; // Mantém o valor alto
                }
                else {
                    baseBonus = 1.0; // Reduz drasticamente após a primeira tentativa
                }
                break;
        }
    }
    return baseBonus;
}
function showBallEffectivenessTip(player, ballTypeId, pokemon) {
    const pokemonData = POKEMONS_DATA.find(p => p.id === pokemon.typeId);
    const pokemonLevel = pokemon.getDynamicProperty("pr:level") || 1;
    let tip = "";
    switch (ballTypeId) {
        case "pr:net_ball":
            if (pokemonData?.types.some(type => type === "bug" || type === "water")) {
                tip = "§aNet Ball is super effective against Bug/Water types!";
            }
            else {
                tip = "§cNet Ball is less effective against this Pokémon type.";
            }
            break;
        case "pr:dive_ball":
            if (pokemonData?.types.includes("water")) {
                tip = "§aDive Ball is very effective against Water types!";
            }
            else {
                tip = "§cDive Ball works better on Water-type Pokémon.";
            }
            break;
        case "pr:nest_ball":
            if (pokemonLevel <= 20) {
                tip = `§aNest Ball is effective against low-level Pokémon! (Lv.${pokemonLevel})`;
            }
            else {
                tip = `§cNest Ball is less effective against high-level Pokémon. (Lv.${pokemonLevel})`;
            }
            break;
        case "pr:timer_ball":
            tip = "§eTimer Ball becomes more effective with each failed attempt!";
            break;
        case "pr:quick_ball":
            tip = "§eQuick Ball is most effective on first use!";
            break;
        case "pr:dusk_ball":
            const timeOfDay = world.getTimeOfDay();
            if (timeOfDay > 13000 || timeOfDay < 1000) {
                tip = "§aDusk Ball is very effective during night time!";
            }
            else {
                tip = "§cDusk Ball works better at night or in dark places.";
            }
            break;
        case "pr:master_ball":
        case "pr:dream_ball":
            tip = "§6This ball guarantees capture!";
            break;
        default:
            // Análise geral baseada no HP
            const healthComp = pokemon.getComponent("minecraft:health");
            const hpPercent = Math.round(healthComp.currentValue / (pokemonData?.maxHealth ?? 100) * 100);
            if (hpPercent < 25) {
                tip = "§aLow HP increases capture chance!";
            }
            else if (hpPercent > 75) {
                tip = "§cWeaken the Pokémon first for better capture rates!";
            }
            break;
    }
    if (tip) {
        player.sendMessage(tip);
    }
}