#!/usr/bin/env node

/**
 * Test dialog positioning and reliability issues
 */

const fs = require('fs');
const { JSDOM } = require('jsdom');

// Load the generated HTML file
const htmlContent = fs.readFileSync('/tmp/test_advanced_image_editor.html', 'utf8');

// Create JSDOM environment
const dom = new JSDOM(htmlContent, {
    runScripts: "dangerously",
    resources: "usable",
    pretendToBeVisual: true
});

const { window } = dom;
const { document } = window;

// Add console methods to window for debugging
window.console = console;

// Wait for DOM to load and components to initialize
setTimeout(() => {
    try {
        console.log('🎯 Testing Dialog Positioning and Reliability...\n');

        const components = window.markitectComponents;
        if (!components) {
            console.error('❌ Components not initialized');
            return;
        }

        const sections = document.querySelectorAll('.ui-edit-section');
        console.log(`Found ${sections.length} sections to test`);

        let testCount = 0;
        let successCount = 0;
        let positioningIssues = 0;

        // Test clicking each section multiple times to check for intermittent issues
        sections.forEach((section, index) => {
            const sectionId = section.getAttribute('data-section-id');

            console.log(`\nTEST ${index + 1}: Section ${sectionId}`);

            // Test multiple clicks on the same section
            for (let attempt = 1; attempt <= 3; attempt++) {
                testCount++;
                console.log(`  Attempt ${attempt}:`);

                // Click the section
                section.click();

                setTimeout(() => {
                    const floatingMenu = document.querySelector('.ui-edit-floating-menu');

                    if (floatingMenu) {
                        successCount++;
                        console.log(`    ✅ Dialog appeared`);

                        // Check positioning
                        const menuRect = {
                            left: parseInt(floatingMenu.style.left),
                            top: parseInt(floatingMenu.style.top),
                            width: floatingMenu.offsetWidth,
                            height: floatingMenu.offsetHeight
                        };

                        const sectionRect = section.getBoundingClientRect();

                        console.log(`    Section position: (${Math.round(sectionRect.left)}, ${Math.round(sectionRect.top)})`);
                        console.log(`    Dialog position: (${menuRect.left}, ${menuRect.top})`);

                        // Check if dialog is positioned reasonably relative to section
                        const horizontalAlignment = Math.abs(menuRect.left - sectionRect.left) < 50;
                        const verticalProximity = menuRect.top > sectionRect.top && (menuRect.top - sectionRect.bottom) < 100;

                        if (!horizontalAlignment || !verticalProximity) {
                            positioningIssues++;
                            console.log(`    ⚠️  Positioning issue detected`);
                            console.log(`      Horizontal alignment: ${horizontalAlignment ? 'OK' : 'POOR'}`);
                            console.log(`      Vertical proximity: ${verticalProximity ? 'OK' : 'POOR'}`);
                        } else {
                            console.log(`    ✅ Positioning looks good`);
                        }

                        // Close the dialog
                        const closeButton = floatingMenu.querySelector('button');
                        if (closeButton && closeButton.textContent.includes('×')) {
                            closeButton.click();
                        } else {
                            // Try cancel button
                            const cancelButton = Array.from(floatingMenu.querySelectorAll('button')).find(btn => btn.textContent.includes('Cancel'));
                            if (cancelButton) {
                                cancelButton.click();
                            }
                        }

                    } else {
                        console.log(`    ❌ Dialog failed to appear`);
                    }
                }, 100 + (attempt * 50)); // Stagger the timing
            }
        });

        // Summary after all tests
        setTimeout(() => {
            console.log('\n📊 POSITIONING AND RELIABILITY SUMMARY:');
            console.log(`  Total tests: ${testCount}`);
            console.log(`  Successful dialogs: ${successCount}`);
            console.log(`  Success rate: ${Math.round((successCount / testCount) * 100)}%`);
            console.log(`  Positioning issues: ${positioningIssues}`);
            console.log(`  Positioning accuracy: ${Math.round(((successCount - positioningIssues) / successCount) * 100)}%`);

            if (successCount < testCount) {
                console.log('\n🔍 RELIABILITY ISSUES DETECTED:');
                console.log('  - Some dialogs failed to appear intermittently');
                console.log('  - Possible race conditions in section click handling');
                console.log('  - May need debouncing or state checking');
            }

            if (positioningIssues > 0) {
                console.log('\n🎯 POSITIONING ISSUES DETECTED:');
                console.log('  - Dialogs not aligning properly with content');
                console.log('  - May appear off-screen or in wrong location');
                console.log('  - Need viewport boundary checking and smart positioning');
            }

            console.log('\n🎯 RECOMMENDATIONS:');
            console.log('1. Add debouncing to prevent multiple rapid clicks');
            console.log('2. Implement smart positioning with viewport boundary detection');
            console.log('3. Add fallback positioning when primary position is off-screen');
            console.log('4. Improve reliability with better state management');

        }, 2000);

    } catch (error) {
        console.error('❌ Test failed:', error.message);
        console.error(error.stack);
    }
}, 1000);