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

const html = fs.readFileSync('index.html', 'utf8');
const dom = new JSDOM(html, { runScripts: "dangerously" });

// Polyfill missing globals
dom.window.localStorage = { getItem: () => null, setItem: () => {} };
dom.window.alert = console.log;

// Load app_final.js
const appFinal = fs.readFileSync('app_final.js', 'utf8');
const script = dom.window.document.createElement('script');
script.textContent = appFinal;
dom.window.document.body.appendChild(script);

// Load vouchers_returns.js
const vouchersReturns = fs.readFileSync('vouchers_returns.js', 'utf8');
const script2 = dom.window.document.createElement('script');
script2.textContent = vouchersReturns;
dom.window.document.body.appendChild(script2);

// Mock data
dom.window.currentContacts = [{id: 1, name: 'Test Contact'}];
dom.window.currentWarehouses = [{id: 1, name: 'Test Warehouse'}];
dom.window.currentProjects = [{id: 1, name: 'Test Project'}];
dom.window.currentItems = [{id: 1, name: 'Test Item', unit: 'kg'}];
dom.window.currentAccounts = [{id: 1, name: 'خزينة'}];
dom.window.allInvoices = [];
dom.window.currentSalesLines = [];

try {
    console.log("Testing openSalesModal()...");
    dom.window.openSalesModal();
    console.log("openSalesModal() SUCCESS. Modal title:", dom.window.document.getElementById('sales-modal-title').innerText);
} catch (e) {
    console.error("openSalesModal() FAILED:");
    console.error(e);
}

try {
    console.log("Testing openSalesReturnModal()...");
    dom.window.openSalesReturnModal();
    console.log("openSalesReturnModal() SUCCESS.");
} catch (e) {
    console.error("openSalesReturnModal() FAILED:");
    console.error(e);
}

try {
    console.log("Testing openPurchasesModal()...");
    dom.window.openPurchasesModal();
    console.log("openPurchasesModal() SUCCESS.");
} catch (e) {
    console.error("openPurchasesModal() FAILED:");
    console.error(e);
}

try {
    console.log("Testing openPurchasesReturnModal()...");
    dom.window.openPurchasesReturnModal();
    console.log("openPurchasesReturnModal() SUCCESS.");
} catch (e) {
    console.error("openPurchasesReturnModal() FAILED:");
    console.error(e);
}
