#!/usr/bin/env node

/**
 * Test Image Section Editing Buttons
 *
 * Tests to verify accept, reset, and cancel buttons work correctly in image section editing
 */

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

runner.describe('Image Section Editing Buttons Tests', () => {

    runner.it('should identify image editor container correctly', 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 mock button inside image editor container
            const imageEditorContainer = document.createElement('div');
            imageEditorContainer.className = 'ui-edit-image-editor-container';

            const mockButton = document.createElement('button');
            imageEditorContainer.appendChild(mockButton);

            const sectionElement = document.createElement('div');
            sectionElement.setAttribute('data-section-id', 'test-section-id');
            sectionElement.appendChild(imageEditorContainer);

            // Test getCurrentEditingSectionId with image editor container
            const sectionId = renderer.getCurrentEditingSectionId(mockButton);
            runner.expect(sectionId).toBe('test-section-id');
        }
    });

    runner.it('should handle image section with correct buttons', 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 Image](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Verify createButton method is available for button creation
            runner.expect(typeof renderer.createButton).toBe('function');

            // Test button creation
            const testButton = renderer.createButton('Test Button', 'test-class', () => {});
            runner.expect(testButton.tagName).toBe('BUTTON');
            runner.expect(testButton.textContent).toBe('Test Button');
        }
    });

    runner.it('should have proper button handlers for image editing', 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 Text](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Start editing to prepare the section
            manager.startEditing(imageSection.id);

            // Test that section manager methods exist for button functionality
            runner.expect(typeof manager.acceptChanges).toBe('function');
            runner.expect(typeof manager.cancelChanges).toBe('function');
            runner.expect(typeof manager.resetSection).toBe('function');

            // Test updateContent method for alt text changes
            runner.expect(typeof manager.updateContent).toBe('function');

            // Test that renderer has necessary methods
            runner.expect(typeof renderer.updateSectionContent).toBe('function');
            runner.expect(typeof renderer.hideEditor).toBe('function');
            runner.expect(typeof renderer.showImageEditor).toBe('function');
        }
    });

    runner.it('should handle alt text updates in accept button flow', 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 originalMarkdown = '![Original Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(originalMarkdown);
            const imageSection = sections[0];

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

            // Simulate alt text update (what accept button does)
            const newMarkdown = imageSection.currentMarkdown.replace(
                /!\[(.*?)\]/,
                '![Updated Alt Text]'
            );

            manager.updateContent(imageSection.id, newMarkdown);

            // Verify alt text was updated
            runner.expect(imageSection.currentMarkdown.includes('Updated Alt Text')).toBeTruthy();
            runner.expect(imageSection.currentMarkdown.includes('Original Alt')).toBeFalsy();

            // Test accept flow
            manager.acceptChanges(imageSection.id);
            runner.expect(imageSection.state).toBe('saved');
        }
    });

    runner.it('should handle cancel button flow correctly', 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 originalMarkdown = '![Original Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(originalMarkdown);
            const imageSection = sections[0];

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

            // Make changes (simulate user editing)
            const modifiedMarkdown = imageSection.currentMarkdown.replace(
                /!\[(.*?)\]/,
                '![Modified Alt]'
            );
            manager.updateContent(imageSection.id, modifiedMarkdown);

            // Test cancel flow - should revert changes
            manager.cancelChanges(imageSection.id);

            // Verify changes were cancelled (content should be back to original)
            runner.expect(imageSection.currentMarkdown.includes('Original Alt')).toBeTruthy();
            runner.expect(imageSection.currentMarkdown.includes('Modified Alt')).toBeFalsy();
        }
    });

    runner.it('should handle reset button flow correctly', 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 originalMarkdown = '![Original Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(originalMarkdown);
            const imageSection = sections[0];

            // Start editing and make changes
            manager.startEditing(imageSection.id);
            const modifiedMarkdown = imageSection.currentMarkdown.replace(
                /!\[(.*?)\]/,
                '![Modified Alt]'
            );
            manager.updateContent(imageSection.id, modifiedMarkdown);
            manager.acceptChanges(imageSection.id);

            // At this point section has saved changes
            runner.expect(imageSection.currentMarkdown.includes('Modified Alt')).toBeTruthy();

            // Test reset flow - should go back to original
            manager.resetSection(imageSection.id);

            // Verify section was reset to original content
            runner.expect(imageSection.currentMarkdown.includes('Original Alt')).toBeTruthy();
            runner.expect(imageSection.currentMarkdown.includes('Modified Alt')).toBeFalsy();
            runner.expect(imageSection.state).toBe('original');
        }
    });

    runner.it('should properly identify editor containers for both text and image editors', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Test text editor container
            const textEditorContainer = document.createElement('div');
            textEditorContainer.className = 'ui-edit-editor-container';
            const textButton = document.createElement('button');
            textEditorContainer.appendChild(textButton);

            const textSection = document.createElement('div');
            textSection.setAttribute('data-section-id', 'text-section');
            textSection.appendChild(textEditorContainer);

            // Test image editor container
            const imageEditorContainer = document.createElement('div');
            imageEditorContainer.className = 'ui-edit-image-editor-container';
            const imageButton = document.createElement('button');
            imageEditorContainer.appendChild(imageButton);

            const imageSection = document.createElement('div');
            imageSection.setAttribute('data-section-id', 'image-section');
            imageSection.appendChild(imageEditorContainer);

            // Both should work with getCurrentEditingSectionId
            const textSectionId = renderer.getCurrentEditingSectionId(textButton);
            const imageSectionId = renderer.getCurrentEditingSectionId(imageButton);

            runner.expect(textSectionId).toBe('text-section');
            runner.expect(imageSectionId).toBe('image-section');
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('🖼️ Running Image Section Editing Buttons 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 - image section buttons need attention`);
        } else {
            console.log('✅ All image section button tests passed!');
        }
    });
}

module.exports = runner;