#!/usr/bin/env node

import { chromium } from 'playwright';

/**
 * TEST: Navigation Menu Text Colors in Dark Theme
 *
 * Verifies that menu text is always dark/black regardless of theme,
 * since the menu background is always white.
 */

const THEMES = {
    light: { name: 'Light Theme', selector: 'light' },
    dark: { name: 'Dark Theme', selector: 'dark' }
};

async function testTheme(browser, theme) {
    const context = await browser.newContext({
        viewport: { width: 1278, height: 800 }
    });
    const page = await context.newPage();

    await page.goto(`http://localhost:1999/?lang=en`);
    await page.waitForLoadState('networkidle');

    // Set theme
    await page.evaluate((themeValue) => {
        document.documentElement.setAttribute('data-color-theme', themeValue);
    }, theme.selector);

    // Wait for theme to apply
    await page.waitForTimeout(300);

    // Hover over hamburger to open menu
    await page.hover('.hamburger-btn');
    await page.waitForTimeout(500);

    const results = await page.evaluate(() => {
        const menuItem = document.querySelector('.menu-item');
        const menuIcon = document.querySelector('.menu-item iconify-icon');
        const menuHeader = document.querySelector('.menu-item-header');
        const menuHeaderIcon = document.querySelector('.menu-item-header iconify-icon');
        const controlLabel = document.querySelector('.menu-control-label');
        const controlIcon = document.querySelector('.menu-control-label iconify-icon');

        function getColor(el) {
            if (!el) return 'N/A';
            return window.getComputedStyle(el).color;
        }

        return {
            menuBackground: window.getComputedStyle(document.querySelector('.navigation-menu')).backgroundColor,
            menuItem: {
                exists: !!menuItem,
                color: getColor(menuItem)
            },
            menuIcon: {
                exists: !!menuIcon,
                color: getColor(menuIcon)
            },
            menuHeader: {
                exists: !!menuHeader,
                color: getColor(menuHeader)
            },
            menuHeaderIcon: {
                exists: !!menuHeaderIcon,
                color: getColor(menuHeaderIcon)
            },
            controlLabel: {
                exists: !!controlLabel,
                color: getColor(controlLabel)
            },
            controlIcon: {
                exists: !!controlIcon,
                color: getColor(controlIcon)
            }
        };
    });

    await page.screenshot({
        path: `tests/screenshots/menu-${theme.selector}-theme.png`,
        fullPage: false
    });

    await context.close();
    return results;
}

(async () => {
    const browser = await chromium.launch({ headless: true });

    console.log('🎨 Navigation Menu Color Test - Dark Theme Fix\n');
    console.log('Testing: Menu text should be dark in both themes (white menu bg)\n');

    const allResults = {};
    const failures = [];

    for (const [key, theme] of Object.entries(THEMES)) {
        console.log(`🎨 Testing: ${theme.name}`);
        console.log('='.repeat(60));

        const results = await testTheme(browser, theme);
        allResults[key] = results;

        console.log(`\nMenu Background: ${results.menuBackground}`);
        console.log('\nText Colors:');
        console.log(`  Menu Item: ${results.menuItem.color}`);
        console.log(`  Menu Icon: ${results.menuIcon.color}`);
        console.log(`  Menu Header: ${results.menuHeader.color}`);
        console.log(`  Header Icon: ${results.menuHeaderIcon.color}`);
        console.log(`  Control Label: ${results.controlLabel.color}`);
        console.log(`  Control Icon: ${results.controlIcon.color}`);

        // Validation
        const issues = [];

        // Menu background should be white
        if (!results.menuBackground.includes('255, 255, 255')) {
            issues.push('Menu background should be white (rgb(255, 255, 255))');
        }

        // Text colors should be dark (rgb values < 100)
        function isDarkColor(colorStr) {
            if (!colorStr || colorStr === 'N/A') return false;
            const match = colorStr.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
            if (!match) return false;
            const r = parseInt(match[1]);
            const g = parseInt(match[2]);
            const b = parseInt(match[3]);
            // Dark colors have RGB values < 100
            return r < 100 && g < 100 && b < 100;
        }

        if (!isDarkColor(results.menuItem.color)) {
            issues.push(`Menu item text should be dark, got: ${results.menuItem.color}`);
        }
        if (!isDarkColor(results.menuIcon.color)) {
            issues.push(`Menu icon should be dark, got: ${results.menuIcon.color}`);
        }
        if (!isDarkColor(results.menuHeader.color)) {
            issues.push(`Menu header text should be dark, got: ${results.menuHeader.color}`);
        }
        if (!isDarkColor(results.menuHeaderIcon.color)) {
            issues.push(`Header icon should be dark, got: ${results.menuHeaderIcon.color}`);
        }
        if (!isDarkColor(results.controlLabel.color)) {
            issues.push(`Control label should be dark, got: ${results.controlLabel.color}`);
        }
        if (!isDarkColor(results.controlIcon.color)) {
            issues.push(`Control icon should be dark, got: ${results.controlIcon.color}`);
        }

        if (issues.length > 0) {
            console.log('\n❌ ISSUES FOUND:');
            issues.forEach(issue => {
                console.log(`   - ${issue}`);
                failures.push(`${theme.name}: ${issue}`);
            });
        } else {
            console.log('\n✅ All colors correct - dark text on white background');
        }

        console.log('\n');
    }

    // Final summary
    console.log('='.repeat(60));
    console.log('FINAL SUMMARY\n');

    if (failures.length === 0) {
        console.log('✅ ALL TESTS PASSED\n');
        console.log('Menu colors are correct in all themes:');
        console.log('  ✅ Menu background: White (rgb(255, 255, 255))');
        console.log('  ✅ Menu text: Dark/Black in both light and dark themes');
        console.log('  ✅ Menu icons: Dark gray in both themes');
        console.log('\nDark theme fix verified!\n');
    } else {
        console.log(`❌ ${failures.length} ISSUE(S) FOUND:\n`);
        failures.forEach((failure, i) => {
            console.log(`${i + 1}. ${failure}`);
        });
        console.log('');
    }

    await browser.close();
    process.exit(failures.length === 0 ? 0 : 1);
})();
