#!/usr/bin/env node

/**
 * Test Exact Overlay Positioning
 *
 * Tests that the edit UI overlays exactly on top of original content without
 * changing layout or pushing content down
 */

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

runner.describe('Exact Overlay Positioning Tests', () => {

    runner.it('should use absolute positioning for text editor overlay', 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);

            const textMarkdown = '# Test Content\n\nThis is test content.';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            // Mock element with specific dimensions
            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            mockElement.style.cssText = `
                width: 600px;
                height: 150px;
                padding: 20px;
                margin: 10px;
                border: 1px solid #ccc;
            `;
            Object.defineProperties(mockElement, {
                offsetWidth: { get: () => 600 },
                offsetHeight: { get: () => 150 }
            });

            renderer.findSectionElement = () => mockElement;

            // Show editor
            renderer.showEditor(textSection.id, textSection.currentMarkdown);

            // Verify overlay uses absolute positioning
            const overlayContainer = mockElement.querySelector('.ui-edit-overlay-container');
            runner.expect(overlayContainer).toBeTruthy();
            runner.expect(overlayContainer.style.position).toBe('absolute');
            runner.expect(overlayContainer.style.top).toBe('0px');
            runner.expect(overlayContainer.style.left).toBe('0px');
            runner.expect(overlayContainer.style.zIndex).toBe('1000');

            // Verify exact dimension matching
            runner.expect(overlayContainer.style.width).toBe('600px');
            runner.expect(overlayContainer.style.height).toBe('150px');

            // Verify element is positioned relative
            runner.expect(mockElement.style.position).toBe('relative');

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

    runner.it('should use absolute positioning for image editor overlay', 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 imageMarkdown = '![Test Image](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            // Mock element with specific dimensions
            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', imageSection.id);
            mockElement.style.cssText = `
                width: 800px;
                height: 300px;
                padding: 15px;
            `;
            Object.defineProperties(mockElement, {
                offsetWidth: { get: () => 800 },
                offsetHeight: { get: () => 300 }
            });

            renderer.findSectionElement = () => mockElement;

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

            // Verify overlay uses absolute positioning
            const overlayContainer = mockElement.querySelector('.ui-edit-overlay-container');
            runner.expect(overlayContainer).toBeTruthy();
            runner.expect(overlayContainer.style.position).toBe('absolute');
            runner.expect(overlayContainer.style.top).toBe('0px');
            runner.expect(overlayContainer.style.left).toBe('0px');
            runner.expect(overlayContainer.style.zIndex).toBe('1000');

            // Verify exact dimension matching
            runner.expect(overlayContainer.style.width).toBe('800px');
            runner.expect(overlayContainer.style.height).toBe('300px');

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

    runner.it('should preserve original padding in overlay', 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 textMarkdown = '# Test Content';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            // Mock element with specific padding
            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            mockElement.style.cssText = `
                width: 500px;
                height: 200px;
                padding: 25px 30px 20px 15px;
            `;
            Object.defineProperties(mockElement, {
                offsetWidth: { get: () => 500 },
                offsetHeight: { get: () => 200 }
            });

            renderer.findSectionElement = () => mockElement;

            // Show editor
            renderer.showEditor(textSection.id, textSection.currentMarkdown);

            // Verify overlay preserves padding
            const overlayContainer = mockElement.querySelector('.ui-edit-overlay-container');
            runner.expect(overlayContainer.style.padding).toBe('25px 30px 20px 15px');

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

    runner.it('should size textarea to fit available space', 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 textMarkdown = '# Test Content';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            // Mock element with known dimensions
            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            Object.defineProperties(mockElement, {
                offsetWidth: { get: () => 600 },
                offsetHeight: { get: () => 200 }
            });

            renderer.findSectionElement = () => mockElement;

            // Show editor
            renderer.showEditor(textSection.id, textSection.currentMarkdown);

            // Verify textarea sizing
            const textarea = mockElement.querySelector('.ui-edit-textarea');
            runner.expect(textarea).toBeTruthy();
            runner.expect(textarea.style.resize).toBe('none');
            runner.expect(textarea.style.boxSizing).toBe('border-box');
            runner.expect(textarea.style.overflowY).toBe('auto');

            // Height should be calculated based on available space
            const height = parseInt(textarea.style.height);
            runner.expect(height).toBeGreaterThan(60); // Minimum height
            runner.expect(height).toBeLessThan(200); // Should fit in container

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

    runner.it('should restore original positioning when editor is hidden', 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 textMarkdown = '# Test Content';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            renderer.findSectionElement = () => mockElement;

            // Verify element starts without position style
            runner.expect(mockElement.style.position).toBe('');

            // Show editor
            renderer.showEditor(textSection.id, textSection.currentMarkdown);

            // Verify element becomes relatively positioned
            runner.expect(mockElement.style.position).toBe('relative');

            // Hide editor
            renderer.hideEditor(textSection.id);

            // Verify position is restored
            runner.expect(mockElement.style.position).toBe('');

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

    runner.it('should store and restore original content', 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 textMarkdown = '# Test Content';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            mockElement.innerHTML = '<p>Original content here</p>';
            const originalContent = mockElement.innerHTML;

            renderer.findSectionElement = () => mockElement;

            // Show editor
            renderer.showEditor(textSection.id, textSection.currentMarkdown);

            // Verify original content is stored
            const overlayContainer = mockElement.querySelector('.ui-edit-overlay-container');
            runner.expect(overlayContainer.dataset.originalContent).toBe(originalContent);

            // Mock updateSectionContent
            renderer.updateSectionContent = () => {};

            // Hide editor
            renderer.hideEditor(textSection.id);

            // Verify content is restored
            runner.expect(mockElement.innerHTML).toBe(originalContent);

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

// Run the tests
if (require.main === module) {
    console.log('📏 Running Exact Overlay Positioning 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 - overlay positioning needs attention`);
        } else {
            console.log('✅ All exact overlay positioning tests passed!');
        }
    });
}

module.exports = runner;