import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SearchErrorModal } from '../components/SearchErrorModal';

describe('SearchErrorModal', () => {
  it('renders when open', () => {
    render(<SearchErrorModal isOpen={true} error="Network error" />);
    expect(screen.getByText(/Search failed/i)).toBeInTheDocument();
  });

  it('does not render when closed', () => {
    const { container } = render(<SearchErrorModal isOpen={false} error="Network error" />);
    expect(container.firstChild?.childNodes.length).toBe(0);
  });

  it('displays error message', () => {
    const errorMsg = 'Unable to connect to server';
    render(<SearchErrorModal isOpen={true} error={errorMsg} />);
    expect(screen.getByText(errorMsg)).toBeInTheDocument();
  });

  it('calls onRetry when Retry clicked', async () => {
    const onRetry = vi.fn();
    const user = userEvent.setup();

    render(<SearchErrorModal isOpen={true} error="Error" onRetry={onRetry} canRetry={true} />);

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

    expect(onRetry).toHaveBeenCalled();
  });

  it('calls onSkip when Skip clicked', async () => {
    const onSkip = vi.fn();
    const user = userEvent.setup();

    render(<SearchErrorModal isOpen={true} error="Error" onSkip={onSkip} />);

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

    expect(onSkip).toHaveBeenCalled();
  });

  it('hides Retry button when canRetry is false', () => {
    render(<SearchErrorModal isOpen={true} error="Error" canRetry={false} />);
    expect(screen.queryByRole('button', { name: /Retry/i })).not.toBeInTheDocument();
  });
});
