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

const html = fs.readFileSync('index.html', 'utf8');

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

// Mock DB
window.indexedDB = {};
window.DB = {
    getAll: async () => [],
    add: async () => 1,
    update: async () => {},
    remove: async () => {}
};

// Mock alert
window.alert = console.log;

// Load scripts manually
const scripts = ['db.js', 'app_final.js', 'vouchers_returns.js', 'sales_purchases_module.js', 'subcontracts.js'];
let scriptErr = false;
for (const s of scripts) {
    if (fs.existsSync(s)) {
        try {
            const code = fs.readFileSync(s, 'utf8');
            window.eval(code);
            console.log(`Successfully loaded ${s}`);
        } catch (e) {
            console.error(`Error loading ${s}:`, e.message, e.stack);
            scriptErr = true;
        }
    } else {
        console.error(`Script not found: ${s}`);
    }
}

if (!scriptErr) {
    console.log("All scripts loaded. Checking functions...");
    console.log("openSalesModal exists:", typeof window.openSalesModal === 'function');
    console.log("openSalesReturnsModal exists:", typeof window.openSalesReturnsModal === 'function');
    console.log("renderSales exists:", typeof window.renderSales === 'function');
    console.log("renderSalesReturns exists:", typeof window.renderSalesReturns === 'function');
}
