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

import { LoginScreen } from '../src/platform/components/auth/LoginScreen';

describe('Google login initialization', () => {
  it('restores the sign-in action when server-owned state initialization fails', async () => {
    const initializeOAuth = vi.fn().mockRejectedValue(new Error('login-state unavailable'));
    const user = userEvent.setup();

    render(
      <LoginScreen
        onLogin={vi.fn()}
        loginError={null}
        actions={{
          getPublicLoginOptions: vi.fn().mockResolvedValue({
            providers: [{
              id: 'google',
              kind: 'federated',
              label: 'Google',
              placement: 'primary',
              clientId: 'google-client',
            }],
          }),
          forgotPassword: vi.fn(),
          initializeOAuth,
        }}
      />,
    );

    const button = await screen.findByRole('button', { name: 'Sign in with Google' });
    await user.click(button);

    expect(initializeOAuth).toHaveBeenCalledWith({
      providerId: 'google',
      clientId: 'google-client',
      authorizeContinue: undefined,
    });
    await waitFor(() => expect(button).toBeEnabled());
    expect(button).toHaveAccessibleName('Sign in with Google');
    expect(screen.getByRole('alert')).toHaveTextContent(
      'Unable to start Google sign-in. Please try again.',
    );
  });
});
