/**
 * Svelte action that teleports a DOM node to a target element outside the
 * current component tree. This ensures the node is not affected by focus
 * traps, overlays, or event interceptors (e.g. Radix DismissibleLayer) that
 * are scoped to a parent Dialog/Sheet portal.
 *
 * Usage:
 *   <div use:portal>...</div>              → appended to <body>
 *   <div use:portal={'#target'}>...</div>  → appended to #target
 */
export function portal(node: HTMLElement, target: HTMLElement | string = 'body') {
	function mount() {
		const targetEl =
			typeof target === 'string'
				? (document.querySelector(target) as HTMLElement | null)
				: target;

		if (!targetEl) return;
		targetEl.appendChild(node);
	}

	mount();

	return {
		update(newTarget: HTMLElement | string) {
			target = newTarget;
			mount();
		},
		destroy() {
			node.remove();
		}
	};
}
