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

const HUGGY_WUGGY_ID = "mebesm:huggy_wuggy";
const HUGGY_WUGGY_VENT_ID = "mebesm:huggy_wuggy_vent";
const HUGGY_WUGGY_CROUCHED_ID = "mebesm:huggy_wuggy_crouched";
const ANIMATION_START_NORMAL = "animation.huggy_wuggy.3block";
const WOUNDED_WUGGY_ID = "mebesm:huggy_wuggy_wounded";
const WOUNDED_KISSY_ID = "mebesm:kissy_missy_wounded";
const ANIMATION_START_WOUNDED = "animation.huggy_wuggy_wounded.3block";
const KISSY_MISSY_ID = "mebesm:kissy_missy";
const KISSY_MISSY_VENT_ID = "mebesm:kissy_missy_vent";
const KISSY_MISSY_CROUCHED_ID = "mebesm:kissy_missy_crouched";
const KISSY_ANIMATION_START_NORMAL = "animation.huggy_wuggy.3block";
const KISSY_ANIMATION_START_WOUNDED = "animation.kissy_missy_wounded.3block";
const ANIMATION_STOP = "animation.huggy_wuggy.reset_anim";
const ANIMATION_OPTIONS_LOOP = { loop: true, blendOutTime: 0.1 };
const ANIMATION_OPTIONS_STOP = { duration: 0.1, blendOutTime: 0.1 };
const KISSY_POPPY_ID = "mebesm:kissy_missy_poppy";
const KISSY_POPPY_ANIMATION_START = "animation.kissy_missy_poppy.3block";

function isAir(block) {
    return block?.isValid() && block.permutation.type.id === "minecraft:air";
}

function getBlock(dimension, x, y, z) {
    return dimension.getBlock({ x: Math.floor(x), y: Math.floor(y), z: Math.floor(z) });
}

function notAir(block) {
    return block?.isValid() && block.permutation.type.id !== "minecraft:air";
}

function setState(entity, state) {
    try { entity.setProperty("mebesm:huggy_state", state); } catch (e) { }
}

function setPlayerState(player, state) {
    try { player.setProperty("mebesm:huggy_player_state", state); } catch (e) { }
}

function setSpeed(entity, speed) {
    try {
        const attr = entity.getComponent("minecraft:movement");
        if (attr) attr.setCurrentValue(speed);
    } catch (e) { }
}

function updateTransformationLogic() {
    const dimension = world.getDimension("overworld");

    for (const e of dimension.getEntities({ type: HUGGY_WUGGY_ID })) {
        if (!e.isValid()) continue;
        const { x, y, z } = e.location;
        const ventBlock = getBlock(dimension, x, y + 2, z);
        const threeBlock = getBlock(dimension, x, y + 3, z);
        setState(e, notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0);
    }

    for (const e of dimension.getEntities({ type: WOUNDED_WUGGY_ID })) {
        if (!e.isValid()) continue;
        const { x, y, z } = e.location;
        const ventBlock = getBlock(dimension, x, y + 2, z);
        const threeBlock = getBlock(dimension, x, y + 3, z);
        const state = notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0;
        setState(e, state);
        setSpeed(e, 0.3);
    }

    for (const e of dimension.getEntities({ type: KISSY_MISSY_ID })) {
        if (!e.isValid()) continue;
        const { x, y, z } = e.location;
        const ventBlock = getBlock(dimension, x, y + 2, z);
        const threeBlock = getBlock(dimension, x, y + 3, z);
        setState(e, notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0);
    }

    for (const e of dimension.getEntities({ type: WOUNDED_KISSY_ID })) {
        if (!e.isValid()) continue;
        const { x, y, z } = e.location;
        const ventBlock = getBlock(dimension, x, y + 2, z);
        const threeBlock = getBlock(dimension, x, y + 3, z);
        const state = notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0;
        setState(e, state);
        setSpeed(e, 0.3);
    }

    for (const e of dimension.getEntities({ type: KISSY_POPPY_ID })) {
        if (!e.isValid()) continue;
        const { x, y, z } = e.location;
        const ventBlock = getBlock(dimension, x, y + 2, z);
        const threeBlock = getBlock(dimension, x, y + 3, z);
        const state = notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0;
        setState(e, state);
        setSpeed(e, 0.3);
    }

    for (const player of world.getAllPlayers()) {
        if (!player.isValid()) continue;

        const isHuggy = player.getProperty("mebesm:is_morphed_huggy_wuggy");
        const isHuggyWounded = player.getProperty("mebesm:is_morphed_huggy_wuggy_wounded");
        const isKissy = player.getProperty("mebesm:is_morphed_kissy_missy");
        const isKissyWounded = player.getProperty("mebesm:is_morphed_kissy_missy_wounded");

        if (!isHuggy && !isHuggyWounded && !isKissy && !isKissyWounded) {
            try {
                const cur = player.getProperty("mebesm:huggy_player_state");
                if (cur !== 0) setPlayerState(player, 0);
            } catch (_) { }
            continue;
        }

        const dim = player.dimension;
        const { x, y, z } = player.location;
        const ventBlock = getBlock(dim, x, y + 2, z);
        const threeBlock = getBlock(dim, x, y + 3, z);
        const state = notAir(ventBlock) ? 2 : notAir(threeBlock) ? 1 : 0;

        setPlayerState(player, state);
    }
}

