/**
 * Comprehensive Unit Tests for LoginPage Component
 *
 * Test Coverage:
 * - Component rendering (form fields, buttons, links)
 * - Form validation
 * - Form submission and login flow
 * - Error handling and display
 * - MFA redirect flow
 * - Domain-based redirect logic (platform/business users)
 * - OAuth buttons integration
 * - Accessibility
 * - Internationalization
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
import LoginPage from '../LoginPage';
import { useLogin } from '../../hooks/useAuth';
import { useNavigate } from 'react-router-dom';

// Mock dependencies - create mock functions inside factories to avoid hoisting issues
vi.mock('../../hooks/useAuth', () => ({
  useLogin: vi.fn(),
}));

vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual('react-router-dom');
  return {
    ...actual,
    useNavigate: vi.fn(),
    Link: ({ children, to, ...props }: any) => <a href={to} {...props}>{children}</a>,
  };
});

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string) => {
      const translations: Record<string, string> = {
        'auth.email': 'Email',
        'auth.password': 'Password',
        'auth.enterEmail': 'Enter your email',
        'auth.welcomeBack': 'Welcome back',
        'auth.pleaseEnterDetails': 'Please enter your email and password to sign in.',
        'auth.signIn': 'Sign in',
        'auth.signingIn': 'Signing in...',
        'auth.authError': 'Authentication Error',
        'auth.invalidCredentials': 'Invalid credentials',
        'auth.orContinueWith': 'Or continue with',
        'marketing.tagline': 'Manage Your Business with Confidence',
        'marketing.description': 'Access your dashboard to manage appointments, customers, and grow your business.',
        'marketing.copyright': 'All rights reserved',
      };
      return translations[key] || key;
    },
  }),
}));

vi.mock('../../components/SmoothScheduleLogo', () => ({
  default: ({ className }: { className?: string }) => (
    <div className={className} data-testid="logo">Logo</div>
  ),
}));

vi.mock('../../components/OAuthButtons', () => ({
  default: ({ disabled }: { disabled?: boolean }) => (
    <div data-testid="oauth-buttons">
      <button disabled={disabled}>Google</button>
      <button disabled={disabled}>Apple</button>
    </div>
  ),
}));

vi.mock('../../components/LanguageSelector', () => ({
  default: () => <div data-testid="language-selector">Language Selector</div>,
}));

vi.mock('../../components/DevQuickLogin', () => ({
  DevQuickLogin: ({ embedded }: { embedded?: boolean }) => (
    <div data-testid="dev-quick-login" data-embedded={embedded}>Dev Quick Login</div>
  ),
}));

// Test wrapper with Router and QueryClient
const createWrapper = () => {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  });

  return ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter>{children}</BrowserRouter>
    </QueryClientProvider>
  );
};

describe('LoginPage', () => {
  let mockNavigate: ReturnType<typeof vi.fn>;
  let mockLoginMutate: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    vi.clearAllMocks();

    // Setup mocks
    mockNavigate = vi.fn();
    vi.mocked(useNavigate).mockReturnValue(mockNavigate);

    mockLoginMutate = vi.fn();
    vi.mocked(useLogin).mockReturnValue({
      mutate: mockLoginMutate,
      mutateAsync: vi.fn(),
      isPending: false,
    });

    // Mock window.location
    Object.defineProperty(window, 'location', {
      value: {
        hostname: 'platform.lvh.me',
        port: '5173',
        protocol: 'http:',
        href: 'http://platform.lvh.me:5173/',
      },
      writable: true,
      configurable: true,
    });

    // Mock sessionStorage
    global.sessionStorage = {
      getItem: vi.fn(),
      setItem: vi.fn(),
      removeItem: vi.fn(),
      clear: vi.fn(),
      key: vi.fn(),
      length: 0,
    };
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe('Rendering', () => {
    it('should render login form', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByRole('heading', { name: /welcome back/i })).toBeInTheDocument();
      expect(screen.getByText('Please enter your email and password to sign in.')).toBeInTheDocument();
    });

    it('should render email input field', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      expect(emailInput).toBeInTheDocument();
      expect(emailInput).toHaveAttribute('type', 'email');
      expect(emailInput).toHaveAttribute('name', 'email');
      expect(emailInput).toHaveAttribute('required');
      expect(emailInput).toHaveAttribute('placeholder', 'Enter your email');
    });

    it('should render password input field', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const passwordInput = screen.getByLabelText(/password/i);
      expect(passwordInput).toBeInTheDocument();
      expect(passwordInput).toHaveAttribute('type', 'password');
      expect(passwordInput).toHaveAttribute('name', 'password');
      expect(passwordInput).toHaveAttribute('required');
      expect(passwordInput).toHaveAttribute('placeholder', '••••••••');
    });

    it('should render submit button', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const submitButton = screen.getByRole('button', { name: /sign in/i });
      expect(submitButton).toBeInTheDocument();
      expect(submitButton).toHaveAttribute('type', 'submit');
    });

    it('should render email and password icons', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      // lucide-react renders SVG elements
      const form = screen.getByRole('heading', { name: /welcome back/i }).closest('div')?.parentElement;
      const svgs = form?.querySelectorAll('svg');

      // Should have icons for email, password, and arrow in button
      expect(svgs).toBeDefined();
      expect(svgs!.length).toBeGreaterThanOrEqual(2);
    });

    it('should render logo', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const logos = screen.getAllByTestId('logo');
      expect(logos.length).toBeGreaterThan(0);
    });

    it('should render branding section on desktop', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByText('Manage Your Business with Confidence')).toBeInTheDocument();
      expect(screen.getByText(/access your dashboard/i)).toBeInTheDocument();
    });
  });

  describe('OAuth Integration', () => {
    it('should render OAuth buttons', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByTestId('oauth-buttons')).toBeInTheDocument();
    });

    it('should display OAuth divider text', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByText('Or continue with')).toBeInTheDocument();
    });

    it('should disable OAuth buttons when login is pending', () => {
      vi.mocked(useLogin).mockReturnValue({
        mutate: vi.fn(),
        mutateAsync: vi.fn(),
        isPending: true,
      });

      render(<LoginPage />, { wrapper: createWrapper() });

      const oauthButtons = screen.getAllByRole('button', { name: /google|apple/i });
      oauthButtons.forEach(button => {
        expect(button).toBeDisabled();
      });
    });
  });

  describe('Additional Components', () => {
    it('should render language selector', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByTestId('language-selector')).toBeInTheDocument();
    });

    it('should render dev quick login component', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const devQuickLogin = screen.getByTestId('dev-quick-login');
      expect(devQuickLogin).toBeInTheDocument();
      expect(devQuickLogin).toHaveAttribute('data-embedded', 'true');
    });

    it('should display copyright text', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const currentYear = new Date().getFullYear();
      expect(screen.getByText(`© ${currentYear} All rights reserved`)).toBeInTheDocument();
    });
  });

  describe('Form Input Handling', () => {
    it('should update email field on input', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i) as HTMLInputElement;
      await user.type(emailInput, 'test@example.com');

      expect(emailInput.value).toBe('test@example.com');
    });

    it('should update password field on input', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const passwordInput = screen.getByLabelText(/password/i) as HTMLInputElement;
      await user.type(passwordInput, 'password123');

      expect(passwordInput.value).toBe('password123');
    });

    it('should handle empty form submission', async () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const submitButton = screen.getByRole('button', { name: /sign in/i });
      fireEvent.click(submitButton);

      // HTML5 validation should prevent submission
      expect(mockLoginMutate).not.toHaveBeenCalled();
    });
  });

  describe('Form Submission', () => {
    it('should call login mutation with email and password', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      expect(mockLoginMutate).toHaveBeenCalledWith(
        { email: 'test@example.com', password: 'password123' },
        expect.any(Object)
      );
    });

    it('should clear error state on new submission', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      // First submission - simulate error
      await user.type(emailInput, 'wrong@example.com');
      await user.type(passwordInput, 'wrongpass');
      await user.click(submitButton);

      // Trigger error callback
      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;
      onError({ response: { data: { error: 'Invalid credentials' } } });

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
      });

      // Clear inputs and try again
      await user.clear(emailInput);
      await user.clear(passwordInput);
      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Error should be cleared before new submission
      expect(screen.queryByText('Invalid credentials')).not.toBeInTheDocument();
    });

    it('should disable submit button when login is pending', () => {
      vi.mocked(useLogin).mockReturnValue({
        mutate: vi.fn(),
        mutateAsync: vi.fn(),
        isPending: true,
      });

      render(<LoginPage />, { wrapper: createWrapper() });

      const submitButton = screen.getByRole('button', { name: /signing in/i });
      expect(submitButton).toBeDisabled();
    });

    it('should show loading state in submit button', () => {
      vi.mocked(useLogin).mockReturnValue({
        mutate: vi.fn(),
        mutateAsync: vi.fn(),
        isPending: true,
      });

      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByText('Signing in...')).toBeInTheDocument();

      // Should have loading spinner (Loader2 icon)
      const button = screen.getByRole('button', { name: /signing in/i });
      const svg = button.querySelector('svg');
      expect(svg).toBeInTheDocument();
    });
  });

  describe('Error Handling', () => {
    it('should display error message on login failure', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'wrongpassword');
      await user.click(submitButton);

      // Simulate error
      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;
      onError({ response: { data: { error: 'Invalid credentials' } } });

      await waitFor(() => {
        expect(screen.getByText('Authentication Error')).toBeInTheDocument();
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
      });
    });

    it('should display default error message when no specific error provided', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate error without message
      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;
      onError({});

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
      });
    });

    it('should show error icon in error message', async () => {
      const user = userEvent.setup();
      const { container } = render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'wrongpassword');
      await user.click(submitButton);

      // Simulate error with act to wrap state updates
      await waitFor(() => {
        const callArgs = mockLoginMutate.mock.calls[0];
        expect(callArgs).toBeDefined();
      });

      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;

      await act(async () => {
        onError({ response: { data: { error: 'Invalid credentials' } } });
      });

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
        const errorBox = screen.getByTestId('error-message');
        const svg = errorBox?.querySelector('svg');
        expect(svg).toBeInTheDocument();
      });
    });
  });

  describe('MFA Flow', () => {
    it('should redirect to MFA page when MFA is required', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate MFA required response
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        mfa_required: true,
        user_id: 123,
        mfa_methods: ['sms', 'totp'],
        phone_last_4: '1234',
      });

      await waitFor(() => {
        expect(sessionStorage.setItem).toHaveBeenCalledWith(
          'mfa_challenge',
          JSON.stringify({
            user_id: 123,
            mfa_methods: ['sms', 'totp'],
            phone_last_4: '1234',
          })
        );
        expect(mockNavigate).toHaveBeenCalledWith('/mfa-verify');
      });
    });

    it('should not navigate to dashboard when MFA is required', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate MFA required response
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        mfa_required: true,
        user_id: 123,
        mfa_methods: ['sms'],
        phone_last_4: '1234',
      });

      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith('/mfa-verify');
        expect(mockNavigate).not.toHaveBeenCalledWith('/');
      });
    });
  });

  describe('Domain-based Redirects', () => {
    it('should navigate to dashboard for platform user on platform domain', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'admin@platform.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate successful login for platform user
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        access: 'access-token',
        refresh: 'refresh-token',
        user: {
          id: 1,
          email: 'admin@platform.com',
          role: 'superuser',
          first_name: 'Admin',
          last_name: 'User',
        },
      });

      await waitFor(() => {
        expect(mockNavigate).toHaveBeenCalledWith('/');
      });
    });

    it('should show error when platform user tries to login on business subdomain', async () => {
      // Mock business subdomain
      Object.defineProperty(window, 'location', {
        value: {
          hostname: 'demo.lvh.me',
          port: '5173',
          protocol: 'http:',
        },
        writable: true,
      });

      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'admin@platform.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate platform user login on business subdomain
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        access: 'access-token',
        refresh: 'refresh-token',
        user: {
          id: 1,
          email: 'admin@platform.com',
          role: 'superuser',
        },
      });

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
        expect(mockNavigate).not.toHaveBeenCalled();
      });
    });

    it('should redirect business user to their business subdomain', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'owner@demo.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate business user login from platform domain
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        access: 'access-token',
        refresh: 'refresh-token',
        user: {
          id: 2,
          email: 'owner@demo.com',
          role: 'owner',
          business_subdomain: 'demo',
        },
      });

      await waitFor(() => {
        expect(window.location.href).toContain('demo.lvh.me');
        expect(window.location.href).toContain('access_token=access-token');
        expect(window.location.href).toContain('refresh_token=refresh-token');
      });
    });

    it('should show error when customer tries to login on root domain', async () => {
      // Mock root domain
      Object.defineProperty(window, 'location', {
        value: {
          hostname: 'lvh.me',
          port: '5173',
          protocol: 'http:',
        },
        writable: true,
      });

      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'customer@example.com');
      await user.type(passwordInput, 'password123');
      await user.click(submitButton);

      // Simulate customer login on root domain
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        access: 'access-token',
        refresh: 'refresh-token',
        user: {
          id: 3,
          email: 'customer@example.com',
          role: 'customer',
          business_subdomain: 'demo',
        },
      });

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
        expect(mockNavigate).not.toHaveBeenCalled();
      });
    });
  });

  describe('Accessibility', () => {
    it('should have proper form labels', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
      expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
    });

    it('should have required attributes on inputs', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByLabelText(/email/i)).toHaveAttribute('required');
      expect(screen.getByLabelText(/password/i)).toHaveAttribute('required');
    });

    it('should have proper input types', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByLabelText(/email/i)).toHaveAttribute('type', 'email');
      expect(screen.getByLabelText(/password/i)).toHaveAttribute('type', 'password');
    });

    it('should have autocomplete attributes', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByLabelText(/email/i)).toHaveAttribute('autoComplete', 'email');
      expect(screen.getByLabelText(/password/i)).toHaveAttribute('autoComplete', 'current-password');
    });

    it('should have accessible logo links', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const links = screen.getAllByRole('link');
      const logoLinks = links.filter(link => link.getAttribute('href') === '/');

      expect(logoLinks.length).toBeGreaterThan(0);
    });
  });

  describe('Internationalization', () => {
    it('should use translations for form labels', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByText('Email')).toBeInTheDocument();
      expect(screen.getByText('Password')).toBeInTheDocument();
    });

    it('should use translations for buttons', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();
    });

    it('should use translations for headings', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByRole('heading', { name: /welcome back/i })).toBeInTheDocument();
    });

    it('should use translations for placeholders', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      expect(screen.getByPlaceholderText('Enter your email')).toBeInTheDocument();
      expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
    });

    it('should use translations for error messages', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'wrongpassword');
      await user.click(submitButton);

      // Simulate error
      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;
      onError({});

      await waitFor(() => {
        expect(screen.getByText('Authentication Error')).toBeInTheDocument();
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
      });
    });
  });

  describe('Visual State', () => {
    it('should have proper styling classes on form elements', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      expect(emailInput).toHaveClass('focus:ring-brand-500', 'focus:border-brand-500');

      const passwordInput = screen.getByLabelText(/password/i);
      expect(passwordInput).toHaveClass('focus:ring-brand-500', 'focus:border-brand-500');
    });

    it('should have proper button styling', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      const submitButton = screen.getByRole('button', { name: /sign in/i });
      expect(submitButton).toHaveClass('bg-brand-600', 'hover:bg-brand-700');
    });

    it('should have error styling when error is displayed', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      const emailInput = screen.getByLabelText(/email/i);
      const passwordInput = screen.getByLabelText(/password/i);
      const submitButton = screen.getByRole('button', { name: /sign in/i });

      await user.type(emailInput, 'test@example.com');
      await user.type(passwordInput, 'wrongpassword');
      await user.click(submitButton);

      // Simulate error with act to wrap state updates
      await waitFor(() => {
        const callArgs = mockLoginMutate.mock.calls[0];
        expect(callArgs).toBeDefined();
      });

      const callArgs = mockLoginMutate.mock.calls[0];
      const onError = callArgs[1].onError;

      await act(async () => {
        onError({ response: { data: { error: 'Invalid credentials' } } });
      });

      await waitFor(() => {
        expect(screen.getByText('Invalid credentials')).toBeInTheDocument();
        const errorBox = screen.getByTestId('error-message');
        expect(errorBox).toHaveClass('bg-red-50', 'dark:bg-red-900/20');
      });
    });
  });

  describe('Integration', () => {
    it('should handle complete login flow successfully', async () => {
      const user = userEvent.setup();
      render(<LoginPage />, { wrapper: createWrapper() });

      // Fill in form
      await user.type(screen.getByLabelText(/email/i), 'owner@demo.com');
      await user.type(screen.getByLabelText(/password/i), 'password123');

      // Submit form
      await user.click(screen.getByRole('button', { name: /sign in/i }));

      // Verify mutation was called
      expect(mockLoginMutate).toHaveBeenCalledWith(
        { email: 'owner@demo.com', password: 'password123' },
        expect.any(Object)
      );

      // Simulate successful response
      const callArgs = mockLoginMutate.mock.calls[0];
      const onSuccess = callArgs[1].onSuccess;
      onSuccess({
        access: 'access-token',
        refresh: 'refresh-token',
        user: {
          id: 1,
          email: 'owner@demo.com',
          role: 'owner',
          business_subdomain: 'demo',
        },
      });

      // Since we're on platform domain and user is business owner, should redirect
      await waitFor(() => {
        expect(window.location.href).toContain('demo');
      });
    });

    it('should render all sections together', () => {
      render(<LoginPage />, { wrapper: createWrapper() });

      // Form elements
      expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
      expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
      expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();

      // Additional components
      expect(screen.getByTestId('oauth-buttons')).toBeInTheDocument();
      expect(screen.getByTestId('language-selector')).toBeInTheDocument();
      expect(screen.getByTestId('dev-quick-login')).toBeInTheDocument();

      // Branding
      expect(screen.getAllByTestId('logo').length).toBeGreaterThan(0);
      expect(screen.getByText('Manage Your Business with Confidence')).toBeInTheDocument();
    });
  });
});
