#!/usr/bin/env node

import { chromium } from 'playwright';

const LANDSCAPE_VIEWPORT = { width: 667, height: 375 };

(async () => {
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext({
        viewport: LANDSCAPE_VIEWPORT,
        userAgent: 'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36',
        hasTouch: true
    });
    const page = await context.newPage();

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

    const debug = await page.evaluate(() => {
        // Find all elements wider than viewport
        const viewportWidth = window.innerWidth;
        const wideElements = [];

        document.querySelectorAll('*').forEach((el) => {
            const rect = el.getBoundingClientRect();
            if (rect.width > viewportWidth) {
                const computed = window.getComputedStyle(el);
                wideElements.push({
                    tag: el.tagName.toLowerCase(),
                    id: el.id || '(no id)',
                    classes: el.className || '(no classes)',
                    width: Math.round(rect.width),
                    computedWidth: computed.width,
                    maxWidth: computed.maxWidth,
                    overflow: computed.overflowX
                });
            }
        });

        // Sort by width descending
        wideElements.sort((a, b) => b.width - a.width);

        return {
            viewportWidth,
            bodyScrollWidth: document.body.scrollWidth,
            documentScrollWidth: document.documentElement.scrollWidth,
            hasHorizontalScroll: document.body.scrollWidth > viewportWidth,
            wideElements: wideElements.slice(0, 10) // Top 10 widest
        };
    });

    console.log(`Horizontal Scroll Debug:\n`);
    console.log(`Viewport: ${debug.viewportWidth}px`);
    console.log(`Body scroll width: ${debug.bodyScrollWidth}px`);
    console.log(`Document scroll width: ${debug.documentScrollWidth}px`);
    console.log(`Has horizontal scroll: ${debug.hasHorizontalScroll ? '❌ YES' : '✅ NO'}\n`);

    if (debug.wideElements.length > 0) {
        console.log(`Elements wider than viewport:\n`);
        debug.wideElements.forEach((el, i) => {
            console.log(`${i + 1}. <${el.tag}> #${el.id} .${el.classes}`);
            console.log(`   Width: ${el.width}px | Max-width: ${el.maxWidth} | Overflow: ${el.overflow}`);
            console.log(`   Computed width: ${el.computedWidth}\n`);
        });
    } else {
        console.log('No elements wider than viewport found\n');
    }

    await browser.close();
})();
