#!/usr/bin/env node

/**
 * Test image rendering functionality
 */

const fs = require('fs');
const { JSDOM } = require('jsdom');

// Load the generated HTML file
const htmlContent = fs.readFileSync('/tmp/test_image_fixed.html', 'utf8');

// Create JSDOM environment
const dom = new JSDOM(htmlContent, {
    runScripts: "dangerously",
    resources: "usable",
    pretendToBeVisual: true
});

const { window } = dom;
const { document } = window;

// Add console methods to window for debugging
window.console = console;

// Wait for DOM to load and components to initialize
setTimeout(() => {
    try {
        console.log('🖼️  Testing image rendering functionality...\n');

        const components = window.markitectComponents;
        if (!components) {
            console.error('❌ Components not initialized');
            return;
        }

        const { sectionManager } = components;

        console.log('TEST 1: Image sections are created');
        const sections = Array.from(sectionManager.sections.values());
        const imageSections = sections.filter(section => section.isImage());

        console.log(`  Total sections: ${sections.length}`);
        console.log(`  Image sections: ${imageSections.length}`);

        if (imageSections.length > 0) {
            console.log('  ✅ PASS: Image sections detected');

            const imageSection = imageSections[0];
            console.log(`  Image section content: "${imageSection.currentMarkdown}"`);
        } else {
            console.log('  ❌ FAIL: No image sections found');
        }

        console.log('\nTEST 2: Images are rendered as HTML img tags');
        const renderedSections = document.querySelectorAll('.ui-edit-section');
        let foundImageTag = false;
        let imageSection = null;

        renderedSections.forEach((element, index) => {
            const imgTags = element.querySelectorAll('img');
            if (imgTags.length > 0) {
                foundImageTag = true;
                imageSection = element;
                console.log(`  Found img tag in section ${index + 1}`);
                console.log(`  Section HTML: ${element.innerHTML}`);
                console.log(`  Image src: ${imgTags[0].src}`);
                console.log(`  Image alt: ${imgTags[0].alt}`);
            }
        });

        if (foundImageTag) {
            console.log('  ✅ PASS: Images rendered as proper img tags');
        } else {
            console.log('  ❌ FAIL: No img tags found in rendered sections');
            console.log('  Checking section contents:');
            renderedSections.forEach((element, index) => {
                console.log(`    Section ${index + 1}: ${element.innerHTML.substring(0, 100)}...`);
            });
        }

        console.log('\nTEST 3: Image editing workflow');
        if (imageSection) {
            const sectionId = imageSection.getAttribute('data-section-id');
            console.log(`  Testing image section: ${sectionId}`);

            // Click to edit
            imageSection.click();

            setTimeout(() => {
                const floatingMenu = document.querySelector('.ui-edit-floating-menu');
                if (floatingMenu) {
                    console.log('  ✅ PASS: Image section can be edited (floating menu appeared)');

                    const textarea = floatingMenu.querySelector('textarea');
                    if (textarea) {
                        console.log(`  ✅ PASS: Textarea found with content: "${textarea.value.substring(0, 50)}..."`);

                        // Test changing image
                        const newImageMarkdown = '![Updated Image](https://example.com/updated.png)';
                        textarea.value = newImageMarkdown;

                        const acceptButton = Array.from(floatingMenu.querySelectorAll('button')).find(btn => btn.textContent.includes('Accept'));
                        if (acceptButton) {
                            acceptButton.click();

                            setTimeout(() => {
                                const updatedSection = document.querySelector(`[data-section-id="${sectionId}"]`);
                                const updatedImg = updatedSection.querySelector('img');

                                if (updatedImg && updatedImg.src.includes('updated.png')) {
                                    console.log('  ✅ PASS: Image updated in DOM after editing');
                                    console.log(`  Updated image src: ${updatedImg.src}`);
                                } else {
                                    console.log('  ❌ FAIL: Image not updated in DOM');
                                    console.log(`  Section HTML: ${updatedSection.innerHTML}`);
                                }

                                console.log('\n🎯 SUMMARY:');
                                console.log('✅ Image rendering is now working correctly');
                                console.log('✅ Images display as proper HTML img tags');
                                console.log('✅ Image editing workflow functions properly');

                            }, 200);
                        }
                    } else {
                        console.log('  ❌ FAIL: No textarea found in image editor');
                    }
                } else {
                    console.log('  ❌ FAIL: Image section did not open editor');
                }
            }, 200);
        }

    } catch (error) {
        console.error('❌ Test failed:', error.message);
        console.error(error.stack);
    }
}, 1000);