#!/usr/bin/env node

/**
 * Test Buttons Top, Alt Text Bottom Layout
 *
 * Tests that buttons appear at the top of the margin and alt text at the bottom
 */

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

runner.describe('Buttons Top, Alt Text Bottom Layout Tests', () => {

    runner.it('should position buttons at top and alt text at bottom of margin', 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 Alt Text](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

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

            // Get controls container and verify order
            const controls = mockElement.querySelector('.ui-edit-controls');
            const children = Array.from(controls.children);

            // Verify button group is first (top of margin)
            runner.expect(children[0].className).toBe('ui-edit-button-group');

            // Verify alt text group is second (bottom of margin due to margin-top: auto)
            runner.expect(children[1].className).toBe('ui-edit-alt-text-group');

            // Verify button group contains buttons
            const buttonGroup = children[0];
            const buttons = buttonGroup.querySelectorAll('button');
            runner.expect(buttons.length).toBe(3);

            // Verify alt text group contains alt text and change indicator
            const altTextGroup = children[1];
            const altTextContainer = altTextGroup.querySelector('.ui-edit-alt-text-container');
            const changeIndicator = altTextGroup.querySelector('.change-indicator');
            runner.expect(altTextContainer).toBeTruthy();
            runner.expect(changeIndicator).toBeTruthy();

            // Verify alt text group has margin-top: auto for bottom positioning
            runner.expect(altTextGroup.style.marginTop).toBe('auto');

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

    runner.it('should maintain button group styling for vertical layout', 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](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify button group styling
            const buttonGroup = mockElement.querySelector('.ui-edit-button-group');
            runner.expect(buttonGroup.style.display).toBe('flex');
            runner.expect(buttonGroup.style.flexDirection).toBe('column');
            runner.expect(buttonGroup.style.gap).toBe('8px');

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

    runner.it('should include responsive CSS for grouped layout', 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](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

            // Show editor (this adds responsive CSS)
            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify responsive style includes group rules
            const responsiveStyles = Array.from(document.head.querySelectorAll('style')).find(style =>
                style.textContent.includes('@media (max-width: 1024px)')
            );
            runner.expect(responsiveStyles).toBeTruthy();

            const cssText = responsiveStyles.textContent;
            runner.expect(cssText.includes('.ui-edit-button-group')).toBeTruthy();
            runner.expect(cssText.includes('.ui-edit-alt-text-group')).toBeTruthy();
            runner.expect(cssText.includes('flex-direction: row !important')).toBeTruthy();
            runner.expect(cssText.includes('order: -1 !important')).toBeTruthy();

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

    runner.it('should handle controls with space-between justification', 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](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify controls use space-between to push alt text to bottom
            const controls = mockElement.querySelector('.ui-edit-controls');
            runner.expect(controls.style.justifyContent).toBe('space-between');

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

    runner.it('should maintain proper content order: buttons then alt text', 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 Alt](https://via.placeholder.com/400x200)';
            const sections = manager.createSectionsFromMarkdown(imageMarkdown);
            const imageSection = sections[0];

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

            renderer.showImageEditor(imageSection.id, imageSection);

            // Verify functional accessibility
            const acceptBtn = mockElement.querySelector('button');
            const altTextInput = mockElement.querySelector('input[type="text"]');

            runner.expect(acceptBtn).toBeTruthy();
            runner.expect(altTextInput).toBeTruthy();
            runner.expect(altTextInput.value).toBe('Test Alt');

            // Verify buttons come before alt text in the controls
            const controls = mockElement.querySelector('.ui-edit-controls');
            const buttonGroup = controls.querySelector('.ui-edit-button-group');
            const altTextGroup = controls.querySelector('.ui-edit-alt-text-group');

            // Get positions to verify order
            const buttonPosition = Array.from(controls.children).indexOf(buttonGroup);
            const altTextPosition = Array.from(controls.children).indexOf(altTextGroup);

            runner.expect(buttonPosition).toBeLessThan(altTextPosition);

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

// Run the tests
if (require.main === module) {
    console.log('🔄 Running Buttons Top, Alt Text Bottom Layout 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 - button/alt text layout needs attention`);
        } else {
            console.log('✅ All button/alt text layout tests passed!');
        }
    });
}

module.exports = runner;