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

import SignIn from '../../src/app/(auth)/sign-in/page';

const { mockSignIn, mockToastError } = vi.hoisted(() => ({
  mockSignIn: vi.fn(),
  mockToastError: vi.fn(),
}));

vi.mock('@convex-dev/auth/react', () => ({
  useAuthActions: () => ({ signIn: mockSignIn }),
}));

vi.mock('next/navigation', () => ({
  useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}));

vi.mock('sonner', () => ({
  toast: {
    error: mockToastError,
    success: vi.fn(),
  },
}));

describe('sign-in input retention', () => {
  it('keeps the typed email and password after a failed sign-in', async () => {
    mockSignIn.mockRejectedValue(new Error('Invalid credentials'));

    render(<SignIn />);

    const emailInput = screen.getByPlaceholderText('you@example.com');
    const passwordInput = screen.getByPlaceholderText('Your password');

    fireEvent.change(emailInput, {
      target: { value: 'person@example.com' },
    });
    fireEvent.change(passwordInput, { target: { value: 'Sup3rSecret!' } });

    fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));

    await waitFor(() => expect(mockToastError).toHaveBeenCalled());

    await waitFor(() => {
      expect(emailInput).toHaveValue('person@example.com');
      expect(passwordInput).toHaveValue('Sup3rSecret!');
    });
  });
});
