#!/usr/bin/env node

/**
 * Test Floating Status Panel Removal
 *
 * Tests that the floating status panel is no longer created above the editor menu
 */

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

runner.describe('Floating Status Panel Removal Tests', () => {

    runner.it('should not create floating status panel when updateStatusDisplay is called', 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 a mock status object
            const mockStatus = {
                state: 'ready',
                totalSections: 5,
                editingSections: [],
                modifiedSections: 0
            };

            // Call updateStatusDisplay
            renderer.updateStatusDisplay(mockStatus);

            // Verify no floating status panel was created
            const statusPanel = document.querySelector('.ui-edit-status-panel');
            runner.expect(statusPanel).toBeFalsy();

            // Verify no status panel exists in body
            const statusPanels = document.querySelectorAll('.ui-edit-status-panel');
            runner.expect(statusPanels.length).toBe(0);

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

    runner.it('should handle multiple status updates without creating panels', 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);

            // Call updateStatusDisplay multiple times with different statuses
            const statuses = [
                { state: 'ready', totalSections: 5, editingSections: [], modifiedSections: 0 },
                { state: 'editing', totalSections: 5, editingSections: ['section1'], modifiedSections: 0 },
                { state: 'modified', totalSections: 5, editingSections: [], modifiedSections: 1 }
            ];

            statuses.forEach(status => {
                renderer.updateStatusDisplay(status);
            });

            // Verify still no floating status panels exist
            const statusPanels = document.querySelectorAll('.ui-edit-status-panel');
            runner.expect(statusPanels.length).toBe(0);

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

    runner.it('should not have createStatusPanel method available', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Verify createStatusPanel method is no longer available or does nothing
            if (typeof renderer.createStatusPanel === 'function') {
                // If method exists, it should not create elements
                const result = renderer.createStatusPanel();
                runner.expect(result).toBeFalsy();
            } else {
                // Method should not exist
                runner.expect(typeof renderer.createStatusPanel).toBe('undefined');
            }
        }
    });

    runner.it('should not interfere with control panel status display', 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 sections and render them
            const sections = manager.createSectionsFromMarkdown('# Test\n\nContent');
            renderer.renderAllSections(sections);

            // Verify that control panel functionality is unaffected
            runner.expect(typeof renderer.updateControlPanelStats).toBe('function');
            runner.expect(typeof renderer.createControlPanel).toBe('function');

            // Test that control panel can still be created
            const controlPanel = renderer.createControlPanel();
            runner.expect(controlPanel).toBeTruthy();
            runner.expect(controlPanel.tagName).toBe('DIV');

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

    runner.it('should handle status tracking setup without creating floating panels', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            container.innerHTML = '<div id="markdown-content"></div>';
            document.body.appendChild(container);

            // Create editor instance
            const editor = new global.MarkitectCleanEditor();

            // Mock the DOM elements editor expects
            const mockElement = container.querySelector('#markdown-content');
            if (mockElement) {
                // Set up basic content
                mockElement.innerHTML = '<p>Test content</p>';
            }

            // Test setupStatusTracking if it exists
            if (typeof editor.setupStatusTracking === 'function') {
                try {
                    editor.setupStatusTracking();

                    // Wait a moment for any async operations
                    await new Promise(resolve => setTimeout(resolve, 100));

                    // Verify no floating status panels were created
                    const statusPanels = document.querySelectorAll('.ui-edit-status-panel');
                    runner.expect(statusPanels.length).toBe(0);
                } catch (error) {
                    // If setup fails, ensure it's not due to panel creation
                    const statusPanels = document.querySelectorAll('.ui-edit-status-panel');
                    runner.expect(statusPanels.length).toBe(0);
                }
            }

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

// Run the tests
if (require.main === module) {
    console.log('🗑️ Running Floating Status Panel Removal 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 - floating status removal incomplete`);
        } else {
            console.log('✅ All floating status removal tests passed!');
        }
    });
}

module.exports = runner;