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

// const purificationEffects1 = ["poison", "hunger", "slowness", "weakness", "nausea"];
const purificationEffects2 = ["poison", "hunger", "slowness", "weakness", "nausea", "blindness", "wither", "fatal_poison", "mining_fatigue", "darkness"];

function removeEffects(player, effects) {
    effects.forEach(effect => player.removeEffect(effect));
}

world.afterEvents.itemCompleteUse.subscribe(use => {
    const player = use.source;
    const item = use.itemStack;
    const itemType = item.typeId;

    switch (itemType) {
        case "fiery:healing_potion1":
            player.addEffect("instant_health", 1, { amplifier: 0, showParticles: false });
            player.dimension.spawnParticle('fiery:regeneration', {
                x: player.location.x,
                y: player.location.y + 1,
                z: player.location.z
            });
            break;
        case "fiery:healing_potion2":
            player.addEffect("instant_health", 1, { amplifier: 1, showParticles: false });
            player.dimension.spawnParticle('fiery:regeneration', {
                x: player.location.x,
                y: player.location.y + 1,
                z: player.location.z
            });
            break;
        case "fiery:tough_potion1":
            player.addEffect("resistance", 90 * 20, { amplifier: 0, showParticles: true });
            break;
        case "fiery:tough_potion2":
            player.addEffect("resistance", 45 * 20, { amplifier: 1, showParticles: true });
            break;
        case "fiery:purification_potion1":
            let duration1 = 30 * 20;
            const interval1 = system.runInterval(() => {
                if (duration1 <= 0) {
                    system.clearRun(interval1);
                } else {
                    removeEffects(player, purificationEffects2);
                    player.dimension.spawnParticle('fiery:soul_regeneration', {
                        x: player.location.x,
                        y: player.location.y + 1,
                        z: player.location.z
                    });
                    duration1 -= 20;
                }
            }, 20);
            break;
        case "fiery:purification_potion2":
            let duration2 = 60 * 20;
            const interval2 = system.runInterval(() => {
                if (duration2 <= 0) {
                    system.clearRun(interval2);
                } else {
                    removeEffects(player, purificationEffects2);
                    player.dimension.spawnParticle('fiery:soul_regeneration', {
                        x: player.location.x,
                        y: player.location.y + 1,
                        z: player.location.z
                    });
                    duration2 -= 20;
                }
            }, 20);
            break;
    }
});
