import { render, screen, fireEvent, act } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import LoginPage from '../pages/LoginPage';

vi.mock('../context/AuthContext', () => ({
  useAuth: () => ({
    login: vi.fn(),
    user: null,
    loading: false,
    error: null,
    clearError: vi.fn(),
  }),
}));

const renderLogin = () =>
  render(
    <MemoryRouter>
      <LoginPage />
    </MemoryRouter>
  );

describe('LoginPage', () => {
  it('renders the Sign in button', () => {
    renderLogin();
    expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();
  });

  it('Sign in button is enabled when not loading', () => {
    renderLogin();
    expect(screen.getByRole('button', { name: /sign in/i })).not.toBeDisabled();
  });

  it('clicking Sign in without input triggers HTML5 validation (button stays mounted)', async () => {
    renderLogin();
    const btn = screen.getByRole('button', { name: /sign in/i });
    await act(async () => { fireEvent.click(btn); });
    expect(btn).toBeInTheDocument();
  });

  it('renders email and password inputs', () => {
    renderLogin();
    expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
    expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
  });
});
