#!/usr/bin/env node

/**
 * Test StartEdit UI Issue
 *
 * Debug test to investigate why startEditing succeeds but UI doesn't appear
 * for sections after images
 */

const { TestRunner } = require('./test_runner.js');
const runner = new TestRunner();

runner.describe('StartEdit UI Issue Tests', () => {

    runner.it('should trace the complete flow from click to UI appearance', async () => {
        // Load editor
        delete require.cache[require.resolve('/home/worsch/markitect_project/markitect/static/editor.js')];
        require('/home/worsch/markitect_project/markitect/static/editor.js');

        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            container.innerHTML = '<div id="markdown-content"></div>';
            document.body.appendChild(container);

            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create markdown with image followed by text sections
            const testMarkdown = `# Section Before Image
This section should work.

![Test Image](https://via.placeholder.com/400x200.jpg)

# Section After Image
This section has issues.

# Another Section After Image
This section also has issues.`;

            console.log('🔍 Creating sections from markdown...');
            const sections = manager.createSectionsFromMarkdown(testMarkdown);
            console.log(`Created ${sections.length} sections:`, sections.map(s => ({ id: s.id, type: s.type, isImage: s.isImage ? s.isImage() : false })));

            console.log('🔍 Rendering all sections...');
            renderer.renderAllSections(sections);

            // Find sections
            const beforeImageSection = sections.find(s => s.currentMarkdown.includes('Before Image'));
            const imageSection = sections.find(s => s.isImage && s.isImage());
            const afterImageSection = sections.find(s => s.currentMarkdown.includes('Section After Image'));
            const anotherAfterSection = sections.find(s => s.currentMarkdown.includes('Another Section'));

            console.log('🔍 Section analysis:');
            console.log('Before image section:', beforeImageSection ? beforeImageSection.id : 'NOT FOUND');
            console.log('Image section:', imageSection ? imageSection.id : 'NOT FOUND');
            console.log('After image section:', afterImageSection ? afterImageSection.id : 'NOT FOUND');
            console.log('Another after section:', anotherAfterSection ? anotherAfterSection.id : 'NOT FOUND');

            // Test that DOM elements exist
            const beforeElement = renderer.findSectionElement(beforeImageSection.id);
            const imageElement = renderer.findSectionElement(imageSection.id);
            const afterElement = renderer.findSectionElement(afterImageSection.id);
            const anotherElement = renderer.findSectionElement(anotherAfterSection.id);

            console.log('🔍 DOM elements found:');
            console.log('Before image element:', !!beforeElement);
            console.log('Image element:', !!imageElement);
            console.log('After image element:', !!afterElement);
            console.log('Another after element:', !!anotherElement);

            runner.expect(beforeElement).toBeTruthy();
            runner.expect(imageElement).toBeTruthy();
            runner.expect(afterElement).toBeTruthy();
            runner.expect(anotherElement).toBeTruthy();

            // Test the problematic section
            console.log('\n🔍 Testing problematic section:', afterImageSection.id);
            console.log('Section state before startEditing:', afterImageSection.state);
            console.log('Is editing before:', afterImageSection.isEditing());

            // Hook into the event system to see if events are being fired
            let editStartedCalled = false;
            let showEditorCalled = false;

            manager.on('edit-started', (data) => {
                console.log('📡 EVENT: edit-started fired for:', data.sectionId);
                editStartedCalled = true;
            });

            // Override showEditor to track if it's called
            const originalShowEditor = renderer.showEditor;
            renderer.showEditor = function(sectionId, content) {
                console.log('🎭 OVERRIDE: showEditor called for:', sectionId);
                showEditorCalled = true;
                return originalShowEditor.call(this, sectionId, content);
            };

            // Call startEditing directly
            console.log('\n🚀 Calling manager.startEditing directly...');
            try {
                const result = manager.startEditing(afterImageSection.id);
                console.log('✅ startEditing returned:', result ? 'SUCCESS' : 'FAILURE');
                console.log('Section state after:', afterImageSection.state);
                console.log('Is editing after:', afterImageSection.isEditing());
            } catch (error) {
                console.log('❌ startEditing threw error:', error.message);
            }

            // Check if events were fired
            console.log('\n📊 Event tracking results:');
            console.log('edit-started event fired:', editStartedCalled);
            console.log('showEditor called:', showEditorCalled);

            // Check if floating menu appeared
            setTimeout(() => {
                const floatingMenu = document.querySelector('.ui-edit-floating-menu');
                console.log('UI check - floating menu exists:', !!floatingMenu);

                if (!floatingMenu) {
                    console.log('❌ UI ISSUE: startEditing succeeded but no floating menu appeared');
                    console.log('Current editing sections:', Array.from(renderer.editingSections));
                    console.log('Current floating menu:', renderer.currentFloatingMenu);
                } else {
                    console.log('✅ UI working: floating menu appeared');
                }

                // Cleanup
                document.body.removeChild(container);
                runner.expect(true).toBeTruthy(); // Just pass the test, we're debugging
            }, 100);
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('🔍 Running StartEdit UI Issue Tests');
    runner.run().then(() => {
        console.log('\n🏁 Test completed - check console output above for debugging info');
    });
}

module.exports = runner;