/**
 * Conversations Settings Manager
 * Manages conversation visibility settings for tenant admin
 * 
 * Features:
 * - Configure if stores see new conversations before transfer
 * - Modal interface for settings
 * - Real-time updates
 * - Multi-language support
 */

const ConversationsSettings = {
  currentSettings: null,

  /**
   * Initialize settings manager
   */
  init() {
    this.loadSettings();
    this.attachEventListeners();
  },

  /**
   * Load current settings from API
   */
  async loadSettings() {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch('/api/tenant/conversations/settings', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        throw new Error('Failed to load settings');
      }

      const result = await response.json();
      this.currentSettings = result.data;
    } catch (error) {
      console.error('Error loading conversation settings:', error);
      this.showNotification('error', 'Failed to load settings');
    }
  },

  /**
   * Save settings to API
   */
  async saveSettings(settings) {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch('/api/tenant/conversations/settings', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(settings)
      });

      if (!response.ok) {
        throw new Error('Failed to save settings');
      }

      const result = await response.json();
      this.currentSettings = result.data;
      this.showNotification('success', 'Settings saved successfully');
      return true;
    } catch (error) {
      console.error('Error saving conversation settings:', error);
      this.showNotification('error', 'Failed to save settings');
      return false;
    }
  },

  /**
   * Show settings modal
   */
  showSettingsModal() {
    const modal = document.getElementById('conversation-settings-modal');
    const overlay = document.getElementById('conversation-settings-overlay');
    
    if (!modal || !overlay) {
      this.createSettingsModal();
      return this.showSettingsModal();
    }

    // Populate current settings
    const checkbox = document.getElementById('stores-see-new-conversations');
    if (checkbox && this.currentSettings) {
      checkbox.checked = this.currentSettings.stores_see_new_conversations;
    }

    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
  },

  /**
   * Hide settings modal
   */
  hideSettingsModal() {
    const modal = document.getElementById('conversation-settings-modal');
    const overlay = document.getElementById('conversation-settings-overlay');
    
    if (modal) modal.classList.add('hidden');
    if (overlay) overlay.classList.add('hidden');
  },

  /**
   * Create settings modal HTML
   */
  createSettingsModal() {
    const modalHTML = `
      <div id="conversation-settings-overlay" class="conversation-settings-overlay hidden"></div>
      <div id="conversation-settings-modal" class="conversation-settings-modal hidden">
        <div class="settings-modal-header">
          <h2 data-i18n="conversations.settings.title">Conversation Settings</h2>
          <button class="settings-modal-close" onclick="ConversationsSettings.hideSettingsModal()">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="settings-modal-body">
          <div class="settings-section">
            <div class="settings-section-header">
              <i class="fas fa-eye"></i>
              <h3 data-i18n="conversations.settings.visibility_title">Conversation Visibility</h3>
            </div>
            
            <div class="settings-option">
              <div class="settings-option-content">
                <label class="settings-option-label">
                  <input 
                    type="checkbox" 
                    id="stores-see-new-conversations"
                    class="settings-checkbox"
                  />
                  <span class="settings-option-title" data-i18n="conversations.settings.stores_see_new">
                    Stores can see new conversations
                  </span>
                </label>
                <p class="settings-option-description" data-i18n="conversations.settings.stores_see_new_desc">
                  When enabled, store users can see and respond to new conversations immediately. 
                  When disabled, stores will only see conversations after they receive a transfer from admin, flow, or department.
                </p>
              </div>
            </div>

            <div class="settings-info-box">
              <i class="fas fa-info-circle"></i>
              <div>
                <strong data-i18n="conversations.settings.note_title">Important Note:</strong>
                <p data-i18n="conversations.settings.note_desc">
                  Admin users always see all conversations regardless of this setting. 
                  Department users always require transfers to see conversations.
                </p>
              </div>
            </div>
          </div>
        </div>
        
        <div class="settings-modal-footer">
          <button 
            class="btn-secondary" 
            onclick="ConversationsSettings.hideSettingsModal()"
            data-i18n="common.cancel"
          >
            Cancel
          </button>
          <button 
            class="btn-primary" 
            onclick="ConversationsSettings.handleSaveSettings()"
            data-i18n="common.save"
          >
            Save Changes
          </button>
        </div>
      </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHTML);
  },

  /**
   * Handle save settings button click
   */
  async handleSaveSettings() {
    const checkbox = document.getElementById('stores-see-new-conversations');
    if (!checkbox) return;

    const settings = {
      stores_see_new_conversations: checkbox.checked
    };

    const success = await this.saveSettings(settings);
    if (success) {
      this.hideSettingsModal();
      
      // Reload conversations if UserConversations is available
      if (window.UserConversations && typeof window.UserConversations.loadConversations === 'function') {
        window.UserConversations.loadConversations();
      }
    }
  },

  /**
   * Attach event listeners
   */
  attachEventListeners() {
    // Close modal on overlay click
    document.addEventListener('click', (e) => {
      if (e.target.id === 'conversation-settings-overlay') {
        this.hideSettingsModal();
      }
    });

    // Close modal on ESC key
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        this.hideSettingsModal();
      }
    });
  },

  /**
   * Show notification
   */
  showNotification(type, message) {
    // Use existing notification system if available
    if (window.showNotification) {
      window.showNotification(type, message);
      return;
    }

    // Fallback notification
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 20px;
      background: ${type === 'success' ? '#10b981' : '#ef4444'};
      color: white;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
      z-index: 10000;
      animation: slideIn 0.3s ease;
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
      notification.style.animation = 'slideOut 0.3s ease';
      setTimeout(() => notification.remove(), 300);
    }, 3000);
  }
};

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => ConversationsSettings.init());
} else {
  ConversationsSettings.init();
}
