// ===== MAIN APPLICATION JS =====

document.addEventListener('DOMContentLoaded', function() {

  // ============================================
  // 1. THEME MANAGEMENT
  // ============================================
  
  /**
   * Apply theme based on saved preference or system preference
   */
  function applyTheme(theme) {
    const isDark = theme === 'dark';
    document.body.classList.toggle('dark-theme', isDark);
    localStorage.setItem('theme', theme);
    
    // Update all theme icons
    updateThemeIcons(isDark);
  }
  
  /**
   * Update all theme toggle icons
   */
  function updateThemeIcons(isDark) {
    const toggles = document.querySelectorAll('#themeToggle, #themeToggleLogin');
    toggles.forEach(toggle => {
      const icon = toggle.querySelector('i');
      if (icon) {
        if (isDark) {
          icon.classList.remove('fa-moon');
          icon.classList.add('fa-sun');
        } else {
          icon.classList.remove('fa-sun');
          icon.classList.add('fa-moon');
        }
      }
    });
  }
  
  /**
   * Toggle theme
   */
  function toggleTheme() {
    const isDark = document.body.classList.contains('dark-theme');
    applyTheme(isDark ? 'light' : 'dark');
  }
  
  // Check for saved theme preference
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme) {
    applyTheme(savedTheme);
  } else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    applyTheme('dark');
  } else {
    applyTheme('light');
  }
  
  // Login page theme toggle
  const loginToggle = document.getElementById('themeToggleLogin');
  if (loginToggle) {
    loginToggle.addEventListener('click', function(e) {
      e.preventDefault();
      toggleTheme();
    });
  }
  
  // Main theme toggle
  const themeToggle = document.getElementById('themeToggle');
  if (themeToggle) {
    themeToggle.addEventListener('click', function(e) {
      e.preventDefault();
      toggleTheme();
    });
  }
  
  // Listen for system theme changes
  if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
      if (!localStorage.getItem('theme')) {
        applyTheme(e.matches ? 'dark' : 'light');
      }
    });
  }

  // ============================================
  // 2. PROFILE DROPDOWN
  // ============================================
  
  const profileBtn = document.getElementById('profileBtn');
  const profileDropdown = document.getElementById('profileDropdown');
  
  if (profileBtn && profileDropdown) {
    profileBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      profileDropdown.classList.toggle('show');
    });
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
      if (!profileBtn.contains(e.target) && !profileDropdown.contains(e.target)) {
        profileDropdown.classList.remove('show');
      }
    });
  }

  // ============================================
  // 3. MODAL HANDLING
  // ============================================
  
  const modal = document.getElementById('demoModal');
  if (modal) {
    // Close on backdrop click
    modal.addEventListener('click', function(e) {
      if (e.target === this) {
        this.classList.remove('show');
      }
    });
    
    // Close on Escape key
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape' && modal.classList.contains('show')) {
        modal.classList.remove('show');
      }
    });
  }
  
  // Trigger modal on terminated badges
  document.querySelectorAll('.status-badge.terminated').forEach(el => {
    el.addEventListener('click', function() {
      if (modal) {
        modal.classList.add('show');
      }
    });
  });

  // ============================================
  // 4. TOAST NOTIFICATIONS
  // ============================================
  
  // Auto-dismiss toasts
  const toasts = document.querySelectorAll('.toast');
  setTimeout(() => {
    toasts.forEach((t, index) => {
      setTimeout(() => {
        if (t.parentNode) {
          t.style.opacity = '0';
          t.style.transform = 'translateX(20px)';
          setTimeout(() => {
            if (t.parentNode) t.remove();
          }, 300);
        }
      }, index * 500 + 3000);
    });
  }, 1000);

  // ============================================
  // 5. BULK SELECTION
  // ============================================
  
  const selectAll = document.querySelector('thead input[type="checkbox"]');
  if (selectAll) {
    selectAll.addEventListener('change', function() {
      const checkboxes = document.querySelectorAll('tbody input[type="checkbox"]');
      checkboxes.forEach(cb => cb.checked = this.checked);
      updateBulkBar();
    });
  }
  
  const rowCheckboxes = document.querySelectorAll('tbody input[type="checkbox"]');
  rowCheckboxes.forEach(cb => {
    cb.addEventListener('change', updateBulkBar);
  });
  
  function updateBulkBar() {
    const checked = document.querySelectorAll('tbody input[type="checkbox"]:checked');
    const bulkBar = document.getElementById('bulkBar');
    if (bulkBar) {
      if (checked.length > 0) {
        bulkBar.classList.add('show');
        const countSpan = bulkBar.querySelector('.caption');
        if (countSpan) {
          countSpan.textContent = checked.length + ' selected';
        }
      } else {
        bulkBar.classList.remove('show');
      }
    }
  }

  // ============================================
  // 6. SEARCH WITH DEBOUNCE
  // ============================================
  
  const searchInput = document.querySelector('.search input');
  if (searchInput) {
    let debounceTimer;
    searchInput.addEventListener('input', function() {
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(() => {
        const searchValue = this.value.trim();
        console.log('Searching for:', searchValue);
        // Trigger AJAX search here
        if (typeof window.searchData === 'function') {
          window.searchData(searchValue);
        }
      }, 300);
    });
  }

  // ============================================
  // 7. SIDEBAR TOGGLE (Mobile)
  // ============================================
  
  const sidebarToggle = document.getElementById('sidebarToggle');
  const sidebar = document.querySelector('.sidebar');
  const mainContent = document.querySelector('.main-content');
  
  if (sidebarToggle && sidebar) {
    sidebarToggle.addEventListener('click', function() {
      sidebar.classList.toggle('collapsed');
      if (mainContent) {
        mainContent.classList.toggle('expanded');
      }
    });
  }

  // ============================================
  // 8. RESPONSIVE TABLE SCROLL
  // ============================================
  
  const tableWrappers = document.querySelectorAll('.table-responsive');
  tableWrappers.forEach(wrapper => {
    // Add scroll indicators if needed
    if (wrapper.scrollWidth > wrapper.clientWidth) {
      wrapper.classList.add('scrollable');
    }
  });

  // ============================================
  // 9. TOOLTIPS (Simple)
  // ============================================
  
  document.querySelectorAll('[data-tooltip]').forEach(el => {
    el.addEventListener('mouseenter', function(e) {
      const tooltip = document.createElement('div');
      tooltip.className = 'tooltip';
      tooltip.textContent = this.dataset.tooltip;
      tooltip.style.cssText = `
        position: absolute;
        background: #1e293b;
        color: #f8fafc;
        padding: 6px 12px;
        border-radius: 6px;
        font-size: 12px;
        z-index: 1000;
        pointer-events: none;
        white-space: nowrap;
        transform: translateY(-100%);
        margin-top: -8px;
      `;
      
      const rect = this.getBoundingClientRect();
      tooltip.style.left = rect.left + rect.width/2 - tooltip.offsetWidth/2 + 'px';
      tooltip.style.top = rect.top + 'px';
      
      document.body.appendChild(tooltip);
      this._tooltip = tooltip;
    });
    
    el.addEventListener('mouseleave', function() {
      if (this._tooltip && this._tooltip.parentNode) {
        this._tooltip.remove();
        this._tooltip = null;
      }
    });
  });

}); // End DOMContentLoaded

