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

const SIGNAL_LAMP_ID = "mebesm:signal_lamp";
const TRIGGER_COMPONENT_ID = "wall_lamp_on:block_trigger";
const SIREN_ENTITY_ID = "mebesm:signal";
const TAG_PREFIX = "siren_at_";

function getAnchorTag(location) {
    const x = Math.floor(location.x);
    const y = Math.floor(location.y);
    const z = Math.floor(location.z);
    return `${TAG_PREFIX}${x}_${y}_${z}`;
}

function spawnSirenEntity(block) {
    const { x, y, z } = block.location;
    const anchorTag = getAnchorTag(block.location);

    try {
        const entity = block.dimension.spawnEntity(SIREN_ENTITY_ID, {
            x: x + 0.5,
            y: y,
            z: z + 0.5
        });
        entity.addTag(anchorTag);
        console.warn(`[SIREN] Спавнено моба з тегом ${anchorTag}`);
    } catch (e) {
        console.error(`[SIREN ERROR] Не вдалося заспавнити: ${e}`);
    }
}

function removeSirenEntity(block) {
    const anchorTag = getAnchorTag(block.location);
    const entities = block.dimension.getEntities({
        type: SIREN_ENTITY_ID,
        tags: [anchorTag]
    });

    if (entities.length === 0) {
        console.warn(`[SIREN WARNING] Моб з тегом ${anchorTag} не знайдено.`);
        return;
    }

    for (const entity of entities) {
        try {
            entity.kill();
            console.warn(`[SIREN] Моб з тегом ${anchorTag} видалено.`);
        } catch (e) {
            console.error(`[SIREN ERROR] Помилка при видаленні: ${e}`);
        }
    }
}

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

    registry.registerCustomComponent(TRIGGER_COMPONENT_ID, {
        onPlace: e => {
            if (e.block.typeId === SIGNAL_LAMP_ID) {
                spawnSirenEntity(e.block);
            }
        },
        onPlayerDestroy: e => {
            if (e.block.typeId === SIGNAL_LAMP_ID) {
                system.runTimeout(() => {
                    removeSirenEntity(e.block);
                }, 2);
            }
        }
    });

    console.warn("✅ Компонент сирени зареєстровано.");
});

console.warn("✅ Скрипт активний.");
