#!/usr/bin/env node

/**
 * Test Improved Image Editing Workflow
 *
 * Tests the new image editing features:
 * - Drop zone functionality
 * - Staging changes instead of immediate application
 * - Apply changes only on accept button
 */

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

runner.describe('Improved Image Editing Workflow Tests', () => {

    runner.it('should create image editor with drop zone functionality', 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 section with image
            const imageMarkdown = '![Test Image](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Render the section to create DOM element
            renderer.renderAllSections(sections);

            // Mock findSectionElement to return a test element
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify drop zone elements exist
            const imagePreview = testElement.querySelector('.ui-edit-image-preview');
            runner.expect(imagePreview).toBeTruthy();
            runner.expect(imagePreview.style.cursor).toBe('pointer');
            runner.expect(imagePreview.style.border.includes('dashed')).toBeTruthy();

            // Verify change indicator exists
            const changeIndicator = testElement.querySelector('.change-indicator');
            runner.expect(changeIndicator).toBeTruthy();
            runner.expect(changeIndicator.style.display).toBe('none'); // Initially hidden

            // Verify file input exists (hidden)
            const fileInput = testElement.querySelector('input[type="file"]');
            runner.expect(fileInput).toBeTruthy();
            runner.expect(fileInput.accept).toBe('image/*');

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

    runner.it('should handle staging state for image changes', 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);

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

            // Render the section to create DOM element
            renderer.renderAllSections(sections);

            // Mock findSectionElement
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify original content is unchanged
            runner.expect(imageSection.currentMarkdown).toBe(imageMarkdown);

            // Verify alt text input has original value
            const altTextInput = testElement.querySelector('input[type="text"]');
            runner.expect(altTextInput.value).toBe('Original Alt');

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

    runner.it('should track changes in staging state without immediate application', 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);

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

            // Render the section
            renderer.renderAllSections(sections);

            // Mock findSectionElement
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Get alt text input and change it
            const altTextInput = testElement.querySelector('input[type="text"]');
            altTextInput.value = 'Modified Alt Text';

            // Trigger input event to simulate user typing
            const inputEvent = new Event('input', { bubbles: true });
            altTextInput.dispatchEvent(inputEvent);

            // Verify section content is NOT immediately changed
            runner.expect(imageSection.currentMarkdown).toBe(originalMarkdown);
            runner.expect(imageSection.currentMarkdown.includes('Modified Alt Text')).toBeFalsy();

            // Verify change indicator is shown
            const changeIndicator = testElement.querySelector('.change-indicator');
            // Note: We can't test display style directly due to how it's updated via function closure
            runner.expect(changeIndicator).toBeTruthy();

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

    runner.it('should apply staged changes only when accept button is clicked', 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);

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

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

            // Render the section
            renderer.renderAllSections(sections);

            // Mock findSectionElement and updateSectionContent
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            let updatedContent = null;
            renderer.updateSectionContent = (sectionId, content) => {
                updatedContent = content;
            };

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Modify alt text
            const altTextInput = testElement.querySelector('input[type="text"]');
            altTextInput.value = 'Accepted Alt Text';
            const inputEvent = new Event('input', { bubbles: true });
            altTextInput.dispatchEvent(inputEvent);

            // Verify content still not changed
            runner.expect(imageSection.currentMarkdown).toBe(originalMarkdown);

            // Click accept button
            const acceptButton = testElement.querySelector('.ui-edit-accept');
            runner.expect(acceptButton).toBeTruthy();

            // Simulate accept button click
            acceptButton.click();

            // Verify changes were applied
            runner.expect(imageSection.currentMarkdown.includes('Accepted Alt Text')).toBeTruthy();
            runner.expect(updatedContent?.includes('Accepted Alt Text')).toBeTruthy();

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

    runner.it('should discard staged changes when cancel button is clicked', 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);

            // 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);

            // Render the section
            renderer.renderAllSections(sections);

            // Mock findSectionElement
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Modify alt text
            const altTextInput = testElement.querySelector('input[type="text"]');
            altTextInput.value = 'Should Be Discarded';
            const inputEvent = new Event('input', { bubbles: true });
            altTextInput.dispatchEvent(inputEvent);

            // Click cancel button
            const cancelButton = testElement.querySelector('.ui-edit-cancel');
            runner.expect(cancelButton).toBeTruthy();

            // Simulate cancel button click
            cancelButton.click();

            // Verify changes were discarded
            runner.expect(imageSection.currentMarkdown).toBe(originalMarkdown);
            runner.expect(imageSection.currentMarkdown.includes('Should Be Discarded')).toBeFalsy();

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

    runner.it('should reset staged changes when reset button is clicked', 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);

            // 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);

            // Render the section
            renderer.renderAllSections(sections);

            // Mock findSectionElement
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Modify alt text
            const altTextInput = testElement.querySelector('input[type="text"]');
            altTextInput.value = 'Should Be Reset';
            const inputEvent = new Event('input', { bubbles: true });
            altTextInput.dispatchEvent(inputEvent);

            // Click reset button
            const resetButton = testElement.querySelector('.ui-edit-reset');
            runner.expect(resetButton).toBeTruthy();

            // Simulate reset button click
            resetButton.click();

            // Verify alt text input was reset to original
            runner.expect(altTextInput.value).toBe('Original Alt');

            // Verify section content is still original
            runner.expect(imageSection.currentMarkdown).toBe(originalMarkdown);

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

    runner.it('should handle drag and drop event listeners', 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);

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

            // Render the section
            renderer.renderAllSections(sections);

            // Mock findSectionElement
            const testElement = document.createElement('div');
            testElement.setAttribute('data-section-id', imageSection.id);
            renderer.findSectionElement = () => testElement;

            // Show image editor
            renderer.showImageEditor(imageSection.id, imageSection);

            // Get image preview element
            const imagePreview = testElement.querySelector('.ui-edit-image-preview');
            runner.expect(imagePreview).toBeTruthy();

            // Test that drag event listeners are attached by checking if events can be created
            // We can't fully test the drag functionality without complex event simulation,
            // but we can verify the elements and basic structure

            // Verify the element has pointer cursor for click functionality
            runner.expect(imagePreview.style.cursor).toBe('pointer');

            // Verify file input exists for click-to-select functionality
            const fileInput = testElement.querySelector('input[type="file"]');
            runner.expect(fileInput).toBeTruthy();
            runner.expect(fileInput.style.display).toBe('none');

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

// Run the tests
if (require.main === module) {
    console.log('🎨 Running Improved Image Editing Workflow 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 workflow needs attention`);
        } else {
            console.log('✅ All improved image workflow tests passed!');
        }
    });
}

module.exports = runner;