import { world, system, EquipmentSlot } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";

const RESISTANCE_AMPLIFIER = 255;
const SHORT_DURATION_TICKS = 10;
const BURN_INTERVAL_TICKS = 60;

export async function onLoad() {
}

export async function onTick() {
    for (const player of world.getAllPlayers()) {
        if (!player || !player.isValid()) continue;

        const mainhandItem = utils.getItemInHand(player);
        const offhandItem = utils.getItemInOffHand(player);
        const hasFireShield = (mainhandItem && mainhandItem.typeId === "tcs_cwp:fire_shield") ||
                             (offhandItem && offhandItem.typeId === "tcs_cwp:fire_shield");

        if (hasFireShield && player.isSneaking) {
            player.addEffect("minecraft:resistance", SHORT_DURATION_TICKS, { amplifier: RESISTANCE_AMPLIFIER, showParticles: false });
            
            // Trigger burn every 3 seconds while sneaking
            if (system.currentTick % BURN_INTERVAL_TICKS === 0) {
                await burnNearby(player);
            }
        }
    }
}

export async function onEntityHurt(event) {
    let entity = event.hurtEntity;

    if(entity.typeId !== "minecraft:player") return;

    const mainhandItem = utils.getItemInHand(entity);
    const offhandItem = utils.getItemInOffHand(entity);

    if(mainhandItem && mainhandItem.typeId === "tcs_cwp:fire_shield") {
        if(inventory_utils.damageItem(entity, EquipmentSlot.Mainhand, 1)) {
            entity.runCommandAsync(`playsound random.break`);
        }
    } else if (offhandItem && offhandItem.typeId === "tcs_cwp:fire_shield") {
        if(inventory_utils.damageItem(entity, EquipmentSlot.Offhand, 1)) {
            entity.runCommandAsync(`playsound random.break`);
        }
    }
}

async function burnNearby(player) {
    const entities = await utils.getAllEntitiesInRange(player.dimension, player.location, 0, 3);
    for (const entity of entities) {
        if (!entity || !entity.isValid()) continue;
        if (entity.id === player.id) continue;
        if (entity.typeId === "minecraft:item" || entity.typeId === "minecraft:xp_orb") continue;
        try { entity.setOnFire(4, true); } catch (e) {}
    }
}
