import type {
    ReactNode
} from "react";

type PortalItem = {
    children: ReactNode;
    name?: string;
    key: string;
};

let portals: PortalItem[] = [];

const listeners: Array<(portals: PortalItem[]) => void> = [];

export const context = {
    subscribe: (listener: (portals: PortalItem[]) => void) => {
        listeners.push(listener);

        return () => {
            listeners.splice(listeners.indexOf(listener), 1);
        };
    },
    mount: (key: string, children: ReactNode, name?: string) => {
        portals = [
            ...portals,
            {
                children,
                name,
                key
            }
        ];

        listeners.forEach(l => l(portals));
    },
    update: (key: string, children: ReactNode, name?: string) => {
        portals = portals.map(p => p.key === key ? {
            ...p,
            children,
            name
        } : p);

        listeners.forEach(l => l(portals));
    },
    unmount: (key: string) => {
        portals = portals.filter(p => p.key !== key);

        listeners.forEach(l => l(portals));
    }
};
