import React from 'react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import AppErrorBoundary from './AppErrorBoundary';

const Boom = (): JSX.Element => {
  throw new Error('dashboard exploded');
};

describe('AppErrorBoundary', () => {
  let consoleError: jest.SpyInstance;

  beforeEach(() => {
    consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
  });

  afterEach(() => {
    consoleError.mockRestore();
  });

  it('renders children when nothing throws', () => {
    render(
      <MemoryRouter>
        <AppErrorBoundary>
          <div>chat loaded</div>
        </AppErrorBoundary>
      </MemoryRouter>,
    );

    expect(screen.getByText('chat loaded')).toBeInTheDocument();
  });

  it('shows the failure details instead of a blank screen', () => {
    render(
      <MemoryRouter>
        <AppErrorBoundary>
          <Boom />
        </AppErrorBoundary>
      </MemoryRouter>,
    );

    expect(screen.getByRole('alert')).toBeInTheDocument();
    expect(screen.getByText(/Something broke on this screen/i)).toBeInTheDocument();
    expect(screen.getByText(/dashboard exploded/)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /reload/i })).toBeInTheDocument();
  });
});
