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

const filesToTest = [
    'dashboard.html',
    'lab.html',
    'pharmacy.html',
    'staff.html',
    'settings.html',
    'style-guide.html'
];

async function runTests() {
    console.log('--- UI Frontend Tests ---');
    let allPassed = true;

    for (const file of filesToTest) {
        const filePath = path.join(__dirname, file);
        const html = fs.readFileSync(filePath, 'utf8');

        // Setup DOM
        const dom = new JSDOM(html, { runScripts: "dangerously" });
        const { window } = dom;
        const { document } = window;

        // Verify globals.js is included
        const scripts = Array.from(document.querySelectorAll('script'));
        const hasGlobalsJS = scripts.some(s => s.src.includes('globals.js'));
        if (!hasGlobalsJS) {
            console.error(`❌ [FAILED] ${file}: Missing globals.js inclusion!`);
            allPassed = false;
        }

        // Check buttons
        const buttons = document.querySelectorAll('button');
        let deadButtons = 0;
        
        buttons.forEach(btn => {
            const hasOnClick = btn.hasAttribute('onclick');
            const hasId = btn.hasAttribute('id');
            const isSubmit = btn.type === 'submit';
            const hasClass = btn.className.includes('btn');
            
            // If it's a structural button without logic, it's a dead click
            if (!hasOnClick && !hasId && !isSubmit && !btn.className.includes('close')) {
                deadButtons++;
                console.error(`❌ [FAILED] ${file}: Dead button found -> "${btn.textContent.trim()}"`);
            }
            
            // Ensure global classes are used
            if (!hasClass && !btn.className.includes('opt') && !btn.className.includes('close')) {
                console.warn(`⚠️ [WARNING] ${file}: Button missing global .btn class -> "${btn.textContent.trim()}"`);
            }
        });

        if (hasGlobalsJS && deadButtons === 0) {
            console.log(`✅ [PASSED] ${file}: All ${buttons.length} buttons are wired and globals.js is loaded.`);
        } else {
            allPassed = false;
        }
    }

    if (allPassed) {
        console.log('\n✅✅ ALL UI TESTS PASSED! Zero dead clicks confirmed.');
    } else {
        console.log('\n❌❌ SOME UI TESTS FAILED. Please review the logs above.');
    }
}

runTests().catch(console.error);
