import { $internal as internal } from 'koota';
import { useWorld } from './useWorld';
export function isWorld(target) {
    return typeof target?.spawn === 'function';
}
export function useTag(target, tag) {
    const contextWorld = useWorld();
    let value = $state(false);
    $effect(() => {
        const t = target();
        if (!t) {
            value = false;
            return;
        }
        const world = isWorld(t) ? t : contextWorld;
        // ???
        // eslint-disable-next-line prefer-const
        let entity;
        /**
         * Subscribe before reading worldEntity: world.onAdd triggers lazy
         * registration so worldEntity is guaranteed to exist after this.
         */
        const onAddUnsub = world.onAdd(tag, (e) => {
            if (e === entity)
                value = true;
        });
        const onRemoveUnsub = world.onRemove(tag, (e) => {
            if (e === entity)
                value = false;
        });
        entity = isWorld(t) ? t[internal].worldEntity : t;
        value = entity.has(tag);
        return () => {
            onAddUnsub();
            onRemoveUnsub();
        };
    });
    return {
        get current() {
            return value;
        },
    };
}
