const fs = require('fs');

// 1. Update index.html
let html = fs.readFileSync('index.html', 'utf8');

const commentsHTML = (type) => `
      <!-- Comments Section -->
      <div id="${type}-chat-section" style="margin-top: 20px; border-top: 1px solid var(--border); padding-top:15px; display: none;">
        <h4 style="margin-bottom:10px;">إضافة تعليق ومناقشة</h4>
        <div id="${type}-comments-list" style="max-height:150px; overflow-y:auto; margin-bottom:10px; background:rgba(0,0,0,0.1); padding:10px; border-radius:5px;"></div>
        <div style="display:flex; gap:10px; align-items:center; position:relative;">
          <input type="text" id="${type}-new-comment" placeholder="اكتب تعليقاً... استخدم @ لعمل منشن" style="flex:1;" oninput="window.handleMentionInput(this)">
          <div class="mention-dropdown" style="display:none; position:absolute; bottom:100%; right:0; background:white; color:black; border:1px solid #ccc; border-radius:5px; max-height:150px; overflow-y:auto; z-index:1000; min-width:150px; box-shadow:0 0 5px rgba(0,0,0,0.5);"></div>
          <button type="button" class="btn-primary" style="width:auto; padding: 10px 20px;" onclick="window.addAbstractComment('${type}')">إرسال</button>
        </div>
      </div>
`;

// Insert into abstract-modal before modal-actions
if (!html.includes('id="abstract-chat-section"')) {
    html = html.replace(
        '<div class="modal-actions" id="abstract-action-buttons" style="margin-top:20px;">',
        commentsHTML('abstract') + '\n      <div class="modal-actions" id="abstract-action-buttons" style="margin-top:20px;">'
    );
}

// Insert into client-abstract-modal before modal-actions
if (!html.includes('id="client-abstract-chat-section"')) {
    html = html.replace(
        '<div class="modal-actions" id="client-abstract-action-buttons" style="margin-top:20px;">',
        commentsHTML('client-abstract') + '\n      <div class="modal-actions" id="client-abstract-action-buttons" style="margin-top:20px;">'
    );
}

fs.writeFileSync('index.html', html, 'utf8');
console.log('index.html updated successfully.');

// 2. Update app_final.js
let js = fs.readFileSync('app_final.js', 'utf8');

// --- Add abstract comments functions ---
const abstractCommentsJS = `
window.renderAbstractComments = function(type, ab) {
  const section = document.getElementById(type + '-chat-section');
  if(section) section.style.display = ab.id ? 'block' : 'none';
  
  const listId = type + '-comments-list';
  const list = document.getElementById(listId);
  if(!list) return;
  list.innerHTML = '';
  if (!ab.comments || ab.comments.length === 0) {
    list.innerHTML = '<div style="color:var(--text-secondary); text-align:center; font-size:12px;">لا توجد تعليقات بعد.</div>';
    return;
  }
  ab.comments.forEach(c => {
    let text = c.text;
    text = text.replace(/@([\\w\\u0600-\\u06FF]+)/g, '<span style="color:var(--primary); font-weight:bold;">@$1</span>');
    list.innerHTML += \`<div style="margin-bottom:8px; padding-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.05);">
      <strong style="font-size:12px; color:var(--text-secondary);">\${c.user} - \${new Date(c.date).toLocaleString('ar-EG')}</strong>
      <div style="margin-top:4px;">\${text}</div>
    </div>\`;
  });
  list.scrollTop = list.scrollHeight;
};

window.addAbstractComment = async function(type) {
  try {
    const input = document.getElementById(type + '-new-comment');
    const text = input.value.trim();
    if(!text || !window.currentViewingAbstractId) return;
    
    let isClient = type === 'client-abstract';
    let dbTable = isClient ? 'client_abstracts' : 'abstracts';
    let allData = isClient ? allClientAbstracts : allAbstracts;
    
    const abIndex = allData.findIndex(i => i.id === window.currentViewingAbstractId);
    if(abIndex === -1) return;
    
    const ab = allData[abIndex];
    if(!ab.comments) ab.comments = [];
    
    const commentObj = { user: currentUser.username, text: text, date: new Date().toISOString() };
    ab.comments.push(commentObj);
    
    const mentions = text.match(/@([\\w\\u0600-\\u06FF]+)/g);
    if(mentions) {
      for(let m of mentions) {
        const username = m.substring(1);
        const mentionedUser = currentUsers.find(u => u.username === username);
        if(mentionedUser) {
          let notifs = await window.DB.getAll('notifications') || [];
          notifs.push({
            id: Date.now().toString() + Math.random().toString(36).substring(2),
            user: mentionedUser.username,
            text: \`تم عمل منشن لك في مستخلص رقم \${ab.doc_no}\`,
            link: \`#\`,
            date: new Date().toISOString(),
            read: false
          });
          await window.DB.put('notifications', notifs);
        }
      }
    }
    
    await window.DB.put(dbTable, ab);
    input.value = '';
    window.renderAbstractComments(type, ab);
    
    const allNotifications = await window.DB.getAll('notifications') || [];
    const myNotifs = allNotifications.filter(n => n.user === currentUser.username && !n.read);
    if(window.renderNotifications) renderNotifications(myNotifs);
  } catch(e) {
    alert("حدث خطأ أثناء إضافة التعليق: " + e.message);
  }
};
`;

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

