import { useEffect, useRef } from "react";

import { Dialog } from "@/shared";

import { useDialogStore } from "../lib/useDialogStore";

export function DialogsContextProvider() {
	const dialogRef = useRef<HTMLDialogElement>(null);
	const { stack, close } = useDialogStore();

	useEffect(() => {
		if (stack.length === 0) {
			return;
		}

		dialogRef.current?.focus();
	}, [stack]);

	if (stack.length === 0) {
		return null;
	}

	return (
		<>
			{stack.map((content) => (
				<Dialog 
					defaultOpen 
					key={content.key} 
					onOpenChange={(open) => {
						if (!open) {
							close();
						}
					}}
				>
					{content.content}
				</Dialog>
			))}
		</>
	);
}
