import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';

// We test the error boundary and component cache directly
// by importing the module internals
import { PluginPage } from '../PluginLoader';

// The PluginErrorBoundary is not exported, so we test through PluginPage
// The componentCache is module-level and persists across tests

describe('PluginPage', () => {
  it('shows error fallback when component fails to load', async () => {
    // Use a non-existent component path - the dynamic import will fail
    render(<PluginPage component="@/pages/NonExistentPage" pluginName="broken" />);
    
    // The error boundary should catch the import error and show fallback
    const errorMsg = await screen.findByText(/Failed to load plugin/);
    expect(errorMsg).toBeInTheDocument();
    expect(errorMsg).toHaveTextContent('broken');
  });

  it('shows error fallback with correct plugin name', async () => {
    render(<PluginPage component="@/pages/AnotherMissingPage" pluginName="my_custom_plugin" />);
    
    const errorMsg = await screen.findByText(/Failed to load plugin/);
    expect(errorMsg).toHaveTextContent('my_custom_plugin');
  });

  it('error boundary catches import errors and shows fallback UI', async () => {
    render(<PluginPage component="@/pages/NonExistentPage" pluginName="test" />);
    
    // The error boundary should catch the failed dynamic import
    const alert = await screen.findByRole('alert');
    expect(alert).toBeInTheDocument();
    expect(alert).toHaveTextContent('Failed to load plugin: test');
    
    // Verify the error message has the correct CSS classes
    expect(alert.className).toContain('text-red-600');
  });

  it('handles empty component path gracefully', async () => {
    render(<PluginPage component="" pluginName="empty" />);
    
    const alert = await screen.findByRole('alert');
    expect(alert).toHaveTextContent('Failed to load plugin: empty');
  });

  it('error boundary has role="alert" for accessibility', async () => {
    render(<PluginPage component="@/pages/MissingPage" pluginName="test" />);
    
    const alert = await screen.findByRole('alert');
    expect(alert).toBeInTheDocument();
    expect(alert).toHaveTextContent('Failed to load plugin: test');
  });

  it('handles different plugin names in error boundary', async () => {
    render(<PluginPage component="@/pages/YetAnotherMissing" pluginName="plugin_x" />);
    
    const alert = await screen.findByRole('alert');
    expect(alert).toHaveTextContent('plugin_x');
  });
});
