#!/usr/bin/env node

/**
 * Test X Button Functionality
 *
 * Tests the new X button in the FloatingMenu component
 */

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

runner.describe('FloatingMenu X Button Tests', () => {

    runner.it('should create X button in drag handle', 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);

            // Create test section
            const textMarkdown = 'Test section for X button';
            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: 400, bottom: 150, left: 50, width: 350, 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 X button exists
            const closeButton = menuElement.querySelector('.ui-edit-close-button');
            runner.expect(closeButton).toBeTruthy();
            runner.expect(closeButton.innerHTML).toBe('✕');
            runner.expect(closeButton.style.cursor).toBe('pointer');

            // Verify drag handle has proper structure
            const dragHandle = menuElement.querySelector('.ui-edit-drag-handle');
            runner.expect(dragHandle).toBeTruthy();
            runner.expect(dragHandle.style.justifyContent).toBe('space-between');

            // Verify left content exists
            const leftContent = dragHandle.querySelector('div');
            runner.expect(leftContent).toBeTruthy();
            runner.expect(leftContent.innerHTML).toContain('📝');
            runner.expect(leftContent.innerHTML).toContain('Editing Text');

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

    runner.it('should close menu when X button is clicked', 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);

            const textMarkdown = 'Test section for close functionality';
            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: 400, bottom: 150, left: 50, width: 350, height: 50 })
                }
            });

            renderer.findSectionElement = () => mockElement;

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

            const testContent = document.createElement('div');
            const testControls = document.createElement('div');

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

            // Verify menu is visible
            runner.expect(floatingMenu.isVisible).toBeTruthy();
            runner.expect(document.body.contains(menuElement)).toBeTruthy();

            // Click the X button
            const closeButton = menuElement.querySelector('.ui-edit-close-button');
            closeButton.click();

            // Verify menu is hidden
            runner.expect(floatingMenu.isVisible).toBeFalsy();
            runner.expect(document.body.contains(menuElement)).toBeFalsy();

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

    runner.it('should work correctly with image editor', 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);

            const imageMarkdown = '![Test](test.jpg)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

            renderer.findSectionElement = () => mockElement;

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

            const testContent = document.createElement('div');
            const testControls = document.createElement('div');

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

            // Verify X button exists in image editor
            const closeButton = menuElement.querySelector('.ui-edit-close-button');
            runner.expect(closeButton).toBeTruthy();

            // Verify image-specific content in drag handle
            const dragHandle = menuElement.querySelector('.ui-edit-drag-handle');
            runner.expect(dragHandle.innerHTML).toContain('🖼️');
            runner.expect(dragHandle.innerHTML).toContain('Editing Image');

            // Test close functionality
            closeButton.click();
            runner.expect(floatingMenu.isVisible).toBeFalsy();

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

// Run the tests
if (require.main === module) {
    console.log('✕ Running FloatingMenu X Button 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 - X button 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 X button tests passed!');
        }
    });
}

module.exports = runner;