/**
 * Helmyx Main JavaScript
 */

document.addEventListener('DOMContentLoaded', () => {

  // === SIDEBAR TOGGLE ===
  const sidebar = document.getElementById('sidebar');
  const sidebarToggle = document.getElementById('sidebarToggle');
  const mainWrapper = document.getElementById('mainWrapper');

  if (sidebarToggle && sidebar) {
    sidebarToggle.addEventListener('click', () => {
      if (window.innerWidth <= 768) {
        sidebar.classList.toggle('mobile-open');
      } else {
        sidebar.classList.toggle('collapsed');
        localStorage.setItem('sidebar_collapsed', sidebar.classList.contains('collapsed'));
      }
    });

    // Restore state
    if (window.innerWidth > 768 && localStorage.getItem('sidebar_collapsed') === 'true') {
      sidebar.classList.add('collapsed');
    }
  }

  // === DROPDOWN MENUS ===
  document.addEventListener('click', (e) => {
    // Close all dropdowns if clicked outside
    if (!e.target.closest('[data-dropdown]')) {
      document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
        menu.classList.remove('show');
      });
    }
  });

  const dropdownToggles = document.querySelectorAll('[data-dropdown]');
  dropdownToggles.forEach(toggle => {
    toggle.addEventListener('click', (e) => {
      e.stopPropagation();
      const targetId = toggle.getAttribute('data-dropdown');
      const targetMenu = document.getElementById(targetId);
      
      // Close others
      document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
        if (menu !== targetMenu) menu.classList.remove('show');
      });

      if (targetMenu) {
        targetMenu.classList.toggle('show');
      }
    });
  });

  // === ACTIVE NAV DETECTION ===
  const currentPath = window.location.pathname;
  const navItems = document.querySelectorAll('.nav-item');
  navItems.forEach(item => {
    if (item.getAttribute('href') && currentPath.includes(item.getAttribute('href'))) {
      item.classList.add('active');
    }
  });

  // === FLASH MESSAGE AUTO-DISMISS ===
  const alerts = document.querySelectorAll('.alert');
  alerts.forEach(alert => {
    const dismissBtn = alert.querySelector('.alert-dismiss');
    if (dismissBtn) {
      dismissBtn.addEventListener('click', () => {
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 300);
      });
    }
    // Auto dismiss after 5s
    setTimeout(() => {
      if (alert.parentNode) {
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 300);
      }
    }, 5000);
  });

  // === TABS ===
  const tabItems = document.querySelectorAll('.tab-item');
  tabItems.forEach(tab => {
    tab.addEventListener('click', () => {
      const target = document.querySelector(tab.dataset.target);
      const parent = tab.closest('.tabs');
      const contents = target.parentElement.querySelectorAll('.tab-content');
      
      parent.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
      contents.forEach(c => c.classList.remove('active'));

      tab.classList.add('active');
      target.classList.add('active');
    });
  });

  // === TABLE SEARCH ===
  const tableSearch = document.querySelector('.table-search');
  if (tableSearch) {
    tableSearch.addEventListener('input', (e) => {
      const term = e.target.value.toLowerCase();
      const targetTable = document.querySelector(tableSearch.dataset.target || '.table');
      if (targetTable) {
        const rows = targetTable.querySelectorAll('tbody tr');
        rows.forEach(row => {
          const text = row.textContent.toLowerCase();
          row.style.display = text.includes(term) ? '' : 'none';
        });
      }
    });
  }
});

// === TOAST NOTIFICATIONS ===
window.showToast = function(message, type = 'success', duration = 5000) {
  const container = document.getElementById('toastContainer');
  if (!container) return;

  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  
  let icon = 'check-circle';
  if(type === 'error') icon = 'exclamation-circle';
  if(type === 'warning') icon = 'exclamation-triangle';
  if(type === 'info') icon = 'info-circle';

  toast.innerHTML = `
    <i class="fas fa-${icon} text-${type}" style="font-size: 1.25rem;"></i>
    <div style="flex:1; font-size: 0.875rem; font-weight: 500;">${message}</div>
    <button class="alert-dismiss" onclick="this.parentElement.classList.add('removing'); setTimeout(() => this.parentElement.remove(), 300);"><i class="fas fa-times"></i></button>
  `;

  container.appendChild(toast);

  setTimeout(() => {
    if (toast.parentNode) {
      toast.classList.add('removing');
      setTimeout(() => toast.remove(), 300);
    }
  }, duration);
};

// === MODAL SYSTEM ===
window.openModal = function(modalId) {
  const overlay = document.getElementById(modalId);
  if (overlay) {
    overlay.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }
};

window.closeModal = function(modalId) {
  const overlay = document.getElementById(modalId);
  if (overlay) {
    overlay.classList.add('hidden');
    document.body.style.overflow = '';
  }
};

window.closeAllModals = function() {
  document.querySelectorAll('.modal-overlay').forEach(overlay => {
    overlay.classList.add('hidden');
  });
  document.body.style.overflow = '';
};

// Close modal on overlay click
document.addEventListener('click', (e) => {
  if (e.target.classList.contains('modal-overlay')) {
    closeAllModals();
  }
});
// Close on ESC
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') closeAllModals();
});

// === CONFIRM DIALOG ===
window.confirmAction = function(message, callback) {
  const modal = document.getElementById('confirm-modal');
  if (!modal) return;
  
  document.getElementById('confirm-message').textContent = message;
  
  const confirmBtn = document.getElementById('confirm-btn-yes');
  
  // Clone to remove old listeners
  const newConfirmBtn = confirmBtn.cloneNode(true);
  confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
  
  newConfirmBtn.addEventListener('click', () => {
    closeModal('confirm-modal');
    if (typeof callback === 'function') callback();
  });
  
  openModal('confirm-modal');
};

// === CHART.JS DEFAULTS ===
if (window.Chart) {
  Chart.defaults.font.family = "'Inter', sans-serif";
  Chart.defaults.color = "#64748B";
  Chart.defaults.scale.grid.color = "#E2E8F0";
}

window.formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

window.formatCurrency = (amount, currency = 'USD') => {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: currency }).format(amount);
};
