import { test, expect } from './fixtures';

test.describe('I. Core & Authentication', () => {

    test.beforeEach(async ({ page }) => {
        // Console logs for debugging
        page.on('console', msg => console.log('PAGE LOG:', msg.text()));
        page.on('pageerror', exception => console.log(`PAGE ERROR: ${exception}`));

        await page.goto('/');
    });

    // Helper to handle first login if needed
    async function handleFirstLogin(page: any) {
        console.log('Starting handleFirstLogin helper...');
        const dashboard = page.getByText(/Free Workout|Свободная тренировка/i).first();
        const changePass = page.getByRole('heading', { name: /Change Password|Смена пароля/i });
        const initAcc = page.getByRole('heading', { name: /Setup Your Account|Настройка аккаунта/i });

        for (let i = 0; i < 30; i++) {
            if (await dashboard.isVisible()) {
                console.log('Dashboard visible.');
                return;
            }

            if (await changePass.isVisible()) {
                console.log('Change Password screen detected. Handling...');
                await page.getByLabel(/New Password|Новый пароль/i).fill('StrongNewPass123!');
                await page.getByRole('button', { name: /Save|Change|Сохранить/i }).click();
                // Wait a bit for transition
                await page.waitForTimeout(1000);
                continue;
            }

            if (await initAcc.isVisible()) {
                console.log('Initialization screen detected. Handling...');
                await page.getByRole('button', { name: /Get Started|Начать работу/i }).click();
                // Wait a bit for transition
                await page.waitForTimeout(1000);
                continue;
            }

            await page.waitForTimeout(500);
        }

        // Final check with assertion to fail the test if not reached
        await expect(dashboard).toBeVisible({ timeout: 5000 });
    }

    // 1.1. A. Login - Successful Authentication
    test('1.1 Login - Successful Authentication', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        await handleFirstLogin(page);

        // Expect redirection to dashboard
        await expect(page).not.toHaveURL(/\/login/);
        await expect(page.getByText(/Free Workout|Свободная тренировка/i).first()).toBeVisible();
    });

    // 1.2. A. Login - Invalid Credentials
    test('1.2 Login - Invalid Credentials', async ({ page }) => {
        await page.getByLabel(/Email/i).fill('invalid@user.com');
        await page.getByLabel(/Password|Пароль/i).fill('wrongpassword');
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        await expect(page.getByText('Invalid credentials')).toBeVisible();
        await expect(page.getByRole('button', { name: 'Login' })).toBeVisible();
    });

    test('1.3 & 1.4 Login - First-Time Password Change', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        await expect(page.getByRole('heading', { name: /Change Password|Смена пароля/i }).first()).toBeVisible({ timeout: 10000 });

        // 1.4 Test short password
        await page.getByLabel(/New Password|Новый пароль/i).fill('123');
        await page.getByRole('button', { name: /Save|Change|Сохранить/i }).click();
        await expect(page.getByText(/Password too short|Пароль слишком короткий/i)).toBeVisible();

        // 1.3 Test successful change
        await page.getByLabel(/New Password|Новый пароль/i).fill('StrongNewPass123!');
        await page.getByRole('button', { name: /Save|Change|Сохранить/i }).click();

        // Now we should be on Setup Account page
        await expect(page.getByRole('heading', { name: /Setup Your Account|Настройка аккаунта/i })).toBeVisible();
        await page.getByRole('button', { name: /Get Started|Начать работу/i }).click();

        // Now we should be logged in
        await expect(page.getByText(/Free Workout|Свободная тренировка/i).first()).toBeVisible();
    });


    test('1.5 Login - Language Selection (English)', async ({ page }) => {
        await page.getByRole('combobox').selectOption('en');
        await expect(page.getByLabel(/Email/i)).toBeVisible();
        await expect(page.getByRole('button', { name: /Login|Войти/i })).toBeVisible();
    });

    // 1.6. A. Login - Language Selection (Russian)
    test('1.6 Login - Language Selection (Russian)', async ({ page }) => {
        await page.getByRole('combobox').selectOption('ru');
        await expect(page.getByRole('button', { name: 'Войти' })).toBeVisible();
    });

    // 1.7. B. Navigation - Desktop Navigation Rail
    test('1.7 Navigation - Desktop Navigation Rail', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        await handleFirstLogin(page);

        // Set viewport to desktop
        await page.setViewportSize({ width: 1280, height: 720 });

        await expect(page.getByRole('button', { name: /Tracker|Трекер/i }).first()).toBeVisible();
        await expect(page.getByRole('button', { name: /Plans|Планы/i }).first()).toBeVisible();
    });

    // 1.8. B. Navigation - Mobile Bottom Navigation Bar
    test('1.8 Navigation - Mobile Bottom Navigation Bar', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        await handleFirstLogin(page);

        // Set viewport to mobile
        await page.setViewportSize({ width: 375, height: 667 });

        await page.waitForTimeout(500); // Allow layout transition

        // Verify visibility of mobile nav items
        await expect(page.getByRole('button', { name: /Tracker|Трекер/i }).last()).toBeVisible();
    });

    // 1.9. C. Initialization - Russian Language Seeding
    test('1.9 Initialization - Russian Language Seeding', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        // Handle password change
        await expect(page.getByRole('heading', { name: /Change Password|Смена пароля/i })).toBeVisible();
        await page.getByLabel(/New Password|Новый пароль/i).fill('StrongNewPass123!');
        await page.getByRole('button', { name: /Save|Change|Сохранить/i }).click();

        // Handle initialization - Select Russian
        await expect(page.getByRole('heading', { name: /Setup Your Account|Настройка аккаунта/i })).toBeVisible();
        await page.getByText('Русский').click();
        await page.getByRole('button', { name: /Начать работу|Get Started/i }).click();

        // Expect dashboard
        await expect(page.getByText('Свободная тренировка')).toBeVisible();

        // Verify some exercise is in Russian
        await page.getByText(/Свободная тренировка|Free Workout/i).first().click();
        await page.getByLabel(/Выберите упражнение|Select Exercise/i).click();

        // "Air Squats" should be "Приседания" in suggestions
        await expect(page.getByRole('button', { name: 'Приседания', exact: true })).toBeVisible();
        await page.getByRole('button', { name: 'Приседания', exact: true }).click();

        // Verify it's selected in the input
        const exerciseInput = page.getByLabel(/Выберите упражнение|Select Exercise/i);
        await expect(exerciseInput).toHaveValue('Приседания');

        // Verify "Log Set" button is now in Russian
        await expect(page.getByRole('button', { name: /Записать подход|Log Set/i })).toBeVisible();
    });

    // 1.10. C. Initialization - Optional Profile Data
    test('1.10 Initialization - Optional Profile Data', async ({ page, createUniqueUser }) => {
        const user = await createUniqueUser();

        await page.getByLabel(/Email/i).fill(user.email);
        await page.getByLabel(/Password|Пароль/i).fill(user.password);
        await page.getByRole('button', { name: /Login|Войти/i }).click();

        // Handle password change
        await expect(page.getByRole('heading', { name: /Change Password|Смена пароля/i })).toBeVisible();
        await page.getByLabel(/New Password|Новый пароль/i).fill('StrongNewPass123!');
        await page.getByRole('button', { name: /Save|Change|Сохранить/i }).click();

        // Handle initialization
        await expect(page.getByRole('heading', { name: /Setup Your Account|Настройка аккаунта/i })).toBeVisible();

        // Fill data
        await page.getByLabel(/Birth Date|Дата рожд./i).fill('1990-01-01');
        await page.keyboard.press('Enter');
        await page.getByLabel(/Height|Рост/i).fill('180');
        await page.getByLabel(/Bodyweight|Вес тела/i).fill('80');
        await page.getByLabel(/Gender|Пол/i).selectOption('MALE');

        await page.getByRole('button', { name: /Get Started|Начать работу/i }).click();

        // Expect dashboard
        await expect(page.getByText(/Free Workout|Свободная тренировка/i).first()).toBeVisible();

        // Navigate to profile to verify
        await page.getByRole('button', { name: /Profile|Профиль/i }).first().click();

        // Verify values in Profile section
        await expect(page.getByLabel(/Height|Рост/i)).toHaveValue('180');
        await expect(page.getByLabel(/Birth Date|Дата рожд./i)).toHaveValue('1990-01-01');
        await expect(page.getByLabel(/Gender|Пол/i)).toHaveValue('MALE');
    });

});
