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

// 1. Add nav-settings to allNavs
if (!c.includes("'nav-settings'")) {
    c = c.replace("'nav-client-abstracts', 'nav-audit-logs']", "'nav-client-abstracts', 'nav-audit-logs', 'nav-settings']");
}

// 2. Add switchView event listener
const switchViewTarget = "if (e.target.dataset.view === 'audit-logs' && typeof window.renderAuditLogs === 'function') window.renderAuditLogs();";
const switchViewInject = "if (e.target.dataset.view === 'settings' && typeof window.renderSettings === 'function') window.renderSettings();\n    ";
if (!c.includes("e.target.dataset.view === 'settings'")) {
    c = c.replace(switchViewTarget, switchViewTarget + "\n    " + switchViewInject);
} else {
    // If it was already injected incorrectly, remove the bad injection
    c = c.replace("if (e.target.dataset.view === 'settings' && typeof window.renderSettings === 'function') window.renderSettings();\n    if (e.target.dataset.view === 'audit-logs'", "if (e.target.dataset.view === 'audit-logs'");
    if (!c.includes("e.target.dataset.view === 'settings'")) {
        c = c.replace(switchViewTarget, switchViewTarget + "\n    " + switchViewInject);
    }
}

// 3. Load currentSettings globally in loadData
const loadDataTarget = "window.currentAuditLogs = ((await window.DB.getAll('activity_logs')) || []).filter(Boolean);";
const loadDataInject = "\n  window.currentSettingsArray = await window.DB.getAll('settings');\n  if(window.currentSettingsArray && window.currentSettingsArray.length > 0) window.currentSettings = window.currentSettingsArray[0];\n  ";
if (!c.includes("window.currentSettingsArray")) {
    c = c.replace(loadDataTarget, loadDataTarget + loadDataInject);
}

fs.writeFileSync('app_final.js', c);
console.log('Successfully patched app_final.js for settings');
