import { act, fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type Mock } from 'vitest';
import BookForm from './BookForm';

describe('BookForm', () => {
  let onSave: Mock, input: HTMLElement, submitButton: HTMLElement;
  beforeEach(() => {
    onSave = vi.fn();
    render(<BookForm onSave={onSave} />);
    input = screen.getByTestId('title-input') as HTMLInputElement;
    submitButton = screen.getByTestId('submit');
  });

  it('should save the input correctly', async () => {
    fireEvent.change(input, {
      target: { value: 'React - das umfassende Handbuch' },
    });
    fireEvent.click(submitButton);
    await act(() => Promise.resolve());

    expect(onSave).toHaveBeenCalledWith({
      title: 'React - das umfassende Handbuch',
    });
  });

  it('should show validation error for empty title', async () => {
    fireEvent.change(input, { target: { value: '' } });
    fireEvent.click(submitButton);
    await act(() => Promise.resolve());

    expect(onSave).not.toHaveBeenCalled();
    expect(screen.getByTestId('title-error').textContent).toBe(
      'Titel ist erforderlich.'
    );
  });
});