// ============================================
// GLOBAL FUNCTIONS (Available everywhere)
// ============================================

/**
 * Show toast notification
 * @param {string} message - The message to display
 * @param {string} type - info, success, error, warning
 * @param {number} timeout - Duration in milliseconds
 */
function showToast(message, type = 'info', timeout_duration = 3500) {
  if (timeout_duration <= 0) timeout_duration = 3500;
  
  type = String(type).trim().toLowerCase();
  
  // Create container if it doesn't exist
  let container = document.getElementById('toastContainer');
  if (!container) {
    container = document.createElement('div');
    container.id = 'toastContainer';
    container.style.cssText = `
      position: fixed;
      bottom: 24px;
      right: 24px;
      z-index: 999999;
      display: flex;
      flex-direction: column;
      gap: 10px;
      max-width: 400px;
      width: 100%;
      pointer-events: none;
    `;
    document.body.appendChild(container);
  }
  
 
const toastTypes = {
  info: {
    color: '#3b82f6',
    background: '#0f172a',
    border: '#3b82f640',
    icon: `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12.01" y2="16"/>
      </svg>
    `
  },
  success: {
    color: '#22c55e',
    background: '#052e16',
    border: '#22c55e40',
    icon: `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
    `
  },
  error: {
    color: '#ef4444',
    background: '#450a0a',
    border: '#ef444440',
    icon: `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="12" cy="12" r="10"/>
        <line x1="15" y1="9" x2="9" y2="15"/>
        <line x1="9" y1="9" x2="15" y2="15"/>
      </svg>
    `
  },
  warning: {
    color: '#f59e0b',
    background: '#451a03',
    border: '#f59e0b40',
    icon: `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
        <line x1="12" y1="9" x2="12" y2="13"/>
        <line x1="12" y1="17" x2="12.01" y2="17"/>
      </svg>
    `
  },
  danger: {
    color: '#f43f5e',      // A vibrant rose/crimson red for the icon & accent border to pop
    background: '#4c0519', // A beautiful ultra-dark rose wine background
    border: '#f43f5e40',     // 25% transparent matching border to fit the design system
    icon: `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
        <line x1="12" y1="9" x2="12" y2="13"/>
        <line x1="12" y1="17" x2="12.01" y2="17"/>
      </svg>
    `
  }
};


  // Fallback for unknown type
  if (!toastTypes[type]) {
    type = 'info';
  }
  
  const toastData = toastTypes[type];
  
  // Create toast element
  const toast = document.createElement('div');
  toast.style.cssText = `
    min-width: 260px;
    max-width: 100%;
    background: ${toastData.background};
    border: 1px solid ${toastData.border};
    border-left: 4px solid ${toastData.color};
    color: #f8fafc;
    padding: 14px 16px;
    border-radius: 12px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    font-size: 13px;
    line-height: 1.5;
    font-family: Inter, sans-serif;
    box-shadow: 0 10px 25px rgba(0,0,0,0.35);
    animation: toastSlideIn 0.25s ease;
    transition: all 0.25s ease;
    pointer-events: auto;
    backdrop-filter: blur(10px);
  `;
  
  toast.innerHTML = `
    <div style="color:${toastData.color}; flex-shrink:0; margin-top:1px;">
      ${toastData.icon}
    </div>
    <div style="flex:1; word-break: break-word;">
      ${message}
    </div>
    <button onclick="this.parentElement.remove()" style="
      background: none;
      border: none;
      color: #94a3b8;
      cursor: pointer;
      padding: 4px;
      font-size: 16px;
      flex-shrink: 0;
    ">✕</button>
  `;
  
  // Error shake animation
  if (type === 'error') {
    toast.animate([
      { transform: 'translateX(0)' },
      { transform: 'translateX(-5px)' },
      { transform: 'translateX(5px)' },
      { transform: 'translateX(0)' }
    ], {
      duration: 300
    });
  }
  
  container.appendChild(toast);
  
  // Auto remove
  setTimeout(() => {
    toast.style.opacity = '0';
    toast.style.transform = 'translateX(20px)';
    setTimeout(() => {
      if (toast.parentNode) toast.remove();
    }, 250);
  }, timeout_duration);
}

