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

// The whole block from "window.renderClientAbstracts =" down to "};" before "window.openClientAbstractModal"
// Let's replace the whole window.renderClientAbstracts function to ensure it's 100% correct!

const regex = /window\.renderClientAbstracts = async function\(\) \{[\s\S]*?tbody\.appendChild\(tr\);\s*\}\);\s*\};/g;

const replacement = `window.renderClientAbstracts = async function() {
  currentClientAbstracts = await window.DB.getAll('client_abstracts') || [];
  const tbody = document.getElementById('client-abstracts-tbody');
  if(!tbody) return;
  tbody.innerHTML = '';
  const search = document.getElementById('client-abstract-search').value.toLowerCase();
  const statusFilter = document.getElementById('client-abstract-status-filter').value;
  
  let filtered = currentClientAbstracts.filter(ab => {
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';
    const matchSearch = ab.client_name.toLowerCase().includes(search) || 
                        pName.toLowerCase().includes(search) || 
                        (ab.abstract_number && ab.abstract_number.toLowerCase().includes(search));
    const matchStatus = statusFilter === 'all' || ab.status === statusFilter;
    return matchSearch && matchStatus;
  });
  
  filtered.sort((a,b) => new Date(b.date) - new Date(a.date));
  
  filtered.forEach(ab => {
    const tr = document.createElement('tr');
    const pName = (currentProjects.find(p => p.id == ab.project_id) || {}).name || '';
    
    let paid = 0;
    const linkedVouchers = allInvoices.filter(j => j.type === 'receipt' && j.status === 'posted' && j.linked_invoice_id === 'cab-' + ab.id);
    linkedVouchers.forEach(v => {
        paid += parseFloat(v.amount) || 0;
    });
    
    let actions = \`
      <button class="action-btn btn-view" onclick="printClientAbstract(\${ab.id})">عرض</button>
      \${ab.status === 'draft' ? \`<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="approveClientAbstract(\${ab.id})">اعتماد</button>\` : ''}
      \${ab.status === 'approved' ? \`<button class="action-btn" style="background:var(--success); color:#fff; border:none;" onclick="payClientAbstract(\${ab.id})">سند قبض</button>\` : ''}
      \${ab.status === 'draft' ? \`<button class="action-btn btn-edit" onclick="openClientAbstractModal(\${ab.id})">تعديل</button>\` : ''}
      \${ab.status === 'draft' ? \`<button class="action-btn btn-danger" onclick="deleteClientAbstract(\${ab.id})">حذف</button>\` : ''}
    \`;
    
    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>
    \`;
    tbody.appendChild(tr);
  });
};`;

js = js.replace(regex, replacement);

// Also clean up any loose \nwindow if it exists
js = js.replace(/\\nwindow\.openClientAbstractModal/g, '\nwindow.openClientAbstractModal');
js = js.replace(/\\nwindow\.renderClientAbstracts/g, '\nwindow.renderClientAbstracts');

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Fixed syntax and restored renderClientAbstracts!');
