// ============================================================
// نظام إدارة القضايا القضائية - Main JavaScript
// ============================================================

document.addEventListener('DOMContentLoaded', function () {
  // Initialize Feather Icons
  if (typeof feather !== 'undefined') feather.replace();

  // Auto-dismiss alerts
  document.querySelectorAll('.alert[data-auto-dismiss]').forEach(function (el) {
    setTimeout(function () {
      el.style.opacity = '0';
      el.style.transform = 'translateY(-8px)';
      el.style.transition = 'all .4s';
      setTimeout(function () { el.remove(); }, 400);
    }, 4000);
  });

  // Decision radio options (جلسة)
  document.querySelectorAll('.decision-opt').forEach(function (opt) {
    opt.addEventListener('click', function () {
      document.querySelectorAll('.decision-opt').forEach(o => o.classList.remove('selected'));
      opt.classList.add('selected');
      const radio = opt.querySelector('input[type=radio]');
      if (radio) radio.checked = true;
      // Show/hide related fields
      const val = radio ? radio.value : '';
      toggleDecisionFields(val);
    });
  });

  // Sidebar mobile toggle
  const sidebarToggle = document.getElementById('sidebarToggle');
  if (sidebarToggle) {
    sidebarToggle.addEventListener('click', function () {
      document.getElementById('sidebar').classList.toggle('open');
    });
  }

  // Upload zone drag & drop
  document.querySelectorAll('.upload-zone').forEach(initUploadZone);

  // Modal close on overlay click
  document.querySelectorAll('.modal-overlay').forEach(function (overlay) {
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay) overlay.classList.remove('open');
    });
  });

  // Initialize tooltips (custom simple)
  initTooltips();

  // Confirm delete buttons
  document.querySelectorAll('[data-confirm]').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      if (!confirm(btn.dataset.confirm || 'هل أنت متأكد؟')) e.preventDefault();
    });
  });
});

// ============================================================
// NOTIFICATIONS
// ============================================================
function toggleNotifications(e) {
  e.preventDefault();
  const panel = document.getElementById('notifPanel');
  const overlay = document.getElementById('notifOverlay');
  const isOpen = panel.classList.contains('open');
  if (!isOpen) {
    panel.classList.add('open');
    overlay.classList.add('open');
    loadNotifications();
  } else {
    closeNotifications();
  }
}

function closeNotifications() {
  document.getElementById('notifPanel')?.classList.remove('open');
  document.getElementById('notifOverlay')?.classList.remove('open');
}

async function loadNotifications() {
  const list = document.getElementById('notifList');
  if (!list) return;
  list.innerHTML = '<div class="notif-loading">جارٍ التحميل...</div>';
  try {
    const res = await fetch(BASE_URL + 'api/notifications.php?action=list&limit=20');
    const data = await res.json();
    if (!data.success || !data.notifications.length) {
      list.innerHTML = '<div class="notif-empty">لا توجد إشعارات</div>';
      return;
    }
    list.innerHTML = data.notifications.map(n => `
      <div class="notif-item ${n.is_read == 0 ? 'unread' : ''}" onclick="markRead(${n.id}, this)">
        <div class="notif-item-title">${escHtml(n.title)}</div>
        <div class="notif-item-msg">${escHtml(n.message)}</div>
        <div class="notif-item-time">${n.created_at}</div>
      </div>
    `).join('');
  } catch {
    list.innerHTML = '<div class="notif-empty">تعذر تحميل الإشعارات</div>';
  }
}

async function markRead(id, el) {
  el.classList.remove('unread');
  await fetch(BASE_URL + 'api/notifications.php?action=mark_read', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id })
  });
  updateBadge();
}

async function markAllRead() {
  await fetch(BASE_URL + 'api/notifications.php?action=mark_all_read', { method: 'POST' });
  document.querySelectorAll('.notif-item.unread').forEach(el => el.classList.remove('unread'));
  const badge = document.querySelector('.notif-badge');
  if (badge) badge.remove();
}

async function updateBadge() {
  try {
    const res = await fetch(BASE_URL + 'api/notifications.php?action=count');
    const d = await res.json();
    const badge = document.querySelector('.notif-badge');
    if (d.count > 0) {
      if (badge) badge.textContent = d.count;
    } else {
      if (badge) badge.remove();
    }
  } catch {}
}

