import { JSX, onCleanup, onMount} from "solid-js";

type Children = Array<JSX.Element> | JSX.Element;
export function Dialog(props: {onClose: () => void, children: Children, class?: string}) {
    const positionClasses = () => (props.class ?? "fixed w-screen h-screen top-0 left-0");

    const clickOutsideFn = (ev: MouseEvent) => {
        const target = ev.target as HTMLElement;
        if (target.closest(".modal") === null) {
            props.onClose();
        }
    };

    onMount(() => {
        setTimeout(() => {
            // For some reason this event is fired immediately after the component is mounted,
            // so we delay the event installation to the next tick.
            window.addEventListener("click", clickOutsideFn);
        }, 0);
    });

    onCleanup(() => {
        window.removeEventListener("click", clickOutsideFn);
    });

    return (
        <div class={`modal transition-colors bg-c-background ${positionClasses()}`}>
            {props.children}
        </div>
    );
}
