const fs = require('fs');
let c = fs.readFileSync('app_final.js', 'utf8');

// 1. Remove the duplicate window.loadData
c = c.replace(/window\.loadData = async function \(showLoading = true\) \{[\s\S]*?if \(showLoading\) document\.getElementById\('loading-overlay'\)\.style\.display = 'none';\n  \}\n\}/, '');

// 2. Add .filter(Boolean) to all await window.DB.getAll in the original loadData
c = c.replace(/currentItems = await window\.DB\.getAll\('items'\);/g, "currentItems = ((await window.DB.getAll('items')) || []).filter(Boolean);");
c = c.replace(/currentProjects = await window\.DB\.getAll\('projects'\);/g, "currentProjects = ((await window.DB.getAll('projects')) || []).filter(Boolean);");
c = c.replace(/currentWarehouses = await window\.DB\.getAll\('warehouses'\);/g, "currentWarehouses = ((await window.DB.getAll('warehouses')) || []).filter(Boolean);");
c = c.replace(/currentUsers = await window\.DB\.getAll\('users'\);/g, "currentUsers = ((await window.DB.getAll('users')) || []).filter(Boolean);");
c = c.replace(/currentContacts = await window\.DB\.getAll\('contacts'\) \|\| \[\];/g, "currentContacts = ((await window.DB.getAll('contacts')) || []).filter(Boolean);");
c = c.replace(/currentUnits = await window\.DB\.getAll\('units'\) \|\| \[\];/g, "currentUnits = ((await window.DB.getAll('units')) || []).filter(Boolean);");
c = c.replace(/allInvoices = await window\.DB\.getAll\('transactions'\);/g, "allInvoices = ((await window.DB.getAll('transactions')) || []).filter(Boolean);");
c = c.replace(/allNotifications = await window\.DB\.getAll\('notifications'\) \|\| \[\];/g, "allNotifications = ((await window.DB.getAll('notifications')) || []).filter(Boolean);");
c = c.replace(/currentClientAbstracts = await window\.DB\.getAll\('client_abstracts'\) \|\| \[\];/g, "currentClientAbstracts = ((await window.DB.getAll('client_abstracts')) || []).filter(Boolean);");
c = c.replace(/currentAccounts = await window\.DB\.getAll\('accounts'\) \|\| \[\];/g, "currentAccounts = ((await window.DB.getAll('accounts')) || []).filter(Boolean);");

// 3. Add activity_logs fetch if it doesn't exist
if (!c.includes('window.currentAuditLogs =')) {
  c = c.replace(/(allNotifications = .*\n)/, "$1  window.currentAuditLogs = ((await window.DB.getAll('activity_logs')) || []).filter(Boolean);\n");
}

// 4. Add renderAuditLogs() if it doesn't exist in loadData
if (!c.includes('renderAuditLogs();') && c.includes('renderDashboard();')) {
  c = c.replace(/(renderDashboard\(\);\n)/, "$1  if (typeof renderAuditLogs === 'function') renderAuditLogs();\n");
}

fs.writeFileSync('app_final.js', c);
console.log('Fixed loadData!');
