import * as game from "./game.js";
import { EquipmentSlot } from "@minecraft/server";
import * as utils from './utils.js';


const materials = ["wood", "stone", "iron", "gold", "diamond", "netherite", "copper"];
const effects = {
    poisonous: { effectTarget: "target", effectId: "poison" },
    numbing: { effectTarget: "target", effectId: "slowness" },
    withering: { effectTarget: "target", effectId: "wither" },
    weakening: { effectTarget: "target", effectId: "weakness" },
    levitation: { effectTarget: "target", effectId: "levitation" },
    fire_resistant: { effectTarget: "target", effectId: "fire" },
};

const Category3Weapons = {};
const effectDuration = 60;

for (const effectName in effects) {
    const effectData = effects[effectName];
    for (const material of materials) {
        const itemId = `tcs_cwp:${effectName}_${material}_sword`;
        Category3Weapons[itemId] = {
            ...effectData,
            effectDuration,
            effectName
        };
    }
}

export async function onEntityHurt(event) {
    const attacker = event.damageSource?.damagingEntity;
    if (!attacker || attacker.typeId !== "minecraft:player") return;

    const target = event.hurtEntity;
    if (!target) return;

    const heldItem = attacker.getComponent("minecraft:equippable")?.getEquipment(EquipmentSlot.Mainhand);
    if (!heldItem) return;

    const itemId = heldItem.typeId;
    const weapon = Category3Weapons[itemId];
    if (!weapon) return;

    if (weapon.effectId === "levitation") {
        utils.runEntityCommand(target, `particle tcs_cwp:levitation_hit`);
        game.playSound(attacker, `@a[r=7]`, `tcs_cwp:levitation_sword`, 1, 1, 1);
        target.addEffect("levitation", 80, { amplifier: 0, showParticles: true });
    } else if (weapon.effectName === "fire_resistant") {
        target.setOnFire(5);
        utils.runEntityCommand(target, `particle tcs_cwp:fire_resistant_hit`);
        game.playSound(attacker, `@a[r=7]`, `tcs_cwp:fire_resistant_sword`, 1, 1, 1);
    } else {
        const effectTarget = weapon.effectTarget === "attacker" ? attacker : target;
        effectTarget.addEffect(weapon.effectId, weapon.effectDuration, { amplifier: 0, showParticles: true });
        utils.runEntityCommand(target, `particle tcs_cwp:${weapon.effectName}_hit`);
        game.playSound(attacker, `@a[r=7]`, `tcs_cwp:${weapon.effectName}_sword`, 1, 1, 1);
    }
}

