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

const targetStringStart = `let paidText = paid > 0 ? \`<div style="font-size:0.85em; color:var(--primary); margin-top:5px;">المحصل: \${paid.toLocaleString('ar-EG')}</div>\` : '';`;

const replacementString = `let remaining = Math.max(0, (parseFloat(ab.net_value) || 0) - paid);
    
    tr.innerHTML = \`
      <td>\${ab.abstract_number || ('#' + ab.id)}</td>
      <td>\${new Date(ab.date).toLocaleDateString('ar-EG')}</td>
      <td>\${pName}</td>
      <td>\${ab.client_name || ''}</td>
      <td style="font-weight:bold; color:var(--success);">\${(parseFloat(ab.net_value) || 0).toLocaleString('ar-EG')} ج.م</td>
      <td style="color:var(--primary); font-weight:bold;">\${paid.toLocaleString('ar-EG')} ج.م</td>
      <td style="color:var(--danger); font-weight:bold;">\${remaining.toLocaleString('ar-EG')} ج.م</td>
      <td><span class="status-badge \${ab.status==='approved'?'status-posted':'status-draft'}">\${ab.status==='approved'?'معتمد':'مسودة'}</span></td>
      <td>\${actions}</td>
    \`;`;

// Find start and end using indices
const startIdx = js.indexOf(targetStringStart);
if (startIdx !== -1) {
    // Find the end of the tr.innerHTML block
    const endStr = "<td>${actions}</td>";
    const endIdxStr = js.indexOf(endStr, startIdx);
    
    if (endIdxStr !== -1) {
        // Find the closing backtick and semicolon after endStr
        const finalEndStr = "`;";
        const finalEndIdx = js.indexOf(finalEndStr, endIdxStr) + finalEndStr.length;
        
        const pre = js.substring(0, startIdx);
        const post = js.substring(finalEndIdx);
        
        fs.writeFileSync('app_final.js', pre + replacementString + post, 'utf8');
        console.log('Fixed table columns robustly!');
    } else {
        console.log('Could not find endStr');
    }
} else {
    console.log('Could not find targetStringStart');
}
