import { useEffect } from "react";

const useElementRemovalObserver = (
    targetId: string,
    onRemove: (removedNode: HTMLElement) => void,
    container: HTMLElement | null = document.body
): void => {
    useEffect(() => {
        if (!container) {
            console.warn("Контейнер для наблюдения не найден");
            return;
        }

        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.removedNodes.forEach((node) => {
                    if (node instanceof HTMLElement && node.id === targetId) {
                        onRemove(node);
                    }
                });
            });
        });

        observer.observe(container, { childList: true, subtree: true });

        return () => observer.disconnect();
    }, [targetId, onRemove, container]);
};

export default useElementRemovalObserver;
