const fs = require('fs');

try {
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');

    // In renderItems, we need to add a null check before setting innerHTML for select boxes
    // The typical structure is:
    // const sItem = document.getElementById('sales-returns-item');
    // if (sItem) sItem.innerHTML = options;
    
    // Instead of regex replacing every instance, we can replace the specific crashing lines:
    appFinalJs = appFinalJs.replace(/document\.getElementById\('sales-returns-item'\)\.innerHTML = /g, "const srItem = document.getElementById('sales-returns-item'); if(srItem) srItem.innerHTML = ");
    appFinalJs = appFinalJs.replace(/document\.getElementById\('purchases-returns-item'\)\.innerHTML = /g, "const prItem = document.getElementById('purchases-returns-item'); if(prItem) prItem.innerHTML = ");

    // Also just in case there are other direct innerHTML sets in renderItems
    appFinalJs = appFinalJs.replace(/document\.getElementById\('invoice-item'\)\.innerHTML = /g, "const iItem = document.getElementById('invoice-item'); if(iItem) iItem.innerHTML = ");
    appFinalJs = appFinalJs.replace(/document\.getElementById\('purchases-item'\)\.innerHTML = /g, "const pItem = document.getElementById('purchases-item'); if(pItem) pItem.innerHTML = ");
    
    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');

    // Bust cache
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    const timestamp = Date.now();
    indexHtml = indexHtml.replace(/app_final\.js\?v=\d+/g, 'app_final.js?v=' + timestamp);
    fs.writeFileSync('index.html', indexHtml, 'utf8');

    console.log('Fixed renderItems crash successfully.');
} catch (e) {
    console.error('Error patching renderItems:', e);
}
