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

// Fix syntax error
js = js.replace('\\nwindow.renderClientAbstracts = async function() {', 'window.renderClientAbstracts = async function() {');

// Inject addClientAbstractTaxRow
const jsAddTaxFunc = `
window.addClientAbstractTaxRow = function(name = '', pct = 0, isRefundable = 'false', val = 0) {
    const list = document.getElementById('client-abstract-taxes-list');
    if (!list) return;
    const div = document.createElement('div');
    div.className = 'tax-row flex-row';
    div.style.gap = '5px';
    div.style.marginBottom = '5px';
    div.style.alignItems = 'center';
    
    div.innerHTML = \`
        <input type="text" class="tax-name" placeholder="بيان الضريبة" value="\${name}" style="flex: 2; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px;">
        <div style="display: flex; align-items: center; gap: 2px; flex: 1;">
            <input type="number" class="tax-pct" value="\${pct}" oninput="window.calcClientAbstractTotals()" style="width: 100%; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px; text-align: center;">
            <span>%</span>
        </div>
        <select class="tax-refundable" style="flex: 1.5; padding: 5px; background: #222; color: #fff; border: 1px solid #555; border-radius: 4px;">
            <option value="false" \${isRefundable === 'false' ? 'selected' : ''}>غير مستردة</option>
            <option value="true" \${isRefundable === 'true' ? 'selected' : ''}>مستردة</option>
        </select>
        <span class="tax-value" style="flex: 1; text-align: center; color: #ff6b6b; font-weight: bold;">\${val.toLocaleString('ar-EG')}</span>
        <button class="btn-danger" style="padding: 2px 8px; border-radius: 4px;" onclick="this.parentElement.remove(); window.calcClientAbstractTotals()">x</button>
    \`;
    list.appendChild(div);
};
`;

if (!js.includes('window.addClientAbstractTaxRow = function(')) {
    js = js.replace('window.renderClientAbstracts = async function() {', jsAddTaxFunc + '\nwindow.renderClientAbstracts = async function() {');
}

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('Fixed syntax and injected addClientAbstractTaxRow');
