import { describe, test, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import ErrorBoundary from './ErrorBoundary.js';

describe('ErrorBoundary component', () => {
  beforeEach(() => {
    vi.spyOn(console, 'error').mockImplementation(() => {});
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  test('ErrorBoundary displays when a component crashes', async () => {
    function BuggyComponent() {
      throw new Error('Test error from BuggyComponent');
      return <div>This will never render</div>;
    }

    render(
      <ErrorBoundary>
        <BuggyComponent />
      </ErrorBoundary>,
    );

    expect(screen.getByText(/Sorry, something went wrong./i)).toBeInTheDocument();
  });

  test('onReset is called when reload button is clicked', async () => {
    const BuggyComponent = () => {
      throw new Error('Test error');
    };

    const user = userEvent.setup();
    const onReset = vi.fn();

    render(
      <ErrorBoundary onReset={onReset}>
        <BuggyComponent />
      </ErrorBoundary>,
    );

    expect(screen.getByText(/Sorry, something went wrong/i)).toBeInTheDocument();

    const button = screen.getByRole('button', { name: /reload the app/i });
    await user.click(button);

    // Verify the callback was called
    expect(onReset).toHaveBeenCalledOnce();
  });
});
