#!/usr/bin/env node

/**
 * TDD Tests for Comprehensive Status Dialog Integration
 */

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

// Test comprehensive status dialog functionality
runner.describe('Comprehensive Status Dialog Integration', () => {

    runner.it('should have showDocumentStatus method available', 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.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const editor = new global.MarkitectCleanEditor('# Test\n\nContent', container);

            runner.expect(typeof editor.showDocumentStatus).toBe('function');
        }
    });

    runner.it('should calculate document statistics correctly', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const testContent = '# Heading\n\nParagraph content\n\n```javascript\ncode();\n```\n\n- List item';
            const editor = new global.MarkitectCleanEditor(testContent, container);

            // Access status through the SectionManager
            const status = editor.sectionManager.getDocumentStatus();

            runner.expect(status.totalSections).toBeGreaterThan(0);
            runner.expect(typeof status.hasUnsavedChanges).toBe('boolean');
            runner.expect(typeof status.modifiedSections).toBe('number');
            runner.expect(typeof status.editingSections).toBe('number');
            runner.expect(typeof status.savedSections).toBe('number');
        }
    });

    runner.it('should collect event statistics from DOMRenderer', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const editor = new global.MarkitectCleanEditor('# Test\n\nContent', container);

            // Access event stats through the DOMRenderer
            const eventStats = editor.domRenderer.getEventStats();

            runner.expect(typeof eventStats).toBe('object');
            runner.expect(typeof eventStats.totalEvents).toBe('number');
            runner.expect(typeof eventStats.stats).toBe('object');
            runner.expect(Array.isArray(eventStats.recentEvents)).toBeTruthy();
        }
    });

    runner.it('should categorize sections by type', async () => {
        if (global.MarkitectCleanEditor && global.Section) {
            const container = document.createElement('div');
            const testContent = '# Heading\n\nParagraph\n\n```code```\n\n- List\n\n> Quote';
            const editor = new global.MarkitectCleanEditor(testContent, container);

            const sections = editor.sectionManager.getAllSections();

            runner.expect(sections.length).toBeGreaterThan(0);

            // Check that sections have types
            const typedSections = sections.filter(s => s.type && s.type !== 'paragraph');
            runner.expect(typedSections.length).toBeGreaterThan(0);
        }
    });

    runner.it('should categorize sections by size', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const testContent = [
                '# Short',  // Small
                'Medium length content that is between 100 and 500 characters. This should be categorized as medium size when the showDocumentStatus method analyzes it.', // Medium
                'Very long content that exceeds 500 characters and should be categorized as large. '.repeat(10) // Large
            ].join('\n\n');

            const editor = new global.MarkitectCleanEditor(testContent, container);
            const sections = editor.sectionManager.getAllSections();

            // Check that we have sections of different sizes
            const sizes = sections.map(s => {
                const length = s.currentMarkdown.length;
                if (length < 100) return 'small';
                else if (length < 500) return 'medium';
                else return 'large';
            });

            const uniqueSizes = new Set(sizes);
            runner.expect(uniqueSizes.size).toBeGreaterThan(1); // Should have multiple size categories
        }
    });

    runner.it('should generate comprehensive status HTML', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const testContent = '# Test Heading\n\nTest paragraph content\n\n```javascript\nconsole.log("test");\n```';
            const editor = new global.MarkitectCleanEditor(testContent, container);

            // Mock showModal to capture the HTML
            let capturedTitle = '';
            let capturedHtml = '';
            editor.showModal = (title, html) => {
                capturedTitle = title;
                capturedHtml = html;
            };

            // Call showDocumentStatus
            editor.showDocumentStatus();

            // Verify the modal was called with comprehensive content
            runner.expect(capturedTitle).toContain('Comprehensive Document Status');
            runner.expect(capturedHtml).toContain('Document Overview');
            runner.expect(capturedHtml).toContain('Section States');
            runner.expect(capturedHtml).toContain('Section Types');
            runner.expect(capturedHtml).toContain('Section Sizes');
            runner.expect(capturedHtml).toContain('Event Statistics');
            runner.expect(capturedHtml).toContain('Section Details');
        }
    });

    runner.it('should display section details table with proper data', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const testContent = '# Heading\n\nParagraph\n\n```code```';
            const editor = new global.MarkitectCleanEditor(testContent, container);

            let capturedHtml = '';
            editor.showModal = (title, html) => {
                capturedHtml = html;
            };

            editor.showDocumentStatus();

            // Check that the section details table is present
            runner.expect(capturedHtml).toContain('<table');
            runner.expect(capturedHtml).toContain('<thead');
            runner.expect(capturedHtml).toContain('<tbody');
            runner.expect(capturedHtml).toContain('Section');
            runner.expect(capturedHtml).toContain('Type');
            runner.expect(capturedHtml).toContain('State');
            runner.expect(capturedHtml).toContain('Length');
            runner.expect(capturedHtml).toContain('Changes');
        }
    });

    runner.it('should handle empty document gracefully', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const editor = new global.MarkitectCleanEditor('', container);

            let capturedHtml = '';
            editor.showModal = (title, html) => {
                capturedHtml = html;
            };

            // This should not throw an error
            editor.showDocumentStatus();

            runner.expect(capturedHtml).toBeTruthy();
            runner.expect(capturedHtml).toContain('Total Sections: 0');
        }
    });

    runner.it('should integrate with event tracking system', async () => {
        if (global.MarkitectCleanEditor) {
            const container = document.createElement('div');
            const testContent = '# Test\n\nContent';
            const editor = new global.MarkitectCleanEditor(testContent, container);

            // Simulate some events by calling the event tracking methods directly
            if (editor.domRenderer.trackEvent) {
                editor.domRenderer.trackEvent('section-click', { sectionId: 'test' });
                editor.domRenderer.trackEvent('keyboard-shortcut', { shortcut: 'ctrl+enter' });
            }

            let capturedHtml = '';
            editor.showModal = (title, html) => {
                capturedHtml = html;
            };

            editor.showDocumentStatus();

            // Should show event statistics
            runner.expect(capturedHtml).toContain('Event Statistics');
            runner.expect(capturedHtml).toContain('Total Events');
        }
    });
});

// Run the tests
if (require.main === module) {
    console.log('📊 Running Comprehensive Status Dialog Integration Tests');
    runner.run().then(() => {
        console.log('✅ Comprehensive status dialog tests complete!');
    });
}

module.exports = runner;