#!/usr/bin/env node

/**
 * Test Section Click Debug
 *
 * Debug test to identify why sections after the first image
 * don't respond to clicks properly
 */

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

runner.describe('Section Click Debug Tests', () => {

    runner.it('should find all sections with proper classes and attributes', 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 sections before and after an image
            const testMarkdown = `# Section 1
This is the first section.

# Section 2
This is before the image.

![Test Image](test.jpg)

# Section 3
This section comes after the image.

# Section 4
This is another section after the image.`;

            const sections = manager.createSectionsFromMarkdown(testMarkdown);

            console.log(`Created ${sections.length} sections:`, sections.map(s => s.id));

            // Render all sections
            renderer.renderAllSections(sections);

            // Check that all sections have proper setup
            const allSectionElements = container.querySelectorAll('.ui-edit-section');
            console.log(`Found ${allSectionElements.length} section elements in DOM`);

            runner.expect(allSectionElements.length).toBe(sections.length);

            // Check each section element
            allSectionElements.forEach((element, index) => {
                const sectionId = element.getAttribute('data-section-id');
                console.log(`Section ${index}: ID=${sectionId}, class=${element.className}`);

                runner.expect(sectionId).toBeTruthy();
                runner.expect(element.classList.contains('ui-edit-section')).toBeTruthy();
                runner.expect(element.style.cursor).toBe('pointer');
            });

            // Test that click handler can find sections
            allSectionElements.forEach((element, index) => {
                // Simulate what happens in handleSectionClick
                const foundElement = element.closest('.ui-edit-section');
                runner.expect(foundElement).toBe(element);

                const sectionId = foundElement.getAttribute('data-section-id');
                runner.expect(sectionId).toBeTruthy();

                const section = manager.sections.get(sectionId);
                runner.expect(section).toBeTruthy();

                console.log(`Section ${index} (${sectionId}): Click simulation successful`);
            });

            // Cleanup
            document.body.removeChild(container);
        }
    });

    runner.it('should properly handle click events on sections after images', async () => {
        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);

            const testMarkdown = `# Before Image
Text before image.

![Test Image](test.jpg)

# After Image
Text after image.`;

            const sections = manager.createSectionsFromMarkdown(testMarkdown);
            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('After Image'));

            runner.expect(beforeImageSection).toBeTruthy();
            runner.expect(imageSection).toBeTruthy();
            runner.expect(afterImageSection).toBeTruthy();

            console.log('Before image section ID:', beforeImageSection.id);
            console.log('Image section ID:', imageSection.id);
            console.log('After image section ID:', afterImageSection.id);

            // Test if elements can be found
            const beforeElement = renderer.findSectionElement(beforeImageSection.id);
            const imageElement = renderer.findSectionElement(imageSection.id);
            const afterElement = renderer.findSectionElement(afterImageSection.id);

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

            console.log('Before element found:', !!beforeElement);
            console.log('Image element found:', !!imageElement);
            console.log('After element found:', !!afterElement);

            // Test click simulation
            const testClickHandler = (element, sectionName) => {
                console.log(`Testing click on ${sectionName}:`);
                const sectionElement = element.closest('.ui-edit-section');
                console.log(`  - Found section element:`, !!sectionElement);
                if (sectionElement) {
                    const sectionId = sectionElement.getAttribute('data-section-id');
                    console.log(`  - Section ID:`, sectionId);
                    const section = manager.sections.get(sectionId);
                    console.log(`  - Section object found:`, !!section);
                    console.log(`  - Section is editing:`, section ? section.isEditing() : 'N/A');
                }
                return !!sectionElement;
            };

            const beforeWorks = testClickHandler(beforeElement, 'Before Image');
            const imageWorks = testClickHandler(imageElement, 'Image');
            const afterWorks = testClickHandler(afterElement, 'After Image');

            runner.expect(beforeWorks).toBeTruthy();
            runner.expect(imageWorks).toBeTruthy();
            runner.expect(afterWorks).toBeTruthy();

            // Cleanup
            document.body.removeChild(container);
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('🔍 Running Section Click Debug Tests');
    runner.run().then(() => {
        const results = runner.results;
        const failed = results.filter(r => r.status === 'FAIL').length;

        if (failed > 0) {
            console.log(`❌ ${failed} test(s) failed - section click issue needs investigation`);
            results.forEach(result => {
                if (result.status === 'FAIL') {
                    console.log(`\nFailed test: ${result.name}`);
                    if (result.error) {
                        console.log(`Error: ${result.error}`);
                    }
                }
            });
        } else {
            console.log('✅ All section click debug tests passed!');
        }
    });
}

module.exports = runner;