#!/usr/bin/env node

/**
 * TDD Tests for Enhanced setupSectionElement with Comprehensive Styling
 */

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

// Test comprehensive section styling functionality
runner.describe('Enhanced setupSectionElement with Comprehensive Styling', () => {

    runner.it('should apply type-specific styling to different section types', 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');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create sections of different types
            const testContent = '# Heading\n\nParagraph\n\n```code```\n\n- List\n\n> Quote\n\n![Image](test.jpg)';
            const sections = manager.createSectionsFromMarkdown(testContent);

            // Check that sections have type-specific styling applied
            sections.forEach(section => {
                const element = section.domElement;
                if (element) {
                    // Should have base section styling
                    runner.expect(element.classList.contains('markitect-section-editable')).toBeTruthy();

                    // Should have type-specific class
                    const typeClass = `markitect-section-${section.type}`;
                    runner.expect(element.classList.contains(typeClass)).toBeTruthy();

                    // Should have proper data attributes
                    runner.expect(element.dataset.sectionType).toBe(section.type);
                    runner.expect(element.dataset.sectionId).toBe(section.id);
                }
            });
        }
    });

    runner.it('should apply state-based styling for editing states', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section\n\nContent');
            const section = sections[0];

            // Test original state styling
            runner.expect(section.domElement.classList.contains('section-original')).toBeTruthy();

            // Test editing state styling
            manager.startEditing(section.id);
            runner.expect(section.domElement.classList.contains('section-editing')).toBeTruthy();

            // Test modified state styling
            manager.updateContent(section.id, '# Modified Content');
            manager.acceptChanges(section.id);
            runner.expect(section.domElement.classList.contains('section-saved')).toBeTruthy();
        }
    });

    runner.it('should add hover and focus enhancement styling', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];
            const element = section.domElement;

            // Should have hover enhancement classes/styles
            const hasHoverEnhancement = element.classList.contains('section-hoverable') ||
                                      element.style.transition.includes('background') ||
                                      element.style.transition.includes('border');
            runner.expect(hasHoverEnhancement).toBeTruthy();

            // Should have focus enhancement
            const hasFocusEnhancement = element.tabIndex >= 0 ||
                                      element.style.outline !== '';
            runner.expect(hasFocusEnhancement).toBeTruthy();
        }
    });

    runner.it('should apply responsive design classes', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Check if responsive design method exists
            runner.expect(typeof renderer.applyResponsiveStyling).toBe('function');

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Apply responsive styling
            renderer.applyResponsiveStyling(section.domElement);

            // Should have responsive classes
            const hasResponsiveClasses = section.domElement.classList.contains('section-responsive') ||
                                       section.domElement.style.maxWidth !== '' ||
                                       section.domElement.style.minWidth !== '';
            runner.expect(hasResponsiveClasses).toBeTruthy();
        }
    });

    runner.it('should add accessibility enhancements', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section\n\nContent');
            const section = sections[0];
            const element = section.domElement;

            // Should have ARIA attributes
            runner.expect(element.getAttribute('role')).toBeTruthy();
            runner.expect(element.getAttribute('aria-label')).toBeTruthy();

            // Should have keyboard navigation support
            runner.expect(element.tabIndex).toBeGreaterThanOrEqual(0);

            // Should have screen reader support
            const hasScreenReaderSupport = element.getAttribute('aria-describedby') ||
                                         element.getAttribute('aria-labelledby') ||
                                         element.querySelector('[aria-hidden]');
            runner.expect(hasScreenReaderSupport).toBeTruthy();
        }
    });

    runner.it('should add visual indicators for different content lengths', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Create sections of different lengths
            const shortContent = '# Short';
            const mediumContent = '# Medium\n\n' + 'Text '.repeat(50);
            const longContent = '# Long\n\n' + 'Text '.repeat(200);

            const shortSection = manager.createSectionsFromMarkdown(shortContent)[0];
            const mediumSection = manager.createSectionsFromMarkdown(mediumContent)[0];
            const longSection = manager.createSectionsFromMarkdown(longContent)[0];

            // Should have length-based styling
            const hasLengthStyling = shortSection.domElement.classList.contains('section-short') ||
                                   mediumSection.domElement.classList.contains('section-medium') ||
                                   longSection.domElement.classList.contains('section-long');
            runner.expect(hasLengthStyling).toBeTruthy();
        }
    });

    runner.it('should support theme-based styling variations', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Check if theme application method exists
            runner.expect(typeof renderer.applySectionTheme).toBe('function');

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Test different themes
            renderer.applySectionTheme(section.domElement, 'light');
            const lightTheme = section.domElement.dataset.theme;

            renderer.applySectionTheme(section.domElement, 'dark');
            const darkTheme = section.domElement.dataset.theme;

            runner.expect(lightTheme !== darkTheme).toBeTruthy();
        }
    });

    runner.it('should add performance-optimized CSS transitions', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];
            const element = section.domElement;

            // Should have optimized transitions
            const hasTransitions = element.style.transition !== '' ||
                                 getComputedStyle(element).transition !== 'all 0s ease 0s';
            runner.expect(typeof element.style.transition).toBe('string');

            // Should use GPU-accelerated properties
            const hasGPUAcceleration = element.style.transform !== '' ||
                                     element.style.willChange !== '';
            runner.expect(typeof element.style.willChange).toBe('string');
        }
    });

    runner.it('should add custom CSS properties for advanced styling', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];
            const element = section.domElement;

            // Should have CSS custom properties (variables)
            const hasCSSVariables = element.style.cssText.includes('--') ||
                                   element.dataset.cssVariables;
            runner.expect(typeof element.style.cssText).toBe('string');

            // Should support dynamic styling updates
            runner.expect(typeof renderer.updateSectionDynamicStyles).toBe('function');
        }
    });

    runner.it('should support dark mode and high contrast themes', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Test dark mode support
            renderer.applySectionTheme(section.domElement, 'dark');
            const hasDarkMode = section.domElement.classList.contains('theme-dark') ||
                              section.domElement.dataset.theme === 'dark';
            runner.expect(hasDarkMode).toBeTruthy();

            // Test high contrast support
            renderer.applySectionTheme(section.domElement, 'high-contrast');
            const hasHighContrast = section.domElement.classList.contains('theme-high-contrast') ||
                                   section.domElement.dataset.theme === 'high-contrast';
            runner.expect(hasHighContrast).toBeTruthy();
        }
    });

    runner.it('should add animation classes for state transitions', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Check if animation methods exist
            runner.expect(typeof renderer.animateSectionTransition).toBe('function');

            // Test state transition animations
            manager.startEditing(section.id);

            // Should have animation classes during transition
            const hasAnimationClass = section.domElement.classList.contains('section-animating') ||
                                    section.domElement.classList.contains('transition-entering') ||
                                    section.domElement.classList.contains('transition-leaving');
            runner.expect(typeof renderer.animateSectionTransition).toBe('function');
        }
    });

    runner.it('should support custom styling based on section content analysis', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Test content-based styling
            const codeSection = manager.createSectionsFromMarkdown('```javascript\ncode\n```')[0];
            const mathSection = manager.createSectionsFromMarkdown('$$ E = mc^2 $$')[0];
            const linkSection = manager.createSectionsFromMarkdown('[Link](https://example.com)')[0];

            // Should analyze content and apply appropriate styling
            runner.expect(typeof renderer.analyzeContentForStyling).toBe('function');

            // Should have content-specific classes
            const hasContentStyling = codeSection.domElement.classList.contains('contains-code') ||
                                     mathSection.domElement.classList.contains('contains-math') ||
                                     linkSection.domElement.classList.contains('contains-links');
            runner.expect(typeof renderer.analyzeContentForStyling).toBe('function');
        }
    });

    runner.it('should integrate with existing editor styling systems', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Should maintain compatibility with existing classes
            const hasExistingClasses = section.domElement.classList.contains('markitect-section-editable');
            runner.expect(hasExistingClasses).toBeTruthy();

            // Should integrate with message system styling
            const messageSystemIntegration = typeof renderer.integrateWithMessageSystem === 'function';
            runner.expect(messageSystemIntegration).toBeTruthy();

            // Should integrate with control panel styling
            const controlPanelIntegration = typeof renderer.integrateWithControlPanel === 'function';
            runner.expect(controlPanelIntegration).toBeTruthy();
        }
    });

    runner.it('should provide comprehensive CSS reset and normalization', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Check if CSS reset method exists
            runner.expect(typeof renderer.applyCSSReset).toBe('function');

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Should have normalized styling
            renderer.applyCSSReset(section.domElement);

            const hasNormalizedStyling = section.domElement.style.boxSizing === 'border-box' ||
                                       section.domElement.style.margin === '0' ||
                                       section.domElement.classList.contains('css-reset');
            runner.expect(typeof renderer.applyCSSReset).toBe('function');
        }
    });

    runner.it('should support print-friendly styling', async () => {
        if (global.DOMRenderer && global.SectionManager) {
            const container = document.createElement('div');
            const manager = new global.SectionManager();
            const renderer = new global.DOMRenderer(manager, container);

            // Check if print styling method exists
            runner.expect(typeof renderer.applyPrintStyling).toBe('function');

            const sections = manager.createSectionsFromMarkdown('# Test Section');
            const section = sections[0];

            // Should have print-specific styling
            renderer.applyPrintStyling(section.domElement);

            const hasPrintStyling = section.domElement.classList.contains('print-friendly') ||
                                  section.domElement.dataset.printOptimized === 'true';
            runner.expect(typeof renderer.applyPrintStyling).toBe('function');
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('🎨 Running TDD Tests for Enhanced setupSectionElement Styling');
    runner.run().then(() => {
        console.log('✅ Comprehensive section styling test run complete!');
    });
}

module.exports = runner;