/**
 * Chrome Extension User ID Helper
 * This script provides easy access to the Chrome extension user ID in any web page
 */

(function() {
  'use strict';

  // Namespace for Chrome extension user ID functionality
  window.ChromeExtensionUserID = {
    // Current user ID (will be populated when available)
    userId: null,
    
    // Callbacks to execute when user ID becomes available
    callbacks: [],
    
    /**
     * Get the current user ID
     * @returns {Promise<string|null>} The user ID or null if not available
     */
    async getUserId() {
      // If already available, return immediately
      if (this.userId) {
        return this.userId;
      }
      
      // Try to get from sessionStorage first
      try {
        const storedUserId = sessionStorage.getItem('chromeExtensionUserId');
        if (storedUserId) {
          this.userId = storedUserId;
          return storedUserId;
        }
      } catch (e) {
        // Ignore storage errors
      }
      
      // Try to get from global window variable
      if (window.chromeExtensionUserId) {
        this.userId = window.chromeExtensionUserId;
        return this.userId;
      }
      
      // Request from content script
      return new Promise((resolve) => {
        // Set up listener for the custom event
        const listener = (event) => {
          if (event.detail && event.detail.userId) {
            this.userId = event.detail.userId;
            window.removeEventListener('chromeExtensionUserIdReady', listener);
            resolve(this.userId);
          }
        };
        
        window.addEventListener('chromeExtensionUserIdReady', listener);
        
        // Also check if it's already available
        setTimeout(() => {
          if (window.chromeExtensionUserId) {
            this.userId = window.chromeExtensionUserId;
            window.removeEventListener('chromeExtensionUserIdReady', listener);
            resolve(this.userId);
          } else {
            // Timeout after 5 seconds
            setTimeout(() => {
              window.removeEventListener('chromeExtensionUserIdReady', listener);
              resolve(null);
            }, 5000);
          }
        }, 100);
      });
    },
    
    /**
     * Execute callback when user ID becomes available
     * @param {Function} callback - Function to execute with user ID
     */
    onUserIdReady(callback) {
      if (this.userId) {
        // Execute immediately if already available
        callback(this.userId);
      } else {
        // Store callback for later execution
        this.callbacks.push(callback);
        
        // Try to get user ID
        this.getUserId().then((userId) => {
          if (userId) {
            // Execute all pending callbacks
            this.callbacks.forEach(cb => cb(userId));
            this.callbacks = [];
          }
        });
      }
    },
    
    /**
     * Check if user ID is available
     * @returns {boolean} True if user ID is available
     */
    isAvailable() {
      return this.userId !== null;
    },
    
    /**
     * Get user ID synchronously (only if already loaded)
     * @returns {string|null} The user ID or null if not loaded
     */
    getUserIdSync() {
      return this.userId || window.chromeExtensionUserId || null;
    }
  };
  
  // Auto-initialize when script loads
  window.ChromeExtensionUserID.getUserId().then((userId) => {
    if (userId) {
      console.log('Chrome Extension User ID Helper: User ID loaded:', userId);
    } else {
      console.log('Chrome Extension User ID Helper: No user ID available');
    }
  });
  
  // Listen for the custom event in case it comes later
  window.addEventListener('chromeExtensionUserIdReady', (event) => {
    if (event.detail && event.detail.userId) {
      window.ChromeExtensionUserID.userId = event.detail.userId;
      console.log('Chrome Extension User ID Helper: User ID received via event:', event.detail.userId);
      
      // Execute any pending callbacks
      window.ChromeExtensionUserID.callbacks.forEach(callback => callback(event.detail.userId));
      window.ChromeExtensionUserID.callbacks = [];
    }
  });

})();

// Also provide a simple global function for easy access
window.getChromeExtensionUserId = function() {
  return window.ChromeExtensionUserID.getUserId();
};

// Provide a synchronous version
window.getChromeExtensionUserIdSync = function() {
  return window.ChromeExtensionUserID.getUserIdSync();
};

console.log('Chrome Extension User ID Helper loaded. Use window.getChromeExtensionUserId() or window.ChromeExtensionUserID.getUserId()');
