/**
 * Conversation Delete Functionality
 * Adds delete option to conversation cards with password confirmation
 * 
 * @version 1.0.0
 */

const ConversationDelete = {
  /**
   * Initialize delete functionality
   */
  init() {
    console.log('🗑️ Initializing Conversation Delete functionality...');
    
    // Check if we're in admin mode
    const cfg = window.UserConversationsConfig || {};
    console.log('📋 Config:', cfg);
    
    if (!cfg.adminMode) {
      console.log('⚠️ Not in admin mode, skipping delete functionality');
      return;
    }
    
    console.log('✅ Admin mode detected, attaching delete event listeners');
    this.attachEventListeners();
    
    // Check for existing buttons after a short delay
    setTimeout(() => {
      const buttons = document.querySelectorAll('.conversation-menu-btn');
      console.log(`🔍 Found ${buttons.length} menu buttons after init`);
      if (buttons.length > 0) {
        console.log('✅ Menu buttons are present in DOM');
      } else {
        console.warn('⚠️ No menu buttons found. They should appear when cards are rendered.');
      }
    }, 1000);
  },

  /**
   * Attach event listeners for delete functionality
   */
  attachEventListeners() {
    console.log('📎 Attaching delete event listeners...');
    
    // Log existing menu buttons
    const existingButtons = document.querySelectorAll('.conversation-menu-btn');
    console.log(`Found ${existingButtons.length} conversation menu buttons`);
    
    // Delegate click events for conversation menu buttons
    document.addEventListener('click', (e) => {
      // Handle menu button click
      if (e.target.closest('.conversation-menu-btn')) {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        
        const btn = e.target.closest('.conversation-menu-btn');
        const conversationId = btn.dataset.conversationId;
        console.log('🖱️ Menu button clicked for conversation:', conversationId);
        this.toggleMenu(conversationId, btn);
        return false;
      }

      // Handle delete option click
      if (e.target.closest('.conversation-delete-option')) {
        e.preventDefault();
        e.stopPropagation();
        const option = e.target.closest('.conversation-delete-option');
        const conversationId = option.dataset.conversationId;
        console.log('🗑️ Delete option clicked for conversation:', conversationId);
        this.showDeleteModal(conversationId);
        this.closeAllMenus();
        return false;
      }

      // Close all menus when clicking outside
      this.closeAllMenus();
    }, true); // Use capture phase to catch event before other handlers

    // Handle modal close
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('conversation-delete-modal')) {
        this.closeDeleteModal();
      }
      if (e.target.closest('.conversation-delete-cancel')) {
        this.closeDeleteModal();
      }
    });

    // Handle delete confirmation
    document.addEventListener('click', (e) => {
      if (e.target.closest('.conversation-delete-confirm-btn')) {
        e.preventDefault();
        this.handleDelete();
      }
    });

    // Handle Enter key in password field
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && e.target.classList.contains('conversation-delete-password')) {
        e.preventDefault();
        this.handleDelete();
      }
    });
    
    console.log('✅ Delete event listeners attached');
  },

  /**
   * Toggle conversation menu
   */
  toggleMenu(conversationId, button) {
    console.log('🔄 Toggling menu for conversation:', conversationId);
    
    // Close all other menus
    document.querySelectorAll('.conversation-menu').forEach(menu => {
      if (menu.dataset.conversationId !== conversationId) {
        menu.remove();
      }
    });

    // Check if menu already exists
    const existingMenu = document.querySelector(`.conversation-menu[data-conversation-id="${conversationId}"]`);
    if (existingMenu) {
      console.log('📋 Menu already exists, closing it');
      existingMenu.remove();
      return;
    }

    console.log('📋 Creating new menu');
    
    // Create menu
    const menu = document.createElement('div');
    menu.className = 'conversation-menu';
    menu.dataset.conversationId = conversationId;
    menu.innerHTML = `
      <div class="conversation-menu-option conversation-delete-option" data-conversation-id="${conversationId}">
        <i class="fas fa-trash"></i>
        <span data-i18n="conversation.delete_conversation">Delete</span>
      </div>
    `;

    // Position menu
    document.body.appendChild(menu);
    
    const rect = button.getBoundingClientRect();
    const menuRect = menu.getBoundingClientRect();
    
    menu.style.position = 'fixed';
    menu.style.top = `${rect.bottom + 5}px`;
    
    // Calculate left position, ensuring menu stays within sidebar
    let leftPos = rect.left - 10;
    
    // Check if menu would overflow to the right
    if (leftPos + menuRect.width > window.innerWidth) {
      // Align to the right edge of the button
      leftPos = rect.right - menuRect.width;
    }
    
    // Ensure menu doesn't go off-screen to the left
    if (leftPos < 10) {
      leftPos = 10;
    }
    
    menu.style.left = `${leftPos}px`;
    
    console.log('✅ Menu created and positioned');

    // Apply translations if i18n is available
    if (typeof i18n !== 'undefined' && i18n.applyTranslations) {
      i18n.applyTranslations(menu);
    }
  },

  /**
   * Close all conversation menus
   */
  closeAllMenus() {
    document.querySelectorAll('.conversation-menu').forEach(menu => menu.remove());
  },

  /**
   * Show delete confirmation modal
   */
  showDeleteModal(conversationId) {
    // Remove existing modal if any
    this.closeDeleteModal();

    const modal = document.createElement('div');
    modal.className = 'conversation-delete-modal';
    modal.innerHTML = `
      <div class="conversation-delete-modal-content">
        <div class="conversation-delete-modal-header">
          <h3 data-i18n="conversation.delete_conversation_title">Delete Conversation</h3>
          <button class="conversation-delete-close" onclick="ConversationDelete.closeDeleteModal()">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="conversation-delete-modal-body">
          <div class="conversation-delete-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <p data-i18n="conversation.delete_conversation_warning">
              This action cannot be undone. All messages and conversation history will be permanently deleted.
            </p>
          </div>
          <div class="conversation-delete-form">
            <label data-i18n="conversation.delete_conversation_password_label">
              Enter your login password to confirm
            </label>
            <input 
              type="password" 
              class="conversation-delete-password" 
              data-i18n-placeholder="conversation.delete_conversation_password_placeholder"
              placeholder="Your password"
              autocomplete="current-password"
            />
            <div class="conversation-delete-error" style="display: none;"></div>
          </div>
        </div>
        <div class="conversation-delete-modal-footer">
          <button class="btn btn-secondary conversation-delete-cancel" data-i18n="conversation.delete_conversation_cancel">
            Cancel
          </button>
          <button class="btn btn-danger conversation-delete-confirm-btn" data-conversation-id="${conversationId}" data-i18n="conversation.delete_conversation_confirm">
            Delete Conversation
          </button>
        </div>
      </div>
    `;

    document.body.appendChild(modal);

    // Apply translations if i18n is available
    if (typeof i18n !== 'undefined' && i18n.applyTranslations) {
      i18n.applyTranslations(modal);
    }

    // Focus password field
    setTimeout(() => {
      const passwordField = modal.querySelector('.conversation-delete-password');
      if (passwordField) passwordField.focus();
    }, 100);
  },

  /**
   * Close delete modal
   */
  closeDeleteModal() {
    const modal = document.querySelector('.conversation-delete-modal');
    if (modal) modal.remove();
  },

  /**
   * Handle delete action
   */
  async handleDelete() {
    const modal = document.querySelector('.conversation-delete-modal');
    if (!modal) return;

    const confirmBtn = modal.querySelector('.conversation-delete-confirm-btn');
    const passwordField = modal.querySelector('.conversation-delete-password');
    const errorDiv = modal.querySelector('.conversation-delete-error');
    const conversationId = confirmBtn.dataset.conversationId;
    const password = passwordField.value.trim();

    // Validate password
    if (!password) {
      this.showError(errorDiv, 'Password is required');
      passwordField.focus();
      return;
    }

    // Disable button and show loading
    confirmBtn.disabled = true;
    confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';

    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`/api/tenant/conversations/${conversationId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ password })
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 401) {
          this.showError(errorDiv, this.t('conversation.delete_conversation_invalid_password', 'Invalid password'));
          passwordField.value = '';
          passwordField.focus();
        } else {
          this.showError(errorDiv, data.error || this.t('conversation.delete_conversation_error', 'Failed to delete conversation'));
        }
        confirmBtn.disabled = false;
        confirmBtn.innerHTML = this.t('conversation.delete_conversation_confirm', 'Delete Conversation');
        return;
      }

      // Success
      this.showSuccess(this.t('conversation.delete_conversation_success', 'Conversation deleted successfully'));
      this.closeDeleteModal();

      // Reload conversations
      if (typeof WhatsAppCloud !== 'undefined' && WhatsAppCloud.loadConversations) {
        WhatsAppCloud.loadConversations();
      }

      // Remove conversation card from UI
      const card = document.querySelector(`[data-card-id="${conversationId}"]`);
      if (card) {
        card.style.transition = 'opacity 0.3s, transform 0.3s';
        card.style.opacity = '0';
        card.style.transform = 'scale(0.9)';
        setTimeout(() => card.remove(), 300);
      }

    } catch (error) {
      console.error('Error deleting conversation:', error);
      this.showError(errorDiv, this.t('conversation.delete_conversation_error', 'Failed to delete conversation'));
      confirmBtn.disabled = false;
      confirmBtn.innerHTML = this.t('conversation.delete_conversation_confirm', 'Delete Conversation');
    }
  },

  /**
   * Show error message
   */
  showError(errorDiv, message) {
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    errorDiv.style.color = '#ef4444';
    errorDiv.style.marginTop = '8px';
    errorDiv.style.fontSize = '14px';
  },

  /**
   * Show success notification
   */
  showSuccess(message) {
    if (typeof showNotification === 'function') {
      showNotification(message, 'success');
    } else if (typeof Notification !== 'undefined' && Notification.success) {
      Notification.success(message);
    } else {
      alert(message);
    }
  },

  /**
   * Translation helper
   */
  t(key, fallback) {
    if (typeof i18n !== 'undefined' && i18n.t) {
      return i18n.t(key) || fallback;
    }
    return fallback;
  },

  /**
   * Add menu button to conversation card
   */
  addMenuButtonToCard(cardElement, conversationId) {
    // Check if button already exists
    if (cardElement.querySelector('.conversation-menu-btn')) {
      return;
    }

    const menuBtn = document.createElement('button');
    menuBtn.className = 'conversation-menu-btn';
    menuBtn.dataset.conversationId = conversationId;
    menuBtn.innerHTML = '<i class="fas fa-ellipsis-v"></i>';
    menuBtn.title = 'Options';

    // Add to card header
    const cardHeader = cardElement.querySelector('.wc-pipeline-card-header, .wc-sidebar-conversation-header');
    if (cardHeader) {
      cardHeader.style.position = 'relative';
      cardHeader.appendChild(menuBtn);
    }
  }
};

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    // Wait a bit for UserConversations to initialize
    setTimeout(() => ConversationDelete.init(), 500);
  });
} else {
  // Wait a bit for UserConversations to initialize
  setTimeout(() => ConversationDelete.init(), 500);
}

// Also listen for when UserConversations renders
document.addEventListener('userConversationsRendered', () => {
  console.log('🔄 UserConversations rendered, reinitializing delete functionality');
  ConversationDelete.init();
});

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
  module.exports = ConversationDelete;
}
