document.addEventListener('DOMContentLoaded', () => {
  const sidebar = document.getElementById('sidebar');
  const overlay = document.querySelector('.menu-overlay');
  const openMenu = () => { sidebar?.classList.add('open'); overlay?.classList.add('open'); };
  const closeMenu = () => { sidebar?.classList.remove('open'); overlay?.classList.remove('open'); };
  document.querySelectorAll('[data-open-menu]').forEach((button) => button.addEventListener('click', openMenu));
  document.querySelectorAll('[data-close-menu]').forEach((button) => button.addEventListener('click', closeMenu));

  const detail = document.getElementById('accountDetail');
  document.querySelectorAll('[data-account]').forEach((button) => {
    button.addEventListener('click', () => {
      document.querySelectorAll('.account-row.selected').forEach((row) => row.classList.remove('selected'));
      button.classList.add('selected');
      const account = JSON.parse(button.dataset.account || '{}');
      const labels = {asset:'أصول',liability:'التزامات',equity:'حقوق ملكية',revenue:'إيرادات',expense:'مصروفات',debit:'مدين',credit:'دائن'};
      if (detail) detail.innerHTML = `
        <p class="eyebrow">الحساب المحدد</p><h2>${escapeHtml(account.name_ar)}</h2><code>${escapeHtml(account.code)}</code>
        <div class="detail-grid"><div><span>نوع الحساب</span><strong>${labels[account.account_type] || account.account_type}</strong></div><div><span>طبيعة الرصيد</span><strong>${labels[account.normal_balance] || account.normal_balance}</strong></div><div><span>المستوى</span><strong>${account.level}</strong></div><div><span>السماح بالترحيل</span><strong>${Number(account.is_posting) ? 'نعم' : 'حساب تجميعي'}</strong></div></div>
        <div class="dimension-tags"><span class="${Number(account.requires_project)?'on':''}">المشروع</span><span class="${Number(account.requires_cost_code)?'on':''}">كود التكلفة</span><span class="${Number(account.requires_partner)?'on':''}">الطرف المساعد</span></div>`;
    });
  });
});

function escapeHtml(value) {
  const element = document.createElement('div');
  element.textContent = String(value ?? '');
  return element.innerHTML;
}
