/**
 * SweetAlert2 Wrapper
 * Replace all native alerts/confirms with SweetAlert2
 */

// Custom theme for dark mode
const swalTheme = {
  background: '#1e1e1e',
  color: '#ccc',
  confirmButtonColor: '#007acc',
  cancelButtonColor: '#d32f2f',
  iconColor: '#007acc',
};

// Notification queue system
let notificationQueue = [];
let isShowingNotification = false;
let lastNotifications = new Map();
const DEBOUNCE_TIME = 2000; // 2 seconds

function shouldShowNotification(message) {
  const now = Date.now();
  
  // Check if this message was shown recently
  if (lastNotifications.has(message)) {
    const lastTime = lastNotifications.get(message);
    const timeSince = now - lastTime;
    
    if (timeSince < DEBOUNCE_TIME) {
      console.log('Skipping duplicate notification:', message);
      return false;
    }
  }
  
  // Update last notification time
  lastNotifications.set(message, now);
  
  // Clean up old entries (older than DEBOUNCE_TIME)
  for (const [msg, time] of lastNotifications.entries()) {
    if (now - time > DEBOUNCE_TIME) {
      lastNotifications.delete(msg);
    }
  }
  
  return true;
}

// Process notification queue
async function processNotificationQueue() {
  if (isShowingNotification || notificationQueue.length === 0) {
    return;
  }
  
  isShowingNotification = true;
  const notification = notificationQueue.shift();
  
  try {
    await notification.show();
  } catch (error) {
    console.error('Error showing notification:', error);
  }
  
  isShowingNotification = false;
  
  // Process next notification if any
  if (notificationQueue.length > 0) {
    setTimeout(() => processNotificationQueue(), 100);
  }
}

// Add notification to queue
function queueNotification(showFunction) {
  notificationQueue.push({ show: showFunction });
  processNotificationQueue();
}

/**
 * Override showMessage function
 */
window.showMessage = function(text, type = 'info') {
  // Check for duplicates
  if (!shouldShowNotification(text)) {
    return;
  }
  let icon = 'info';
  let title = '';
  
  switch(type) {
    case 'success':
      icon = 'success';
      title = 'Thành công';
      break;
    case 'error':
      icon = 'error';
      title = 'Lỗi';
      break;
    case 'warning':
      icon = 'warning';
      title = 'Cảnh báo';
      break;
    case 'info':
    default:
      icon = 'info';
      title = 'Thông báo';
      break;
  }
  
  // Remove emoji from text if exists
  const cleanText = text.replace(/^[🔄✓❌⚠️💾📦🎨]+\s*/, '');
  
  // Add to queue
  queueNotification(async () => {
    return new Promise((resolve) => {
      Swal.fire({
        title: title,
        text: cleanText,
        icon: icon,
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        background: swalTheme.background,
        color: swalTheme.color,
        iconColor: type === 'success' ? '#4caf50' : 
                  type === 'error' ? '#f44336' : 
                  type === 'warning' ? '#ff9800' : 
                  swalTheme.iconColor,
        didOpen: (toast) => {
          toast.addEventListener('mouseenter', Swal.stopTimer);
          toast.addEventListener('mouseleave', Swal.resumeTimer);
        },
        didClose: () => {
          resolve();
        }
      });
    });
  });
};

/**
 * Override native confirm
 */
const originalConfirm = window.confirm;
window.confirm = async function(message) {
  const result = await Swal.fire({
    title: 'Xác nhận',
    text: message,
    icon: 'question',
    showCancelButton: true,
    confirmButtonText: 'Đồng ý',
    cancelButtonText: 'Hủy',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
    cancelButtonColor: swalTheme.cancelButtonColor,
    reverseButtons: true,
  });
  
  return result.isConfirmed;
};

/**
 * Override native alert
 */
const originalAlert = window.alert;
window.alert = function(message) {
  Swal.fire({
    title: 'Thông báo',
    text: message,
    icon: 'info',
    confirmButtonText: 'OK',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
  });
};

/**
 * Custom confirm with async/await support
 */
window.confirmAsync = async function(message, title = 'Xác nhận') {
  const result = await Swal.fire({
    title: title,
    text: message,
    icon: 'question',
    showCancelButton: true,
    confirmButtonText: 'Đồng ý',
    cancelButtonText: 'Hủy',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
    cancelButtonColor: swalTheme.cancelButtonColor,
    reverseButtons: true,
  });
  
  return result.isConfirmed;
};

/**
 * Success message
 */
window.showSuccess = function(message, title = 'Thành công') {
  // Check for duplicates
  if (!shouldShowNotification(message)) {
    return;
  }
  
  // Add to queue
  queueNotification(async () => {
    return new Promise((resolve) => {
      Swal.fire({
        title: title,
        text: message,
        icon: 'success',
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        background: swalTheme.background,
        color: swalTheme.color,
        iconColor: '#4caf50',
        didClose: () => {
          resolve();
        }
      });
    });
  });
};

/**
 * Error message
 */
window.showError = function(message, title = 'Lỗi') {
  // Check for duplicates
  if (!shouldShowNotification(message)) {
    return;
  }
  
  Swal.fire({
    title: title,
    text: message,
    icon: 'error',
    confirmButtonText: 'OK',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
    iconColor: '#f44336',
  });
};

/**
 * Warning message
 */
window.showWarning = function(message, title = 'Cảnh báo') {
  // Check for duplicates
  if (!shouldShowNotification(message)) {
    return;
  }
  
  Swal.fire({
    title: title,
    text: message,
    icon: 'warning',
    confirmButtonText: 'OK',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
    iconColor: '#ff9800',
  });
};

/**
 * Loading message
 */
window.showLoading = function(message = 'Đang xử lý...') {
  Swal.fire({
    title: message,
    allowOutsideClick: false,
    allowEscapeKey: false,
    showConfirmButton: false,
    background: swalTheme.background,
    color: swalTheme.color,
    didOpen: () => {
      Swal.showLoading();
    }
  });
};

/**
 * Close loading
 */
window.closeLoading = function() {
  Swal.close();
};

/**
 * Progress message
 */
window.showProgress = function(message, current, total) {
  const percentage = Math.round((current / total) * 100);
  
  Swal.fire({
    title: message,
    html: `
      <div style="margin-top: 20px;">
        <div style="background: #2d2d2d; border-radius: 10px; overflow: hidden; height: 20px;">
          <div style="background: linear-gradient(90deg, #007acc, #00a8ff); width: ${percentage}%; height: 100%; transition: width 0.3s;"></div>
        </div>
        <div style="margin-top: 10px; font-size: 14px; color: #888;">
          ${current} / ${total} (${percentage}%)
        </div>
      </div>
    `,
    allowOutsideClick: false,
    allowEscapeKey: false,
    showConfirmButton: false,
    background: swalTheme.background,
    color: swalTheme.color,
  });
};

/**
 * Input dialog
 */
window.promptAsync = async function(message, defaultValue = '', title = 'Nhập thông tin') {
  const result = await Swal.fire({
    title: title,
    text: message,
    input: 'text',
    inputValue: defaultValue,
    showCancelButton: true,
    confirmButtonText: 'OK',
    cancelButtonText: 'Hủy',
    background: swalTheme.background,
    color: swalTheme.color,
    confirmButtonColor: swalTheme.confirmButtonColor,
    cancelButtonColor: swalTheme.cancelButtonColor,
    inputValidator: (value) => {
      if (!value) {
        return 'Vui lòng nhập giá trị!';
      }
    }
  });
  
  return result.isConfirmed ? result.value : null;
};

console.log('✓ SweetAlert2 wrapper initialized');
