import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { LoginPage } from './LoginPage';

const { signIn, contextError } = vi.hoisted(() => ({
    signIn: vi.fn(),
    contextError: { value: null as string | null },
}));

vi.mock('../context/AppContext', () => ({
    useApp: () => ({ user: null, loading: false, signIn, error: contextError.value }),
}));

describe('LoginPage', () => {
    beforeEach(() => {
        signIn.mockReset();
        contextError.value = null;
    });

    it('submits the email and password to the authentication context', async () => {
        signIn.mockResolvedValue(undefined);
        render(<LoginPage />);
        fireEvent.change(screen.getByLabelText('Email address'), { target: { value: 'agent@example.test' } });
        fireEvent.change(screen.getByLabelText('Password'), { target: { value: 'correct-horse' } });
        fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));

        await waitFor(() => expect(signIn).toHaveBeenCalledWith('agent@example.test', 'correct-horse'));
    });

    it('shows workspace bootstrap errors on the sign-in page', () => {
        contextError.value = 'Unable to load workspace.';
        render(<LoginPage />);
        expect(screen.getByRole('alert').textContent).toContain('Unable to load workspace.');
    });
});
