import { useEffect, useRef } from 'react';
import { appRegistryMetas as fileBrowserMetas } from '../apps/FileBrowser';
import { appRegistryMetas as terminalMetas } from '../apps/Terminal';
import { appRegistryMetas as codeEditorMetas } from '../apps/CodeEditor';
import { appRegistryMetas as chatMetas } from '../apps/Chat';
import { appRegistryMetas as fileViewerMetas } from '../apps/FileViewer';
import { appRegistryMetas as dashboardMetas } from '../apps/Dashboards';
import { appRegistryMetas as projectMetas } from '../apps/Projects';
import { appRegistryMetas as chatHistoryMetas } from '../apps/ChatHistory';
import { appRegistryMetas as previewMetas } from '../apps/Preview';
import { appRegistryMetas as widgetMetas } from '../apps/Widgets';
import { appRegistryMetas as desktopMetas } from '../apps/Desktop';
import { appRegistryMetas as musicMetas } from '../apps/Music';
import { appRegistryMetas as soulseekMetas } from '../apps/Soulseek';
import { appRegistryMetas as monitorMetas } from '../apps/SystemMonitor';
import { useAppRegistry } from './useAppRegistry';
import { useUserApps } from 'state/useUserApps';
import { createUserAppPanel } from '../apps/UserApp/UserAppPanel';
import { createUserAppHeader } from '../apps/UserApp/UserAppHeader';
import { resolveIcon } from '../utils/resolve-icon';

const apps = [...fileBrowserMetas, ...terminalMetas, ...codeEditorMetas, ...chatMetas, ...fileViewerMetas, ...dashboardMetas, ...projectMetas, ...chatHistoryMetas, ...previewMetas, ...widgetMetas, ...desktopMetas, ...musicMetas, ...soulseekMetas, ...monitorMetas];

export const AppRegistry = () => {
  const { registerApp } = useAppRegistry(apps);
  const { apps: userApps, email } = useUserApps();
  const registeredRef = useRef(new Set<string>());

  useEffect(() => {
    if (!email || userApps.length === 0) return;

    for (const app of userApps) {
      const key = `${email}/${app.slug}`;
      if (registeredRef.current.has(key)) continue;
      registeredRef.current.add(key);

      registerApp(key, {
        name: app.name,
        icon: resolveIcon(app.icon),
        component: createUserAppPanel(app.slug),
        header: createUserAppHeader(app.name, resolveIcon(app.icon)),
      });
    }
  }, [userApps, email, registerApp]);

  return null;
};