world.afterEvents.entityDie.subscribe(e => {
    const dead = e.deadEntity;
    if (dead.typeId !== "minecraft:player") return;
    try {
        dead.removeTag("is_angry");
        dead.removeTag("noise_yarnaby");
        dead.removeTag("scream_chum_chomlkins");
        dead.removeTag("scream_yarnaby");
    } catch (_) { }
    for (const p of world.getAllPlayers()) {
        try {
            p.removeTag("is_angry");
            p.removeTag("noise_yarnaby");
            p.removeTag("scream_chum_chomlkins");
            p.removeTag("scream_yarnaby");
        } catch (_) { }
    }
    try {
        dead.dimension.runCommand("tag @e[type=mebesm:chum_chomlkins] remove is_angry");
    } catch (_) { }
});

world.beforeEvents.worldInitialize.subscribe(initEvent => {
    const registry = initEvent.blockComponentRegistry;

    registry.registerCustomComponent('besmc_poppy_box:trigger', {
        onPlayerDestroy: e => { e.dimension.runCommand("function clearPopyBox"); },
        onPlace: e => { e.dimension.runCommand("function a"); },
        onPlayerInteract: e => { e.player.runCommand("function VzaemPopyBox"); },
    });

    registry.registerCustomComponent('besmc_horizontal_bar:trigger', {
        onPlayerInteract: e => { e.player.runCommand("function flylever1"); },
    });
});

system.runInterval(() => {
    try {
        const dim = world.getDimension("overworld");
        const chums = dim.getEntities({ type: "mebesm:chum_chomlkins" }).filter(e => e.isValid());

        for (const chum of chums) {
            const gibletNearby = dim.getEntities({
                type: "mebesm:giblet",
                location: chum.location,
                maxDistance: 12
            }).some(e => e.isValid());

            if (gibletNearby) {
                if (!chum.hasTag("giblet_nearby")) chum.addTag("giblet_nearby");
                if (chum.hasTag("is_angry")) chum.removeTag("is_angry");

                if (chum.hasTag("is_screaming_chum_chomlkins")) {
                    try {
                        chum.runCommand("event entity @s mebesm:finish_scream");
                    } catch (_) { }
                }
            } else {
                if (chum.hasTag("giblet_nearby")) chum.removeTag("giblet_nearby");
            }
        }
    } catch (e) {
        console.error(`[CHUM GIBLET] ${e}`);
    }
}, 5);

world.beforeEvents.worldInitialize.subscribe(() => {
    system.runInterval(updateTransformationLogic, 5);
    console.warn("✅ [MEBESM MAIN] Mob and block logic activated.");
});