import { world, system, ItemUseBeforeEvent, ItemComponentTypes, EntityComponentTypes, Player } from '@minecraft/server';
import { cachedPlayers } from './pvp.js';

system.runInterval(() => {
    for (const player of cachedPlayers) {
        // Inventory
        const inv = player.getComponent(EntityComponentTypes.Inventory).container;
        for (let i = 0; i < inv.size; i++) {
            const slot = inv.getSlot(i);
            const item = slot.getItem();
            if (!item) continue;
            const durability = item.getComponent(ItemComponentTypes.Durability);
            if (!durability) continue;

            const currentDurability = durability.maxDurability - durability.damage;
            const durabilityPercentage = (currentDurability / durability.maxDurability) * 100;

            let colorCode = "§7"; // Default color for the numbers (gray)
            if (durabilityPercentage >= 75) {
                colorCode = "§a"; // Green
            } else if (durabilityPercentage >= 50) {
                colorCode = "§e"; // Yellow
            } else if (durabilityPercentage >= 25) {
                colorCode = "§6"; // Gold/Orange
            } else {
                colorCode = "§c"; // Red
            }

            // Apply color only to the current durability number
            slot.setLore([`§rDurability: ${colorCode}${currentDurability}§8/§7${durability.maxDurability}`]);
        }

        // Equipped items
        const equippable = player.getComponent(EntityComponentTypes.Equippable);
        for (const slotName of ["Offhand", "Head", "Chest", "Legs", "Feet"]) {
            const slot = equippable.getEquipmentSlot(slotName);
            const item = slot.getItem();
            if (!item) continue;
            const durability = item.getComponent(ItemComponentTypes.Durability);
            if (!durability) continue;

            const currentDurability = durability.maxDurability - durability.damage;
            const durabilityPercentage = (currentDurability / durability.maxDurability) * 100;

            let colorCode = "§7"; // Default color for the numbers (gray)
            if (durabilityPercentage >= 75) {
                colorCode = "§a"; // Green
            } else if (durabilityPercentage >= 50) {
                colorCode = "§e"; // Yellow
            } else if (durabilityPercentage >= 25) {
                colorCode = "§6"; // Orange
            } else {
                colorCode = "§c"; // Red
            }

            // Apply color only to the current durability number
            slot.setLore([`§rDurability: ${colorCode}${currentDurability}§8/§7${durability.maxDurability}`]);
        }
    }
});