'use client';
import { useSyncExternalStore } from 'react';

import { modalStore } from './store';

export const ModalRenderer = () => {
  const modals = useSyncExternalStore(modalStore.subscribe, modalStore.getSnapshot, modalStore.getServerSnapshot);

  return (
    <>
      {modals.map((modal) => {
        const { Component, props, id, resolve } = modal;
        return (
          <Component
            key={id}
            {...props}
            isOpen={true}
            onOpenChange={(open: boolean) => {
              if (!open) {
                resolve();
                modalStore.removeModal(id);
              }
            }}
          />
        );
      })}
    </>
  );
};
