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

// Mock the API module
vi.mock('../api', () => ({
    apiFetchTasks: vi.fn(),
    apiFetchUsers: vi.fn(),
    apiCreateTask: vi.fn(),
    apiUpdateTask: vi.fn(),
    apiAddActivity: vi.fn(),
    apiLogin: vi.fn(),
}));

describe('App Component', () => {
    it('renders login page when no user is logged in', () => {
        render(<App />);
        expect(screen.getByRole('button', { name: /sig\s*n\s*in/i })).toBeInTheDocument();
    });

    it('renders main content after login', async () => {
        const mockUser = { id: 'u1', name: 'Test User', email: 'test@example.com', role: 'admin', dept: 'Engineering' };
        const mockTasks = [{ id: 't1', title: 'Task 1', status: 'todo' }];
        const mockUsers = [mockUser];

        // Mock API responses
        (api.apiLogin as any).mockResolvedValue(mockUser);
        (api.apiFetchTasks as any).mockResolvedValue(mockTasks);
        (api.apiFetchUsers as any).mockResolvedValue(mockUsers);

        render(<App />);

        // Simulate login
        const emailInput = screen.getByLabelText(/email/i);
        const passwordInput = screen.getByLabelText(/password/i);
        const loginButton = screen.getByRole('button', { name: /sig\s*n\s*in/i });

        await userEvent.type(emailInput, 'test@example.com');
        await userEvent.type(passwordInput, 'password');
        await userEvent.click(loginButton);

        // Wait for data loading
        await waitFor(() => {
            expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
        });

        // Check if main content is rendered (e.g., Sidebar, Calendar)
        expect(screen.getByText('Calendar')).toBeInTheDocument();
        expect(screen.getByText('Test User')).toBeInTheDocument();
    });
});