/**
 * Navigate to a module page
 * @param {string} module - Module name (e.g., 'employees', 'departments')
 * @param {object} params - Query parameters
 */
function navigateTo(module, params = {}) {
  if (!module) {
    console.error('Module name is required');
    return;
  }
  
  const query = new URLSearchParams(params).toString();
  const url = `${module}.php${query ? '?' + query : ''}`;
  window.location.href = url;
}

/**
 * Navigate to a custom URL
 * @param {string} url - The URL to navigate to
 * @param {object} params - Query parameters
 */
function navigateToUrl(url, params = {}) {
  if (!url) {
    console.error('URL is required');
    return;
  }
  
  const query = new URLSearchParams(params).toString();
  window.location.href = `${url}${query ? '?' + query : ''}`;
}

/**
 * Get URL parameters as object
 */
function getUrlParams() {
  const params = new URLSearchParams(window.location.search);
  const result = {};
  for (const [key, value] of params) {
    result[key] = value;
  }
  return result;
}

/**
 * Format date for display
 */
function formatDate(dateString, format = 'YYYY-MM-DD') {
  if (!dateString) return '';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes);
}

/**
 * Confirm action with modal
 */
function confirmAction(message, callback) {
  if (confirm(message)) {
    if (typeof callback === 'function') {
      callback();
    }
    return true;
  }
  return false;
}

/**
 * Copy text to clipboard
 */
function copyToClipboard(text) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text)
      .then(() => {
        showToast('Copied to clipboard!', 'success');
      })
      .catch(() => {
        fallbackCopy(text);
      });
  } else {
    fallbackCopy(text);
  }
}

function fallbackCopy(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.left = '-9999px';
  document.body.appendChild(textarea);
  textarea.select();
  try {
    document.execCommand('copy');
    showToast('Copied to clipboard!', 'success');
  } catch (err) {
    showToast('Failed to copy', 'error');
  }
  textarea.remove();
}

// ============================================
// ADD CSS ANIMATIONS
// ============================================

// Add toast slide-in animation
const style = document.createElement('style');
style.textContent = `
  @keyframes toastSlideIn {
    from {
      opacity: 0;
      transform: translateX(20px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateX(0) scale(1);
    }
  }
  
  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
  
  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .fade-in {
    animation: fadeIn 0.3s ease;
  }
  
  .slide-down {
    animation: slideDown 0.3s ease;
  }
`;
document.head.appendChild(style);

console.log('✅ HR Malawi JS loaded successfully');