/**
 * Conversation Visibility Settings Modal
 * Manages the configuration for store visibility of new conversations
 */

const ConversationVisibilitySettings = {
  modal: null,
  overlay: null,
  currentSettings: null,

  /**
   * Initialize the visibility settings modal
   */
  init() {
    this.createModal();
    this.attachEventListeners();
  },

  /**
   * Create the modal HTML structure
   */
  createModal() {
    // Create overlay
    this.overlay = document.createElement('div');
    this.overlay.id = 'visibility-settings-overlay';
    this.overlay.className = 'modal-overlay';
    this.overlay.style.cssText = `
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 9998;
    `;

    // Create modal
    this.modal = document.createElement('div');
    this.modal.id = 'visibility-settings-modal';
    this.modal.className = 'modal';
    this.modal.style.cssText = `
      display: none;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      border-radius: 12px;
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
      z-index: 9999;
      max-width: 600px;
      width: 90%;
      max-height: 90vh;
      overflow-y: auto;
    `;

    this.modal.innerHTML = `
      <div style="padding: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h2 style="margin: 0; font-size: 24px; color: #333;" data-i18n="conversations.visibility_settings_title">
            Conversation Visibility Configuration
          </h2>
          <button id="close-visibility-modal" style="background: none; border: none; font-size: 24px; cursor: pointer; color: #666;">
            <i class="fas fa-times"></i>
          </button>
        </div>

        <p style="color: #666; margin-bottom: 24px;" data-i18n="conversations.visibility_settings_description">
          Control how stores and departments see new conversations
        </p>

        <div style="background: #f8f9fa; border-radius: 8px; padding: 20px; margin-bottom: 24px;">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
            <label style="font-weight: 600; color: #333; font-size: 16px;" data-i18n="conversations.stores_can_see_new_label">
              Stores can see new conversations
            </label>
            <label class="toggle-switch" style="position: relative; display: inline-block; width: 60px; height: 34px;">
              <input type="checkbox" id="stores-can-see-toggle" style="opacity: 0; width: 0; height: 0;">
              <span class="toggle-slider" style="
                position: absolute;
                cursor: pointer;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #ccc;
                transition: .4s;
                border-radius: 34px;
              "></span>
            </label>
          </div>

          <div id="enabled-description" style="display: none; padding: 12px; background: #e8f5e9; border-left: 4px solid #4caf50; border-radius: 4px; margin-bottom: 12px;">
            <p style="margin: 0; color: #2e7d32; font-size: 14px;" data-i18n="conversations.stores_can_see_new_enabled">
              <i class="fas fa-check-circle" style="margin-right: 8px;"></i>
              Enabled: Stores can see all new conversations before assignment or transfer
            </p>
          </div>

          <div id="disabled-description" style="display: none; padding: 12px; background: #fff3e0; border-left: 4px solid #ff9800; border-radius: 4px;">
            <p style="margin: 0; color: #e65100; font-size: 14px;" data-i18n="conversations.stores_can_see_new_disabled">
              <i class="fas fa-info-circle" style="margin-right: 8px;"></i>
              Disabled: Stores only see conversations after receiving a transfer from tenant, flow, or department
            </p>
          </div>
        </div>

        <div style="display: flex; gap: 12px; justify-content: flex-end;">
          <button id="cancel-visibility-settings" style="
            padding: 10px 24px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: #666;
          ">
            Cancel
          </button>
          <button id="save-visibility-settings" style="
            padding: 10px 24px;
            border: none;
            background: #00a149;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
          " data-i18n="conversations.visibility_save">
            Save Settings
          </button>
        </div>
      </div>
    `;

    // Add CSS for toggle switch
    const style = document.createElement('style');
    style.textContent = `
      .toggle-switch input:checked + .toggle-slider {
        background-color: #00a149;
      }
      .toggle-slider:before {
        position: absolute;
        content: "";
        height: 26px;
        width: 26px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
      }
      .toggle-switch input:checked + .toggle-slider:before {
        transform: translateX(26px);
      }
      #save-visibility-settings:hover {
        background: #008a3d;
      }
      #cancel-visibility-settings:hover {
        background: #f5f5f5;
      }
    `;
    document.head.appendChild(style);

    document.body.appendChild(this.overlay);
    document.body.appendChild(this.modal);
  },

  /**
   * Attach event listeners
   */
  attachEventListeners() {
    const toggle = document.getElementById('stores-can-see-toggle');
    const closeBtn = document.getElementById('close-visibility-modal');
    const cancelBtn = document.getElementById('cancel-visibility-settings');
    const saveBtn = document.getElementById('save-visibility-settings');

    // Toggle change event
    toggle.addEventListener('change', () => {
      this.updateDescriptions(toggle.checked);
    });

    // Close modal events
    closeBtn.addEventListener('click', () => this.close());
    cancelBtn.addEventListener('click', () => this.close());
    this.overlay.addEventListener('click', () => this.close());

    // Save button
    saveBtn.addEventListener('click', () => this.save());
  },

  /**
   * Update description visibility based on toggle state
   */
  updateDescriptions(enabled) {
    const enabledDesc = document.getElementById('enabled-description');
    const disabledDesc = document.getElementById('disabled-description');

    if (enabled) {
      enabledDesc.style.display = 'block';
      disabledDesc.style.display = 'none';
    } else {
      enabledDesc.style.display = 'none';
      disabledDesc.style.display = 'block';
    }
  },

  /**
   * Open the modal and load current settings
   */
  async open() {
    try {
      // Load current settings
      const response = await fetch('/api/tenant/conversations/visibility-settings', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });

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

      const data = await response.json();
      this.currentSettings = data.data;

      // Update toggle
      const toggle = document.getElementById('stores-can-see-toggle');
      toggle.checked = this.currentSettings.stores_can_see_new_conversations;
      this.updateDescriptions(toggle.checked);

      // Show modal
      this.overlay.style.display = 'block';
      this.modal.style.display = 'block';

      // Apply i18n if available
      if (window.i18n && window.i18n.translatePage) {
        window.i18n.translatePage();
      }
    } catch (error) {
      console.error('Error opening visibility settings:', error);
      this.showNotification('Error loading settings', 'error');
    }
  },

  /**
   * Close the modal
   */
  close() {
    this.overlay.style.display = 'none';
    this.modal.style.display = 'none';
  },

  /**
   * Save settings
   */
  async save() {
    const toggle = document.getElementById('stores-can-see-toggle');
    const saveBtn = document.getElementById('save-visibility-settings');

    try {
      saveBtn.disabled = true;
      saveBtn.textContent = 'Saving...';

      const response = await fetch('/api/tenant/conversations/visibility-settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
          stores_can_see_new_conversations: toggle.checked
        })
      });

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

      const data = await response.json();
      
      this.showNotification(
        window.i18n?.t('conversations.visibility_saved') || 'Settings saved successfully',
        'success'
      );
      
      this.close();

      // Reload conversations if there's a refresh function
      if (window.WhatsAppCloud && window.WhatsAppCloud.loadConversations) {
        setTimeout(() => {
          window.WhatsAppCloud.loadConversations();
        }, 500);
      }
    } catch (error) {
      console.error('Error saving visibility settings:', error);
      this.showNotification(
        window.i18n?.t('conversations.visibility_error') || 'Error saving settings',
        'error'
      );
    } finally {
      saveBtn.disabled = false;
      saveBtn.textContent = window.i18n?.t('conversations.visibility_save') || 'Save Settings';
    }
  },

  /**
   * Show notification
   */
  showNotification(message, type = 'info') {
    // Try to use existing notification system
    if (window.showNotification) {
      window.showNotification(message, type);
      return;
    }

    // Fallback to simple alert
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 16px 24px;
      background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#2196f3'};
      color: white;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 10000;
      font-size: 14px;
      font-weight: 500;
    `;
    notification.textContent = message;
    document.body.appendChild(notification);

    setTimeout(() => {
      notification.style.opacity = '0';
      notification.style.transition = 'opacity 0.3s';
      setTimeout(() => notification.remove(), 300);
    }, 3000);
  }
};

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

// Export for use in other scripts
window.ConversationVisibilitySettings = ConversationVisibilitySettings;
