#!/usr/bin/env node

/**
 * Test Image UI Closure
 *
 * Tests to verify that accept, cancel, and reset buttons properly close the image editing UI
 */

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

runner.describe('Image UI Closure Tests', () => {

    runner.it('should remove image editor container when hideEditor is called', 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');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create a section element with an image editor container
            const sectionElement = document.createElement('div');
            sectionElement.setAttribute('data-section-id', 'test-section');

            const imageEditorContainer = document.createElement('div');
            imageEditorContainer.className = 'ui-edit-image-editor-container';
            sectionElement.appendChild(imageEditorContainer);

            // Mock findSectionElement to return our test element
            renderer.findSectionElement = () => sectionElement;

            // Verify container exists before hiding
            runner.expect(sectionElement.querySelector('.ui-edit-image-editor-container')).toBeTruthy();

            // Call hideEditor
            renderer.hideEditor('test-section');

            // Verify container was removed
            runner.expect(sectionElement.querySelector('.ui-edit-image-editor-container')).toBeFalsy();
        }
    });

    runner.it('should remove text editor container when hideEditor is called', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create a section element with a text editor container
            const sectionElement = document.createElement('div');
            sectionElement.setAttribute('data-section-id', 'test-section');

            const textEditorContainer = document.createElement('div');
            textEditorContainer.className = 'ui-edit-editor-container';
            sectionElement.appendChild(textEditorContainer);

            // Mock findSectionElement to return our test element
            renderer.findSectionElement = () => sectionElement;

            // Verify container exists before hiding
            runner.expect(sectionElement.querySelector('.ui-edit-editor-container')).toBeTruthy();

            // Call hideEditor
            renderer.hideEditor('test-section');

            // Verify container was removed
            runner.expect(sectionElement.querySelector('.ui-edit-editor-container')).toBeFalsy();
        }
    });

    runner.it('should handle case where no editor containers exist', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create a section element with no editor containers
            const sectionElement = document.createElement('div');
            sectionElement.setAttribute('data-section-id', 'test-section');

            // Mock findSectionElement to return our test element
            renderer.findSectionElement = () => sectionElement;

            // Call hideEditor - should not throw error
            try {
                renderer.hideEditor('test-section');
                runner.expect(true).toBeTruthy(); // Should reach here without error
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Should not throw
            }
        }
    });

    runner.it('should handle both editor types in same element', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create a section element with both editor containers
            const sectionElement = document.createElement('div');
            sectionElement.setAttribute('data-section-id', 'test-section');

            const textEditorContainer = document.createElement('div');
            textEditorContainer.className = 'ui-edit-editor-container';
            sectionElement.appendChild(textEditorContainer);

            const imageEditorContainer = document.createElement('div');
            imageEditorContainer.className = 'ui-edit-image-editor-container';
            sectionElement.appendChild(imageEditorContainer);

            // Mock findSectionElement to return our test element
            renderer.findSectionElement = () => sectionElement;

            // Verify both containers exist before hiding
            runner.expect(sectionElement.querySelector('.ui-edit-editor-container')).toBeTruthy();
            runner.expect(sectionElement.querySelector('.ui-edit-image-editor-container')).toBeTruthy();

            // Call hideEditor
            renderer.hideEditor('test-section');

            // Verify both containers were removed
            runner.expect(sectionElement.querySelector('.ui-edit-editor-container')).toBeFalsy();
            runner.expect(sectionElement.querySelector('.ui-edit-image-editor-container')).toBeFalsy();
        }
    });

    runner.it('should verify accept button closes UI by calling hideEditor', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create section with image
            const imageMarkdown = '![Test Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Start editing
            manager.startEditing(imageSection.id);

            // Test that hideEditor is available and can be called
            runner.expect(typeof renderer.hideEditor).toBe('function');

            // Simulate what accept button does
            try {
                manager.acceptChanges(imageSection.id);
                renderer.hideEditor(imageSection.id);
                runner.expect(true).toBeTruthy(); // Should complete without error
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Should not throw
            }
        }
    });

    runner.it('should verify cancel button closes UI by calling hideEditor', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create section with image
            const imageMarkdown = '![Test Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Start editing
            manager.startEditing(imageSection.id);

            // Simulate what cancel button does
            try {
                manager.cancelChanges(imageSection.id);
                renderer.hideEditor(imageSection.id);
                runner.expect(true).toBeTruthy(); // Should complete without error
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Should not throw
            }
        }
    });

    runner.it('should verify reset button closes UI by calling hideEditor', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create section with image
            const imageMarkdown = '![Test Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Start editing
            manager.startEditing(imageSection.id);

            // Simulate what reset button does
            try {
                manager.resetSection(imageSection.id);
                renderer.hideEditor(imageSection.id);
                // Should also update content
                renderer.updateSectionContent(imageSection.id, imageSection.currentMarkdown);
                runner.expect(true).toBeTruthy(); // Should complete without error
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Should not throw
            }
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('🎭 Running Image UI Closure 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 - UI closure needs attention`);
        } else {
            console.log('✅ All image UI closure tests passed!');
        }
    });
}

module.exports = runner;