/**
 * Session Manager for Multi-Session UI
 * Handles displaying and switching between multiple active Filevine sessions
 */

import { MESSAGE_TYPES } from '../lib/constants.js';

export class SessionManager {
  constructor(elements) {
    this.elements = elements;
    this.sessions = [];
    this.isExpanded = false;
    this.attachEventListeners();
  }

  /**
   * Attach event listeners for session management
   */
  attachEventListeners() {
    // Toggle sessions list
    this.elements.toggleSessions?.addEventListener('click', () => {
      this.toggleSessionsList();
    });

    // Refresh sessions
    this.elements.refreshSessions?.addEventListener('click', async () => {
      await this.refreshSessions();
    });
  }

  /**
   * Update session info display
   */
  async updateSessionInfo(auth) {
    if (!auth || !this.elements.sessionInfo) {
      this.hideSessionInfo();
      return;
    }

    // Show session info panel
    this.elements.sessionInfo.classList.remove('hidden');

    // Update current session display
    const userEmail = auth.userEmail || auth.userId || 'User';
    const orgName = auth.orgName || `Org ${auth.orgId}`;

    this.elements.sessionUserEmail.textContent = userEmail;
    this.elements.sessionOrgName.textContent = orgName;

    // Load all active sessions
    await this.refreshSessions();
  }

  /**
   * Hide session info panel
   */
  hideSessionInfo() {
    this.elements.sessionInfo?.classList.add('hidden');
  }

  /**
   * Toggle the sessions list expansion
   */
  toggleSessionsList() {
    this.isExpanded = !this.isExpanded;

    if (this.isExpanded) {
      this.elements.activeSessionsList.classList.remove('hidden');
      this.elements.activeSessionsList.classList.add('expanded');
      this.elements.toggleSessions.classList.add('expanded');
    } else {
      this.elements.activeSessionsList.classList.remove('expanded');
      this.elements.toggleSessions.classList.remove('expanded');
      // Keep it visible but collapsed
      setTimeout(() => {
        if (!this.isExpanded) {
          this.elements.activeSessionsList.classList.add('hidden');
        }
      }, 300); // Match CSS transition duration
    }
  }

  /**
   * Refresh the list of active sessions
   */
  async refreshSessions() {
    try {
      console.log('[Session Manager] Refreshing sessions...');

      // Show loading state
      this.elements.sessionsContainer.innerHTML = '<div class="sessions-loading">Scanning for active sessions...</div>';

      // Get active sessions from background
      const response = await chrome.runtime.sendMessage({
        type: MESSAGE_TYPES.GET_ACTIVE_SESSIONS
      });

      if (!response.success) {
        throw new Error('Failed to get active sessions');
      }

      this.sessions = response.sessions || [];
      console.log('[Session Manager] Found', this.sessions.length, 'active sessions');

      // Update session count badge
      if (this.sessions.length > 1) {
        this.elements.sessionCountBadge.textContent = this.sessions.length;
        this.elements.sessionCountBadge.classList.remove('hidden');
      } else {
        this.elements.sessionCountBadge.classList.add('hidden');
      }

      // Render sessions list
      this.renderSessionsList();

    } catch (error) {
      console.error('[Session Manager] Error refreshing sessions:', error);
      this.elements.sessionsContainer.innerHTML = '<div class="sessions-empty">Failed to load sessions</div>';
    }
  }

  /**
   * Render the sessions list UI
   */
  renderSessionsList() {
    if (this.sessions.length === 0) {
      this.elements.sessionsContainer.innerHTML = '<div class="sessions-empty">No active Filevine sessions found</div>';
      return;
    }

    const sessionsHtml = this.sessions.map(session => {
      const isCurrentSession = session.isActive;
      const currentClass = isCurrentSession ? ' current' : '';

      return `
        <div class="session-item${currentClass}" data-tab-id="${session.tabId}">
          <span class="session-item-icon">🌐</span>
          <div class="session-item-details">
            <div class="session-item-org">${this.escapeHtml(session.orgName)}</div>
            <div class="session-item-email">${this.escapeHtml(session.userEmail)}</div>
            <div class="session-item-tab">Tab ${session.tabId}${isCurrentSession ? ' • Active' : ''}</div>
          </div>
        </div>
      `;
    }).join('');

    this.elements.sessionsContainer.innerHTML = sessionsHtml;

    // Add click handlers to session items
    this.elements.sessionsContainer.querySelectorAll('.session-item').forEach(item => {
      item.addEventListener('click', async () => {
        const tabId = parseInt(item.dataset.tabId);
        await this.switchToSession(tabId);
      });
    });
  }

  /**
   * Switch to a specific session (tab)
   */
  async switchToSession(tabId) {
    try {
      console.log('[Session Manager] Switching to tab:', tabId);

      const response = await chrome.runtime.sendMessage({
        type: MESSAGE_TYPES.SWITCH_TO_SESSION,
        tabId: tabId
      });

      if (response.success) {
        console.log('[Session Manager] Successfully switched to tab:', tabId);
        // Collapse the sessions list after switching
        if (this.isExpanded) {
          this.toggleSessionsList();
        }
        // Refresh sessions to update the active indicator
        setTimeout(() => this.refreshSessions(), 500);
      }

    } catch (error) {
      console.error('[Session Manager] Error switching to session:', error);
      alert(`Failed to switch to session: ${error.message}`);
    }
  }

  /**
   * Escape HTML to prevent XSS
   */
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}
