import { $internal as internal } from 'koota';
import { useWorld } from './useWorld';
export function isWorld(target) {
    return typeof target?.spawn === 'function';
}
export function useTrait(target, trait) {
    const contextWorld = useWorld();
    const targetEntity = $derived(target());
    const world = $derived(isWorld(targetEntity) ? targetEntity : contextWorld);
    const entity = $derived(isWorld(targetEntity) ? targetEntity[internal].worldEntity : targetEntity);
    // Initialize the state with the current value of the trait.
    let value = $derived(entity?.get(trait));
    $effect(() => {
        const onAddUnsub = world.onAdd(trait, (e) => {
            if (e === entity) {
                value = e.get(trait);
            }
        });
        const onRemoveUnsub = world.onRemove(trait, (e) => {
            if (e === entity) {
                value = undefined;
            }
        });
        const onChangeUnsub = world.onChange(trait, (e) => {
            if (e === entity) {
                value = e.get(trait);
            }
        });
        return () => {
            onChangeUnsub();
            onAddUnsub();
            onRemoveUnsub();
        };
    });
    return {
        get current() {
            return value;
        },
    };
}
