import { ItemStack, world, system } from "@minecraft/server";
import { pokemonUtils } from "../utils/pokemonUtils.js";
import { starterMenu } from "../data/ui/starterMenu.js";
import { Debugger } from "../api/debugger.js";
import { ITEMS_UI } from "../data/item.js";
import { uiManager } from "@minecraft/server-ui";
import { POKEMONS_DATA } from "../data/pokemon.js";
const debug = Debugger.getInstance();
world.afterEvents.playerSpawn.subscribe((eventData) => {
    const { player } = eventData;
    // IMPORTANT: Don't key registration off world dynamic properties using nameTag.
    // nameTag can change (ranks, formatting) and world dynamic properties are not
    // always reliable across reloads/respawns, which caused party slots to reset
    // and appear to "randomly" turn into the starter.
    try {
        const hasRegisterTag = player.hasTag("rp_pr:player_registered") || player.hasTag("pr:joined") || player.hasTag("pr:started");

        // If the player already has any slot data saved, never wipe it.
        let hasAnySlot = false;
        for (let i = 0; i < 6; i++) {
            if (pokemonUtils.getPokemonFromSlot(player, i)) {
                hasAnySlot = true;
                break;
            }
        }

        if (!hasRegisterTag) {
            // First time init: only clear if truly empty
            if (!hasAnySlot) {
                pokemonUtils.createSlotsPokemon(player);
                setInitializedItems(player);
            }
            player.addTag("rp_pr:player_registered");
        }
    }
    catch (e) {
        // Fail-safe: never wipe slots on errors.
    }
});
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        const velocity = player.getVelocity();
        const isStarter = world.getDynamicProperty(`pr:starter_${player.nameTag}`);
        /*if (!player.hasTag("b:start") && !isStarter && (velocity.x === 0 || velocity.y === 0 || velocity.z === 0)) {
            player.addTag("b:start")
            starterMenu(player, 0);
        }*/
        const maxLengthName = 16;
        const maxLengthLevel = 5;
        const maxLengthHealth = 5;
        const slots = pokemonUtils.returnPokemonsSlots(player);
        const selectedSlot = player?.getDynamicProperty("pr:selectedSlot") ?? 0;
        player.onScreenDisplay.setTitle(slots.map(slot => {
            return `${slot.name}`.padEnd(maxLengthName, " ") +
                `${slot.level}`.padEnd(maxLengthLevel, " ") +
                `${slot.health.toFixed(0)}%`.padEnd(maxLengthHealth, " ");
        }).join("") +
            `S:${(selectedSlot == -1 ? 1 : selectedSlot + 1)}`.padEnd(5, " "));
    });
}, 5);
world.afterEvents.playerInteractWithEntity.subscribe((eventData) => {
    const { player, target, itemStack } = eventData;
    if (player.hasTag("pr:first_village_quest") && !player.hasTag("pr:first_village_quest_done") && (target?.typeId ?? "").startsWith("pr:quest_")) {
        try {
            player.removeTag("pr:first_village_quest");
            player.addTag("pr:first_village_quest_done");
            player.playSound("random.levelup");
            player.sendMessage("§aQuest Complete! §7You found a village quest NPC.");
            player.onScreenDisplay.setActionBar(" ");
        } catch (e) {}
    }
    if (ITEMS_UI[itemStack?.typeId ?? ""]) {
        player.onScreenDisplay.setActionBar("It was not possible to interact because this item opens an interface.");
        system.runTimeout(() => uiManager.closeAllForms(player), 2);
        return;
    }
    if (target.typeId == "pr:storage_pc") {
        if (!player.isSneaking) {
            pokemonUtils.openPC(player);
            return;
        }
        target.dimension.spawnItem(new ItemStack("pr:storage_pc_spawn_egg", 1), target.location);
        target.remove();
    }
    if (target.typeId == "pr:pokecenter_healer_machinery") {
        if (!player.isSneaking) {
            [0, 1, 2, 3, 4, 5].forEach(slotIndex => {
                system.runTimeout(() => {
                    const slot = pokemonUtils.getPokemonFromSlot(player, slotIndex);
                    if (slot) {
                        const pokemonData = POKEMONS_DATA.find(p => p.id === slot.typeId);
                        if (!pokemonData)
                            return;
                        pokemonUtils.updatePokemonSlot(player, slotIndex, {
                            attack: slot.attack,
                            defense: slot.defense,
                            health: pokemonData?.maxHealth,
                            level: slot.level,
                            name: slot.name,
                            move1: slot.move1,
                            move2: slot.move2,
                            move3: slot.move3,
                            move4: slot.move4,
                            owner: slot.owner,
                            spAttack: slot.spAttack,
                            spDefense: slot.spDefense,
                            speed: slot.speed,
                            typeId: slot.typeId,
                            xp: slot.xp,
                        });
                    }
                }, 1 + slotIndex * 10);
            });
            player.onScreenDisplay.setActionBar("All your pokémons have been healed.");
            return;
        }
        target.dimension.spawnItem(new ItemStack("pr:pokecenter_healer_machinery_spawn_egg", 1), target.location);
        target.remove();
    }
});
function setInitializedItems(player) {
    const inventory = player.getComponent("minecraft:inventory").container;
    const INITIALIZED_ITEMS_DATA = {
        "pr:arceus_phone": {
            amount: 1
        },
        "pr:potion": {
            amount: 1
        },
        "pr:pokeball": {
            amount: 10
        },
    };
    Object.keys(INITIALIZED_ITEMS_DATA).forEach(itemId => {
        const itemData = INITIALIZED_ITEMS_DATA[itemId];
        const itemStack = new ItemStack(itemId, itemData.amount);
        inventory.addItem(itemStack);
    });
}
