
// Global modal helpers (available immediately)
window.openModal = function(id) {
  const m = document.getElementById(id);
  const b = document.getElementById(id + '-backdrop');
  if (m) m.classList.add('show');
  if (b) b.classList.add('show');
}
window.closeModal = function(id) {
  const m = document.getElementById(id);
  const b = document.getElementById(id + '-backdrop');
  if (m) m.classList.remove('show');
  if (b) b.classList.remove('show');
}

// Sidebar toggle (mobile) + other bindings
document.addEventListener('DOMContentLoaded', () => {
  const toggleBtn = document.getElementById('menuToggle');
  const sidebar = document.getElementById('sidebar');
  const backdrop = document.getElementById('drawerBackdrop');

  function openSidebar() {
    sidebar.classList.remove('-translate-x-full');
    backdrop.classList.add('show');
  }
  function closeSidebar() {
    sidebar.classList.add('-translate-x-full');
    backdrop.classList.remove('show');
  }

  if (toggleBtn) toggleBtn.addEventListener('click', openSidebar);
  if (backdrop) backdrop.addEventListener('click', closeSidebar);

  // Active link highlight
  const path = location.pathname.split('/').pop() || 'index.html';
  document.querySelectorAll('[data-nav]').forEach(a => {
    if (a.getAttribute('href') === path) {
      a.classList.add('link-active');
    }
  });

  // Delegated handlers for [data-open-modal] / [data-close-modal]
  document.addEventListener('click', (e) => {
    const openBtn = e.target.closest('[data-open-modal]');
    if (openBtn) {
      const id = openBtn.getAttribute('data-open-modal');
      if (id) openModal(id);
    }
    const closeBtn = e.target.closest('[data-close-modal]');
    if (closeBtn) {
      const modal = closeBtn.closest('.modal');
      if (modal && modal.id) closeModal(modal.id);
    }
  });

  // Prevent default form submission (no data yet)
  document.querySelectorAll('form').forEach(f => {
    f.addEventListener('submit', (e) => {
      e.preventDefault();
      // Basic "saved" toast
      const toast = document.createElement('div');
      toast.textContent = 'ذخیره شد (نمایشی)';
      toast.className = 'fixed bottom-5 right-5 bg-emerald-600 text-white px-4 py-2 rounded-xl shadow-lg';
      document.body.appendChild(toast);
      setTimeout(() => toast.remove(), 1600);
    });
  });

  // Simple dark mode toggle
  const dToggle = document.getElementById('darkToggle');
  if (dToggle) {
    dToggle.addEventListener('click', () => {
      document.documentElement.classList.toggle('dark');
      localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
    });
    // Load preference
    if (localStorage.theme === 'dark') {
      document.documentElement.classList.add('dark');
    }
  }
});
