import { useEffect } from 'react';
import { useActivePluginManifests } from '@/api/pluginManifests';
import { usePluginStore } from '@/store/pluginStore';

/**
 * PluginRegistry — invisible provider component that fetches active plugin
 * UI manifests on mount and populates the plugin store.
 *
 * Must be placed inside AppShell or at the root of the protected route tree.
 */
export function PluginRegistry() {
  const { data, isLoading, error } = useActivePluginManifests();
  const setManifests = usePluginStore((s) => s.setManifests);
  const setLoading = usePluginStore((s) => s.setLoading);
  const setError = usePluginStore((s) => s.setError);

  useEffect(() => {
    setLoading(isLoading);
  }, [isLoading, setLoading]);

  useEffect(() => {
    if (data?.plugins) {
      setManifests(data.plugins);
    }
  }, [data, setManifests]);

  useEffect(() => {
    if (error) {
      setError(error instanceof Error ? error.message : 'Failed to load plugin manifests');
    }
  }, [error, setError]);

  // This component renders nothing visible
  return null;
}
