/**
 * Svelte action: click outside detection
 * Usage: <div use:clickOutside={onClickOutside}>
 * Calls the callback when a click occurs outside the element.
 */
export function clickOutside(node: HTMLElement, callback: () => void) {
    function handleClick(event: MouseEvent) {
        if (!node.contains(event.target as Node)) {
            callback()
        }
    }

    // Delay adding the listener to avoid catching the triggering click
    setTimeout(() => {
        document.addEventListener("click", handleClick, true)
    }, 0)

    return {
        update(newCallback: () => void) {
            callback = newCallback
        },
        destroy() {
            document.removeEventListener("click", handleClick, true)
        },
    }
}
