#!/usr/bin/env node

/**
 * Test Image Functionality Fix
 *
 * Tests to verify image editing functionality works correctly
 */

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

runner.describe('Image Functionality Fix Tests', () => {

    runner.it('should load editor with image handling methods', 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) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Check that image methods exist
            runner.expect(typeof renderer.showImageEditor).toBe('function');
            runner.expect(typeof renderer.replaceImage).toBe('function');
            runner.expect(typeof renderer.resizeImage).toBe('function');
            runner.expect(typeof renderer.addImageCaption).toBe('function');
            runner.expect(typeof renderer.removeImage).toBe('function');
        }
    });

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

            // Verify image is detected in content
            runner.expect(imageSection.currentMarkdown.includes('![Test Image]')).toBeTruthy();
            runner.expect(imageSection.currentMarkdown.includes('placeholder')).toBeTruthy();

            // Test that resizeImage method can be called without error
            try {
                // Mock prompt to avoid user interaction
                const originalPrompt = global.prompt;
                global.prompt = () => '300px';

                renderer.resizeImage(imageSection.id);

                global.prompt = originalPrompt;
                runner.expect(true).toBeTruthy(); // If we get here, no error occurred
            } catch (error) {
                runner.expect(false).toBeTruthy(); // Method should not throw
            }
        }
    });

    runner.it('should handle image replacement flow without errors', 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 updateSectionContent method exists (needed for image replacement)
            runner.expect(typeof renderer.updateSectionContent).toBe('function');

            // Verify the image section has proper structure
            runner.expect(imageSection.currentMarkdown.match(/!\[(.*?)\]\((.*?)\)/)).toBeTruthy();
        }
    });

    runner.it('should handle image alt text updates 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];

            // Test manual alt text update (simulating what showImageEditor does)
            const newMarkdown = imageSection.currentMarkdown.replace(
                /!\[(.*?)\]/,
                '![Updated Alt]'
            );

            manager.updateContent(imageSection.id, newMarkdown);

            runner.expect(imageSection.currentMarkdown.includes('Updated Alt')).toBeTruthy();
            runner.expect(imageSection.currentMarkdown.includes('Original Alt')).toBeFalsy();
        }
    });

    runner.it('should handle createButton method calls for image controls', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Test createButton method
            runner.expect(typeof renderer.createButton).toBe('function');

            // Test button creation with mock action
            const testAction = () => console.log('test action');
            const button = renderer.createButton('Test', 'test-class', testAction);

            runner.expect(button.tagName).toBe('BUTTON');
            runner.expect(button.textContent).toBe('Test');
            runner.expect(button.className).toBe('test-class');
        }
    });
});

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

module.exports = runner;