import { world, ItemStack, system, GameMode, EquipmentSlot } from '@minecraft/server';

/* ITENS QUE DEVEM GASTAR */
const tools = [
    'well:picareta_de_prismarinho',
	'well:picareta_de_ametista',
	'well:picareta_ruby',
	'well:enxada_ruby',
	'well:espada_ruby',
	'well:machado_ruby',
	'well:pa_ruby',
	
	'well:cajado_almas',
	'well:cajado_gelo',
	'well:cajado_sangue',
	'well:cajado_sombrio',
	'well:cajado_venenoso'
	
	
];

world.afterEvents.playerBreakBlock.subscribe(ev => {

    const player = ev.player;
    const itemUsed = ev.itemStackAfterBreak;

    // sem item ou creative → ignora
    if (!itemUsed) return;
    if (player.getGameMode() === GameMode.creative) return;

    // verifica se é nossa ferramenta
    if (!tools.includes(itemUsed.typeId)) return;

    /* PEGAR UNBREAKING */
    let unbreaking = 0;
    const enchComp = itemUsed.getComponent("minecraft:enchantments");
    if (enchComp) {
        const ench = enchComp.enchantments.getEnchantment("unbreaking");
        if (ench) unbreaking = ench.level;
    }

    /* CHANCE VANILLA */
    const breakChance = 100 / (unbreaking + 1);
    if (Math.random() * 100 > breakChance) return;

    /* PEGAR DURABILITY */
    const durability = itemUsed.getComponent("minecraft:durability");
    if (!durability) {
        player.sendMessage("§cITEM SEM DURABILITY!");
        return;
    }

    durability.damage += 1;

    const equip = player.getComponent("minecraft:equippable");

    // QUEBROU?
    if (durability.damage >= durability.maxDurability) {
        player.playSound("random.break");
        equip.setEquipment(EquipmentSlot.Mainhand, new ItemStack("minecraft:air"));
        return;
    }

    // atualizar item na mão
    equip.setEquipment(EquipmentSlot.Mainhand, itemUsed);

});

/* ================================
   GASTAR DURABILIDADE AO USAR ITEM
================================ */

world.afterEvents.itemUse.subscribe(ev => {

    const player = ev.source;
    const itemUsed = ev.itemStack;

    if (!player) return;
    if (!itemUsed) return;
    if (player.getGameMode() === GameMode.creative) return;

    // só nossos itens
    if (!tools.includes(itemUsed.typeId)) return;

    /* PEGAR UNBREAKING */
    let unbreaking = 0;
    const enchComp = itemUsed.getComponent("minecraft:enchantments");
    if (enchComp) {
        const ench = enchComp.enchantments.getEnchantment("unbreaking");
        if (ench) unbreaking = ench.level;
    }

    /* CHANCE VANILLA */
    const breakChance = 100 / (unbreaking + 1);
    if (Math.random() * 100 > breakChance) return;

    const durability = itemUsed.getComponent("minecraft:durability");
    if (!durability) return;

    durability.damage += 1;

    const equip = player.getComponent("minecraft:equippable");

    // QUEBROU?
    if (durability.damage >= durability.maxDurability) {
        player.playSound("random.break");
        equip.setEquipment(EquipmentSlot.Mainhand, new ItemStack("minecraft:air"));
        return;
    }

    equip.setEquipment(EquipmentSlot.Mainhand, itemUsed);

});

/* ================================
   GASTAR DURABILIDADE SEGURANDO ITEM
================================ */


const drainItems = [
    "well:lamparina"
];

function drainSlot(player, slot) {

    const equip = player.getComponent("minecraft:equippable");
    const item = equip.getEquipment(slot);
    if (!item) return;

    if (!drainItems.includes(item.typeId)) return;

    const durability = item.getComponent("minecraft:durability");
    if (!durability) return;

    // 🔴 Se chegou no último ponto → trava e desliga luz
    if (durability.damage >= durability.maxDurability - 1) {

        durability.damage = durability.maxDurability - 1;
        equip.setEquipment(slot, item);

        player.runCommand("scoreboard players set @s iluminacao 0");
        player.runCommand("scoreboard players add @s iluminacao_descarga 1");
        return;
    }

    // 🔻 gasta durabilidade
    durability.damage += 1;
    equip.setEquipment(slot, item);
}

system.runInterval(() => {

    for (const player of world.getPlayers()) {

        if (player.getGameMode() === GameMode.creative) continue;

        drainSlot(player, EquipmentSlot.Mainhand);
        drainSlot(player, EquipmentSlot.Offhand);
    }

}, 40);

system.run(function lampLoop() {

    for (const player of world.getPlayers()) {

        const equip = player.getComponent("minecraft:equippable");
        if (!equip) continue;

        const main = equip.getEquipment(EquipmentSlot.Mainhand);
        const off  = equip.getEquipment(EquipmentSlot.Offhand);

        let lamparina = null;

        // procura lamparina em qualquer mão
        if (main && main.typeId === "well:lamparina") lamparina = main;
        if (off  && off.typeId === "well:lamparina") lamparina = off;

        if (!lamparina) continue;

        const durability = lamparina.getComponent("minecraft:durability");
        if (!durability) continue;

        // 🔴 SE ESTIVER NO ÚLTIMO PONTO → NÃO CRIA LUZ
        if (durability.damage >= durability.maxDurability - 1) continue;

        // 🟡 TEM CARGA → cria luz todo tick ⚡
        player.runCommand("fill ~ ~ ~ ~ ~5 ~ well:luz [] replace air");
    }

    system.run(lampLoop);
});



/* ================================
   RECARREGAR LAMPARINA COM NÉCTAR
================================ */


world.afterEvents.itemUse.subscribe(ev => {

    const player = ev.source;
    const itemUsed = ev.itemStack;
    if (!player || !itemUsed) return;

    // Só roda se usar o néctar
    if (itemUsed.typeId !== "well:nectar_frasco") return;

    const equip = player.getComponent("minecraft:equippable");

    // 🔹 AGORA PEGA A OFFHAND
    const offhandItem = equip.getEquipment(EquipmentSlot.Offhand);

    // Precisa estar segurando a lamparina na offhand
    if (!offhandItem || offhandItem.typeId !== "well:lamparina") {
        player.sendMessage("§cColoque a lamparina na mão esquerda para recarregar!");
        return;
    }

    const durability = offhandItem.getComponent("minecraft:durability");
    if (!durability) return;

    // 🔋 Enche toda durabilidade
    durability.damage = 0;
    equip.setEquipment(EquipmentSlot.Offhand, offhandItem);

    // Liga iluminação novamente
    player.runCommand("scoreboard players set @s iluminacao 300");

    // Consome 1 néctar
    player.runCommand("clear @s well:nectar_frasco 0 1");

    // Som satisfatório 😌
    player.playSound("random.orb");
});
