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

// Find start and end of the broken renderClientAbstracts and openClientAbstractModal block
// The block starts around window.renderClientAbstracts = and ends before window.deleteClientAbstract

const startStr = "window.renderClientAbstracts =";
const endStr = "window.deleteClientAbstract = async function(id)";

const startIndex = js.indexOf(startStr);
let endIndex = js.indexOf(endStr);
if (startIndex !== -1 && endIndex !== -1) {
    let pre = js.substring(0, startIndex);
    let post = js.substring(endIndex);

    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);
  });
};

window.openClientAbstractModal = function(id = null) {
  window.currentViewingAbstractId = id;
  document.getElementById('client-abstract-modal-title').innerText = id ? 'تعديل مستخلص عميل #' + id : 'مستخلص عميل جديد';
  document.getElementById('edit-client-abstract-id').value = id || '';
  
  const pSel = document.getElementById('client-abstract-project');
  pSel.innerHTML = '<option value="">اختر المشروع...</option>' + currentProjects.map(p => \`<option value="\${p.id}">\${p.name}</option>\`).join('');
  
  if (id) {
      const ab = currentClientAbstracts.find(a => a.id === id);
      if (ab) {
          pSel.value = ab.project_id;
          document.getElementById('client-abstract-date').value = ab.date;
          document.getElementById('client-abstract-name').value = ab.client_name || '';
          document.getElementById('client-abstract-notes').value = ab.notes || '';
          document.getElementById('client-abstract-previous-value').value = ab.previous_value || 0;
          document.getElementById('client-abstract-current-value').value = ab.current_value || 0;
          document.getElementById('client-abstract-total-value').value = ab.total_value || 0;
          document.getElementById('client-abstract-deduction-percent').value = ab.deduction_percent || 0;
          document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;
          if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', ab);
      }
  } else {
      document.getElementById('client-abstract-form').reset();
      document.getElementById('client-abstract-date').value = new Date().toISOString().split('T')[0];
      const nextId = (currentClientAbstracts.length > 0 ? Math.max(...currentClientAbstracts.map(a=>a.id)) : 0) + 1;
      document.getElementById('client-abstract-number').value = 'CAB-' + nextId;
      if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', {id:null});
  }
  
  showModal('client-abstract-modal');
};

`;

    js = pre + replacement + post;
    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Fixed renderClientAbstracts and openClientAbstractModal perfectly!');
} else {
    console.log('Could not find start/end bounds!');
}
