#!/usr/bin/env node

/**
 * Test script to verify section clicking functionality works correctly
 */

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

// Load the generated HTML file
const htmlContent = fs.readFileSync('/tmp/test_section_click_fixed.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 section click functionality...');

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

        console.log('✅ Components initialized:', Object.keys(components));

        const { sectionManager, domRenderer, debugPanel, documentControls } = components;

        // Check if sections were created
        const sectionsCount = sectionManager.sections.size;
        console.log(`✅ Found ${sectionsCount} sections in section manager`);

        // Check if sections are rendered in DOM
        const renderedSections = document.querySelectorAll('.ui-edit-section');
        console.log(`✅ Found ${renderedSections.length} rendered section elements`);

        if (renderedSections.length > 0) {
            console.log('🔍 Testing section click on first section...');

            const firstSectionElement = renderedSections[0];
            const sectionId = firstSectionElement.getAttribute('data-section-id');
            console.log(`   Section ID: ${sectionId}`);

            // Get the section object
            const section = sectionManager.sections.get(sectionId);
            if (!section) {
                console.error('❌ Section object not found in manager');
                return;
            }

            console.log(`   Section content: "${section.currentMarkdown.substring(0, 50)}..."`);

            // Simulate click event
            const clickEvent = new window.MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window
            });

            console.log('🖱️  Simulating click on section...');
            firstSectionElement.dispatchEvent(clickEvent);

            // Wait a bit for the click to be processed
            setTimeout(() => {
                // Check if section is now in editing state
                if (section.isEditing()) {
                    console.log('✅ Section click successful - section is now in editing state');

                    // Check if floating menu appeared
                    const floatingMenu = document.querySelector('.ui-edit-floating-menu');
                    if (floatingMenu) {
                        console.log('✅ Floating menu appeared');

                        // Check for accept and cancel buttons
                        const acceptButton = floatingMenu.querySelector('button[style*="background: #28a745"]');
                        const cancelButton = floatingMenu.querySelector('button[style*="background: #dc3545"]');

                        if (acceptButton && cancelButton) {
                            console.log('✅ Accept and Cancel buttons found in floating menu');
                            console.log('🎉 Section click functionality is working correctly!');
                        } else {
                            console.log('❌ Accept/Cancel buttons not found in floating menu');
                        }
                    } else {
                        console.log('❌ Floating menu did not appear');
                    }
                } else {
                    console.log('❌ Section click failed - section is not in editing state');
                    console.log(`   Section state: ${section.editState}`);
                }
            }, 300);

        } else {
            console.log('❌ No sections rendered - cannot test clicking');
        }

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