import { getContext, setContext } from 'svelte';
import { relations, useWorld } from '../ecs';
import { useFocusedEntity, useSelectedEntity } from './useSelection.svelte';
const linkedKey = Symbol('linked-context');
export const provideLinkedEntities = () => {
    const world = useWorld();
    const selectedEntity = useSelectedEntity();
    const focusedEntity = useFocusedEntity();
    const displayEntity = $derived(selectedEntity.current ?? focusedEntity.current);
    let linkedEntities = $derived(displayEntity?.targetsFor(relations.SubEntityLink) ?? []);
    const unsubAdd = world.onAdd(relations.SubEntityLink, (entity, target) => {
        if (entity === displayEntity) {
            linkedEntities = [...linkedEntities, target];
        }
    });
    const unsubRemove = world.onRemove(relations.SubEntityLink, (entity, target) => {
        if (entity === displayEntity) {
            linkedEntities = linkedEntities.filter((e) => e !== target);
        }
    });
    const unsub = () => {
        unsubAdd();
        unsubRemove();
    };
    $effect(() => {
        return unsub;
    });
    setContext(linkedKey, {
        get current() {
            return linkedEntities;
        },
    });
};
export const useLinkedEntities = () => {
    return getContext(linkedKey);
};