// --- Modify openAbstractModal ---
js = js.replace("window.openAbstractModal = function(id = null) {", "window.openAbstractModal = function(id = null) {\\n  window.currentViewingAbstractId = id;");
js = js.replace("document.getElementById('abstract-tax-percent').value = ab.tax_percent || 0;", "document.getElementById('abstract-tax-percent').value = ab.tax_percent || 0;\\n      if(window.renderAbstractComments) window.renderAbstractComments('abstract', ab);");
js = js.replace("document.getElementById('abstract-tax-percent').value = 0;", "document.getElementById('abstract-tax-percent').value = 0;\\n    if(document.getElementById('abstract-chat-section')) document.getElementById('abstract-chat-section').style.display = 'none';");

// --- Modify openClientAbstractModal ---
js = js.replace("window.openClientAbstractModal = function(id = null) {", "window.openClientAbstractModal = function(id = null) {\\n  window.currentViewingAbstractId = id;");
js = js.replace("document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;", "document.getElementById('client-abstract-retention-percent').value = ab.retention_percent || 0;\\n      if(window.renderAbstractComments) window.renderAbstractComments('client-abstract', ab);");
js = js.replace("document.getElementById('client-abstract-taxes-list').innerHTML = '';", "document.getElementById('client-abstract-taxes-list').innerHTML = '';\\n    if(document.getElementById('client-abstract-chat-section')) document.getElementById('client-abstract-chat-section').style.display = 'none';");

// --- Quantity Warnings in calculateAbstractTotals ---
js = js.replace("tr.querySelector('.ca-item-total-val').innerText = tVal.toLocaleString('ar-EG');", `tr.querySelector('.ca-item-total-val').innerText = tVal.toLocaleString('ar-EG');
        if (totalQty > 0 && tQty > totalQty) {
            tr.style.backgroundColor = 'rgba(255, 0, 0, 0.2)';
            let titleElement = tr.querySelector('td:nth-child(2)');
            if(titleElement && !titleElement.innerHTML.includes('تجاوز')) {
                titleElement.innerHTML += '<span style="color: #ff6b6b; font-size: 0.8em; margin-right: 5px; font-weight: bold;">(تجاوز!)</span>';
            }
        } else {
            tr.style.backgroundColor = '';
            let titleElement = tr.querySelector('td:nth-child(2)');
            if(titleElement && titleElement.innerHTML.includes('تجاوز')) {
                titleElement.innerHTML = titleElement.innerHTML.replace(/<span.*>\\(تجاوز!\\)<\\/span>/, '');
            }
        }
`);

fs.writeFileSync('app_final.js', js, 'utf8');
console.log('app_final.js updated successfully.');
