#!/usr/bin/env node

import { chromium } from 'playwright';

const DESKTOP_VIEWPORT = { width: 1278, height: 800 }; // User's actual viewport

(async () => {
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext({
        viewport: DESKTOP_VIEWPORT
    });
    const page = await context.newPage();

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

    const desktopLayout = await page.evaluate(() => {
        const sidebar = document.querySelector('.cv-sidebar-left');
        const sidebarRight = document.querySelector('.cv-sidebar-right');
        const accordion = document.querySelector('.sidebar-accordion');
        const accordionHeader = document.querySelector('.sidebar-accordion-header');
        const downloadBtn = document.querySelector('.download-btn');
        const backdrop = document.querySelector('.fixed-buttons-backdrop');

        const sidebarRect = sidebar?.getBoundingClientRect();
        const accordionRect = accordion?.getBoundingClientRect();

        return {
            viewport: `${window.innerWidth}×${window.innerHeight}`,
            mediaQueries: {
                'landscape-mobile': window.matchMedia('(max-width: 915px) and (orientation: landscape)').matches,
                'mobile-768': window.matchMedia('(max-width: 768px)').matches,
                'mobile-540': window.matchMedia('(max-width: 540px)').matches,
            },
            sidebar: {
                exists: !!sidebar,
                visible: sidebar ? window.getComputedStyle(sidebar).display !== 'none' : false,
                width: sidebarRect ? Math.round(sidebarRect.width) : 0,
                height: sidebarRect ? Math.round(sidebarRect.height) : 0,
                left: sidebarRect ? Math.round(sidebarRect.left) : 0,
            },
            sidebarRight: {
                exists: !!sidebarRight,
                visible: sidebarRight ? window.getComputedStyle(sidebarRight).display !== 'none' : false,
            },
            accordion: {
                exists: !!accordion,
                headerVisible: accordionHeader ? window.getComputedStyle(accordionHeader).display !== 'none' : false,
                open: accordion?.hasAttribute('open'),
                height: accordionRect ? Math.round(accordionRect.height) : 0,
            },
            buttons: {
                downloadBtnExists: !!downloadBtn,
                downloadBtnVisible: downloadBtn ? window.getComputedStyle(downloadBtn).display !== 'none' : false,
                downloadBtnBottom: downloadBtn ? window.getComputedStyle(downloadBtn).bottom : 'N/A',
                backdropExists: !!backdrop,
                backdropVisible: backdrop ? window.getComputedStyle(backdrop).display !== 'none' : false,
            }
        };
    });

    console.log('🖥️  Desktop View Test (1278px)\n');
    console.log(`Viewport: ${desktopLayout.viewport}\n`);

    console.log('Media Queries:');
    console.log(`  • Landscape mobile (≤915px): ${desktopLayout.mediaQueries['landscape-mobile'] ? '✅ MATCHES' : '❌ NO MATCH'}`);
    console.log(`  • Mobile (≤768px): ${desktopLayout.mediaQueries['mobile-768'] ? '✅ MATCHES' : '❌ NO MATCH'}`);
    console.log(`  • Mobile (≤540px): ${desktopLayout.mediaQueries['mobile-540'] ? '✅ MATCHES' : '❌ NO MATCH'}\n`);

    console.log('Left Sidebar:');
    console.log(`  • Exists: ${desktopLayout.sidebar.exists ? '✅' : '❌'}`);
    console.log(`  • Visible: ${desktopLayout.sidebar.visible ? '✅' : '❌ BROKEN'}`);
    console.log(`  • Size: ${desktopLayout.sidebar.width}×${desktopLayout.sidebar.height}px`);
    console.log(`  • Position: left=${desktopLayout.sidebar.left}px\n`);

    console.log('Right Sidebar:');
    console.log(`  • Exists: ${desktopLayout.sidebarRight.exists ? '✅' : '❌'}`);
    console.log(`  • Visible: ${desktopLayout.sidebarRight.visible ? '✅' : '❌ BROKEN'}\n`);

    console.log('Accordion (should NOT be present in desktop view):');
    console.log(`  • Exists: ${desktopLayout.accordion.exists ? '❌ SHOULD NOT EXIST' : '✅'}`);
    console.log(`  • Header visible: ${desktopLayout.accordion.headerVisible ? '❌ SHOULD BE HIDDEN' : '✅'}`);
    console.log(`  • Open: ${desktopLayout.accordion.open ? 'YES' : 'NO'}`);
    console.log(`  • Height: ${desktopLayout.accordion.height}px\n`);

    console.log('Bottom Buttons:');
    console.log(`  • Download button exists: ${desktopLayout.buttons.downloadBtnExists ? '✅' : '❌'}`);
    console.log(`  • Download button visible: ${desktopLayout.buttons.downloadBtnVisible ? '✅' : '❌ BROKEN'}`);
    console.log(`  • Download button bottom: ${desktopLayout.buttons.downloadBtnBottom}`);
    console.log(`  • Backdrop exists: ${desktopLayout.buttons.backdropExists ? '✅' : '❌'}`);
    console.log(`  • Backdrop visible: ${desktopLayout.buttons.backdropVisible ? '✅' : '❌'}\n`);

    await page.screenshot({
        path: 'tests/screenshots/desktop-1278px.png',
        fullPage: true
    });
    console.log('Screenshot saved: tests/screenshots/desktop-1278px.png\n');

    const criticalIssues = [];
    if (!desktopLayout.sidebar.visible) criticalIssues.push('Left sidebar not visible');
    if (!desktopLayout.sidebarRight.visible) criticalIssues.push('Right sidebar not visible');
    if (desktopLayout.accordion.headerVisible) criticalIssues.push('Accordion visible in desktop view');
    if (!desktopLayout.buttons.downloadBtnVisible) criticalIssues.push('Download button not visible');

    if (criticalIssues.length > 0) {
        console.log('❌ CRITICAL ISSUES FOUND:');
        criticalIssues.forEach(issue => console.log(`   - ${issue}`));
    } else {
        console.log('✅ Desktop view looks good');
    }

    await browser.close();
    process.exit(criticalIssues.length > 0 ? 1 : 0);
})();
