#!/usr/bin/env node

/**
 * Test Component Positioning
 *
 * Tests the new FloatingMenu component's button positioning logic:
 * - Wide displays: buttons in side margin
 * - Narrow displays: buttons below content
 */

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

runner.describe('FloatingMenu Component Positioning Tests', () => {

    runner.it('should position buttons in side margin on wide displays', 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 && global.FloatingMenu) {
            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);

            // Mock wide viewport (≥1200px)
            Object.defineProperty(window, 'innerWidth', { value: 1400, configurable: true });

            // Create test section
            const textMarkdown = 'This is a test section for wide display testing.';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            Object.defineProperties(mockElement, {
                getBoundingClientRect: {
                    value: () => ({
                        top: 100,
                        right: 600,
                        bottom: 150,
                        left: 50,
                        width: 550,  // Wide content
                        height: 50
                    })
                }
            });

            renderer.findSectionElement = () => mockElement;

            // Create FloatingMenu
            const floatingMenu = new global.FloatingMenu(textSection.id, 'text', renderer);

            const testContent = document.createElement('div');
            testContent.textContent = 'Test Content';

            const testControls = document.createElement('div');
            testControls.textContent = 'Test Controls';

            const menuElement = floatingMenu.show(testContent, testControls);

            // Verify menu positioning
            runner.expect(menuElement).toBeTruthy();
            runner.expect(menuElement.style.left).toBe('50px'); // Matches element left
            runner.expect(menuElement.style.width).toBe('550px'); // Matches content width

            // Check if controls are positioned in margin (separate element in body)
            const controlsElements = document.querySelectorAll('.ui-edit-controls-area');
            const sideControls = Array.from(controlsElements).find(el =>
                el.parentElement === document.body &&
                el.style.position === 'fixed'
            );

            runner.expect(sideControls).toBeTruthy();
            runner.expect(sideControls.style.left).toBe('590px'); // 50 + 550 + 20

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

    runner.it('should position buttons below content on narrow displays', async () => {
        if (global.DOMRenderer && global.SectionManager && global.FloatingMenu) {
            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);

            // Mock narrow viewport (<1200px)
            Object.defineProperty(window, 'innerWidth', { value: 800, configurable: true });

            // Create test section
            const textMarkdown = 'This is a test section for narrow display testing.';
            const sections = manager.createSectionsFromMarkdown(textMarkdown);
            const textSection = sections[0];

            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', textSection.id);
            Object.defineProperties(mockElement, {
                getBoundingClientRect: {
                    value: () => ({
                        top: 100,
                        right: 450,
                        bottom: 150,
                        left: 50,
                        width: 400,  // Regular content width
                        height: 50
                    })
                }
            });

            renderer.findSectionElement = () => mockElement;

            // Create FloatingMenu
            const floatingMenu = new global.FloatingMenu(textSection.id, 'text', renderer);

            const testContent = document.createElement('div');
            testContent.textContent = 'Test Content';

            const testControls = document.createElement('div');
            testControls.textContent = 'Test Controls';

            const menuElement = floatingMenu.show(testContent, testControls);

            // Verify menu positioning
            runner.expect(menuElement).toBeTruthy();
            runner.expect(menuElement.style.left).toBe('50px'); // Matches element left
            runner.expect(menuElement.style.width).toBe('400px'); // Matches content width

            // Check that controls are inside the main menu (not positioned separately)
            const controlsInMenu = menuElement.querySelector('.ui-edit-controls-area');
            runner.expect(controlsInMenu).toBeTruthy();
            runner.expect(controlsInMenu.style.position).not.toBe('fixed');

            // Verify no separate controls in body
            const sideControls = Array.from(document.querySelectorAll('.ui-edit-controls-area')).find(el =>
                el.parentElement === document.body &&
                el.style.position === 'fixed'
            );
            runner.expect(sideControls).toBeFalsy();

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

    runner.it('should work correctly with image editor component', async () => {
        if (global.DOMRenderer && global.SectionManager && global.FloatingMenu) {
            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);

            // Mock wide viewport
            Object.defineProperty(window, 'innerWidth', { value: 1400, configurable: true });

            // Create image section
            const imageMarkdown = '![Test Image](https://example.com/test.jpg)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

            runner.expect(imageSection.isImage()).toBeTruthy();

            const mockElement = document.createElement('div');
            mockElement.setAttribute('data-section-id', imageSection.id);
            Object.defineProperties(mockElement, {
                getBoundingClientRect: {
                    value: () => ({
                        top: 200,
                        right: 500,
                        bottom: 350,
                        left: 100,
                        width: 400,
                        height: 150
                    })
                }
            });

            renderer.findSectionElement = () => mockElement;

            // Create FloatingMenu for image
            const floatingMenu = new global.FloatingMenu(imageSection.id, 'image', renderer);

            const testContent = document.createElement('div');
            testContent.innerHTML = '<div class="ui-edit-image-preview">Image Preview</div>';

            const testControls = document.createElement('div');
            testControls.innerHTML = '<button>Accept</button><button>Cancel</button>';

            const menuElement = floatingMenu.show(testContent, testControls);

            // Verify image editor specific features
            runner.expect(menuElement).toBeTruthy();
            runner.expect(menuElement.dataset.editType).toBe('image');

            const dragHandle = menuElement.querySelector('.ui-edit-drag-handle');
            runner.expect(dragHandle.innerHTML).toContain('🖼️');
            runner.expect(dragHandle.innerHTML).toContain('Editing Image');

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

// Run the tests
if (require.main === module) {
    console.log('🔧 Running FloatingMenu Component 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 - component positioning needs attention`);
            results.forEach(result => {
                if (result.status === 'FAIL') {
                    console.log(`\nFailed test: ${result.name}`);
                    if (result.error) {
                        console.log(`Error: ${result.error}`);
                    }
                }
            });
        } else {
            console.log('✅ All FloatingMenu component positioning tests passed!');
        }
    });
}

module.exports = runner;