import type { WidgetRegistry, WidgetRegistryEntry } from './types';
import { useGlobal } from 'hooks/useGlobal';

export type WidgetRegistryMeta = { key: string } & WidgetRegistryEntry;

export function useWidgetRegistry(initialWidgets: WidgetRegistryMeta[] = []) {
  const [registry, setRegistry] = useGlobal<WidgetRegistry>('WIDGET_REGISTRY', () => metasToRegistry(initialWidgets));

  const registerWidget = (key: string, entry: WidgetRegistryEntry) => {
    setRegistry((prev) => ({ ...prev, [key]: entry }));
  };

  return { registry, registerWidget };
}

const metasToRegistry = (metas: WidgetRegistryMeta[]): WidgetRegistry =>
  Object.fromEntries(metas.map(({ key, ...entry }) => [key, entry]));
