import { test, expect } from '@playwright/test';

test('base project comprehensive tests and scrolling benchmarks', async ({ page }) => {
    test.setTimeout(60000);
    page.on('console', msg => console.log('BROWSER LOG:', msg.text()));
    page.on('pageerror', err => console.log('BROWSER EXCEPTION:', err.message, err.stack));
    await page.goto('http://127.0.0.1:8082/test/index.html');
    
    // Wait for testStatus to be set (includes basic unit tests and scrolling refresh test)
    await page.waitForFunction(() => window.testStatus !== undefined, { timeout: 60000 });
    
    const status = await page.evaluate(() => window.testStatus);
    expect(status).toBe('passed');

    // Simulate real scrolling and check dynamic rendering for FastList
    console.log('Simulating real scroll on FastList...');
    const scrollInfo = await page.evaluate(async () => {
        window.switchTab?.('ll');
        await new Promise(r => setTimeout(r, 200)); // wait for render
        const el = document.getElementById('ll');
        const results = [];
        
        const getRenderedCount = () => el.querySelectorAll('.border-primary').length;
        
        results.push({ 
            id: 'initial',
            scrollTop: el.scrollTop, 
            scrollHeight: el.scrollHeight,
            clientHeight: el.clientHeight,
            renderedCount: getRenderedCount(),
            renderedListLen: el.state.renderedList?.length
        });

    // Scroll to middle
    el.scrollTop = 50000;
    el.refresh?.();
    await new Promise(r => setTimeout(r, 500));
    const midCount = getRenderedCount();
    const midHtml = el.innerHTML.length;
    results.push({ 
        id: 'deep-middle',
        scrollTop: el.scrollTop, 
        renderedCount: midCount,
        htmlLen: midHtml,
        prevHeight: el.state.prevHeight,
        postHeight: el.state.postHeight,
        renderedListLen: el.state._renderedList?.length
    });
    
    // Scroll to end
    el.scrollTop = el.scrollHeight;
    el.refresh?.();
    await new Promise(r => setTimeout(r, 500));
    results.push({ 
        id: 'end',
        scrollTop: el.scrollTop, 
        renderedCount: getRenderedCount(),
        scrollHeight: el.scrollHeight,
        prevHeight: el.state.prevHeight,
        postHeight: el.state.postHeight
    });
        
        return results;
    });
    
    console.log('Scroll Details:', JSON.stringify(scrollInfo, null, 2));
    expect(scrollInfo[0].renderedCount).toBeGreaterThan(0);
    expect(scrollInfo[1].scrollTop).toBeGreaterThan(0);

    const bench = await page.evaluate(() => window.benchResults);
    if (bench) {
        Object.entries(bench).forEach(([name, time]) => {
            console.log(`BENCHMARK [${name}]: ${time.toFixed(2)}ms`);
        });
    }
});
