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

const html = fs.readFileSync('index.html', 'utf8');
const dbJs = fs.readFileSync('db.js', 'utf8');
const appFinalJs = fs.readFileSync('app_final.js', 'utf8');
const vouchersReturnsJs = fs.readFileSync('vouchers_returns.js', 'utf8');

const virtualConsole = new jsdom.VirtualConsole();

const dom = new JSDOM(html, {
  url: "http://localhost/",
  runScripts: "dangerously",
  virtualConsole
});

dom.window.matchMedia = dom.window.matchMedia || function() {
    return { matches: false, addListener: function() {}, removeListener: function() {} };
};

const scriptDB = dom.window.document.createElement('script');
scriptDB.textContent = dbJs;
dom.window.document.body.appendChild(scriptDB);

const scriptApp = dom.window.document.createElement('script');
scriptApp.textContent = appFinalJs;
dom.window.document.body.appendChild(scriptApp);

const scriptVR = dom.window.document.createElement('script');
scriptVR.textContent = vouchersReturnsJs;
dom.window.document.body.appendChild(scriptVR);

setTimeout(() => {
  try {
      console.log("Calling openSalesReturnModal()...");
      dom.window.openSalesReturnModal();
      console.log("SUCCESS!");
  } catch (e) {
      console.error("CRASHED:", e);
  }
}, 500);
