import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from '@testing-library/react';
import { PluginRegistry } from '../PluginRegistry';
import { usePluginStore } from '@/store/pluginStore';
import type { PluginUiManifest } from '@/store/pluginStore';

// Mock the API hook
const mockManifests: PluginUiManifest[] = [
  {
    name: 'test_plugin',
    display_name: 'Test Plugin',
    version: '1.0.0',
    is_core: false,
    menu_items: [
      { label_key: 'nav.test', label: 'Test', path: '/test', icon: 'TestTube', group: '', order: 100, badge_key: '' },
    ],
    page_routes: [
      { path: '/test', component: '@/pages/Test', parent: '', protected: true, order: 100 },
    ],
    detail_tabs: [],
    settings_pages: [],
    dashboard_widgets: [],
    custom_fields: [],
  },
];

let mockQueryResult: any = {
  data: { plugins: mockManifests, total: 1 },
  isLoading: false,
  error: null,
};

vi.mock('@/api/pluginManifests', () => ({
  useActivePluginManifests: () => mockQueryResult,
}));

describe('PluginRegistry', () => {
  beforeEach(() => {
    usePluginStore.getState().reset();
    mockQueryResult = {
      data: { plugins: mockManifests, total: 1 },
      isLoading: false,
      error: null,
    };
  });

  it('renders nothing visible', () => {
    const { container } = render(<PluginRegistry />);
    expect(container.innerHTML).toBe('');
  });

  it('populates store with manifests on mount', () => {
    render(<PluginRegistry />);
    const manifests = usePluginStore.getState().manifests;
    expect(manifests).toHaveLength(1);
    expect(manifests[0].name).toBe('test_plugin');
  });

  it('sets loading state while fetching', () => {
    mockQueryResult = { data: null, isLoading: true, error: null };
    render(<PluginRegistry />);
    expect(usePluginStore.getState().loading).toBe(true);
  });

  it('sets error state on fetch failure', () => {
    mockQueryResult = { data: null, isLoading: false, error: new Error('Network error') };
    render(<PluginRegistry />);
    expect(usePluginStore.getState().error).toBe('Network error');
  });

  it('handles empty manifests gracefully', () => {
    mockQueryResult = { data: { plugins: [], total: 0 }, isLoading: false, error: null };
    render(<PluginRegistry />);
    const manifests = usePluginStore.getState().manifests;
    expect(manifests).toHaveLength(0);
    expect(usePluginStore.getState().loaded).toBe(true);
  });
});
