import type { ComponentType } from 'react';

interface ModalData {
  id: string;
  scopeId: string;
  Component: ComponentType<any>;
  props: Record<string, unknown>;
  resolve: () => void;
}

let modals: ModalData[] = [];
let listeners: (() => void)[] = [];

const emitChange = () => {
  listeners.forEach((listener) => listener());
};

const SERVER_SNAPSHOT: ModalData[] = [];

export const modalStore = {
  subscribe: (listener: () => void) => {
    listeners = [...listeners, listener];
    return () => {
      listeners = listeners.filter((l) => l !== listener);
    };
  },
  getSnapshot: () => modals,
  getServerSnapshot: () => SERVER_SNAPSHOT,
  addModal: (modal: ModalData) => {
    modals = [...modals, modal];
    emitChange();
  },
  removeModal: (id: string) => {
    modals = modals.filter((m) => m.id !== id);
    emitChange();
  },
  removeByScope: (scopeId: string) => {
    modals = modals.filter((m) => m.scopeId !== scopeId);
    emitChange();
  },
};

export type { ModalData };