// Poll for new notifications every 60s
setInterval(async function () {
  if (typeof BASE_URL !== 'undefined') {
    try {
      const res = await fetch(BASE_URL + 'api/notifications.php?action=count');
      const d = await res.json();
      const badge = document.querySelector('.notif-badge');
      if (d.count > 0) {
        if (badge) badge.textContent = d.count;
        else {
          const btn = document.getElementById('notifBtn');
          if (btn) {
            const b = document.createElement('span');
            b.className = 'notif-badge';
            b.textContent = d.count;
            btn.appendChild(b);
          }
        }
      }
    } catch {}
  }
}, 60000);

// ============================================================
// DECISION FIELDS TOGGLE
// ============================================================
function toggleDecisionFields(val) {
  const postponeFields = document.getElementById('postponeFields');
  const verdictFields = document.getElementById('verdictFields');
  if (postponeFields) postponeFields.style.display = (val === 'postponed') ? 'block' : 'none';
  if (verdictFields) verdictFields.style.display = (val === 'verdict') ? 'block' : 'none';
}

// ============================================================
// UPLOAD ZONE
// ============================================================
function initUploadZone(zone) {
  zone.addEventListener('dragover', function (e) {
    e.preventDefault();
    zone.classList.add('dragover');
  });
  zone.addEventListener('dragleave', function () {
    zone.classList.remove('dragover');
  });
  zone.addEventListener('drop', function (e) {
    e.preventDefault();
    zone.classList.remove('dragover');
    const input = zone.querySelector('input[type=file]');
    if (input && e.dataTransfer.files.length) {
      input.files = e.dataTransfer.files;
      updateFileName(zone, e.dataTransfer.files[0].name);
    }
  });
  const input = zone.querySelector('input[type=file]');
  if (input) {
    input.addEventListener('change', function () {
      if (input.files.length) updateFileName(zone, input.files[0].name);
    });
  }
}

function updateFileName(zone, name) {
  const label = zone.querySelector('p');
  if (label) label.innerHTML = `<strong>${escHtml(name)}</strong> — تم اختيار الملف`;
}

// ============================================================
// MODALS
// ============================================================
function openModal(id) {
  document.getElementById(id)?.classList.add('open');
}
function closeModal(id) {
  document.getElementById(id)?.classList.remove('open');
}

// ============================================================
// TOOLTIPS
// ============================================================
function initTooltips() {
  document.querySelectorAll('[data-tip]').forEach(function (el) {
    el.addEventListener('mouseenter', function () {
      const tip = document.createElement('div');
      tip.className = 'tooltip-bubble';
      tip.textContent = el.dataset.tip;
      tip.style.cssText = 'position:fixed;background:#1B3668;color:#fff;padding:5px 10px;border-radius:6px;font-size:.75rem;z-index:999;pointer-events:none;';
      document.body.appendChild(tip);
      const rect = el.getBoundingClientRect();
      tip.style.top = (rect.top - tip.offsetHeight - 8) + 'px';
      tip.style.right = (window.innerWidth - rect.right) + 'px';
      el._tooltip = tip;
    });
    el.addEventListener('mouseleave', function () {
      if (el._tooltip) { el._tooltip.remove(); el._tooltip = null; }
    });
  });
}

// ============================================================
// UTILITIES
// ============================================================
function escHtml(str) {
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function showToast(message, type = 'success') {
  const toast = document.createElement('div');
  toast.className = `alert alert-${type} fade-in`;
  toast.style.cssText = 'position:fixed;top:20px;left:20px;z-index:9999;max-width:320px;box-shadow:0 4px 20px rgba(0,0,0,.2)';
  toast.innerHTML = message;
  document.body.appendChild(toast);
  setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity .4s'; }, 3500);
  setTimeout(() => toast.remove(), 4000);
}

function formatDate(d) {
  if (!d) return '—';
  const date = new Date(d);
  // ✅ FIX: 'ar-DZ-u-nu-latn' forces Western (Latin) numerals instead of Arabic-Indic
  return date.toLocaleDateString('ar-DZ-u-nu-latn', { year: 'numeric', month: 'long', day: 'numeric' });
}

// Export table to CSV
function exportTableCSV(tableId, filename) {
  const table = document.getElementById(tableId);
  if (!table) return;
  let csv = [];
  table.querySelectorAll('tr').forEach(row => {
    const cells = row.querySelectorAll('th, td');
    csv.push([...cells].map(c => '"' + c.innerText.trim().replace(/"/g, '""') + '"').join(','));
  });
  const blob = new Blob(['\uFEFF' + csv.join('\n')], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = filename + '.csv';
  a.click(); URL.revokeObjectURL(url);
}