// Function to log output to the output div
function log(message) {
  const output = document.getElementById('output');
  const timestamp = new Date().toLocaleTimeString();
  output.innerHTML += `[${timestamp}] ${message}\n`;
  output.scrollTop = output.scrollHeight;
}

// Function to check if chrome.runtime is initialized
function isChromeRuntimeReady() {
  // Check for our global initialization flags first
  if (typeof window.__qtWebChannelTransportReady === 'boolean' &&
      window.__qtWebChannelTransportReady === true) {
    return true;
  }
  
  // Check if the isChromeRuntimeInitialized function exists and use it
  if (typeof window.isChromeRuntimeInitialized === 'function') {
    return window.isChromeRuntimeInitialized();
  }
  
  // Fallback to basic checks
  return typeof chrome !== 'undefined' &&
         chrome.runtime &&
         typeof chrome.runtime.id === 'string';
}

// Function to wait for chrome.runtime to be initialized
function waitForChromeRuntime(callback, maxAttempts = 100) {
  let attempts = 0;
  
  function checkRuntime() {
    if (isChromeRuntimeReady()) {
      log('chrome.runtime API is ready');
      callback();
    } else if (attempts < maxAttempts) {
      attempts++;
      
      // Log less frequently to reduce console spam
      if (attempts === 1 || attempts % 10 === 0) {
        log(`Waiting for chrome.runtime API to initialize (attempt ${attempts}/${maxAttempts})...`);
      }
      
      // Try to trigger initialization if we're past several attempts
      if (attempts > 20 && attempts % 20 === 0) {
        log('Attempting to trigger chrome.runtime initialization');
        document.dispatchEvent(new CustomEvent('requestWebChannelTransport', {
          detail: { timestamp: Date.now() }
        }));
      }
      
      setTimeout(checkRuntime, 100);
    } else {
      log('ERROR: chrome.runtime API failed to initialize after multiple attempts');
      
      // Report initialization status if available
      if (typeof window.reportInitializationStatus === 'function') {
        window.reportInitializationStatus();
      } else {
        log('Initialization status:');
        log(`- chrome defined: ${typeof chrome !== 'undefined'}`);
        log(`- chrome.runtime defined: ${typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined'}`);
        log(`- __qtWebChannelTransportReady: ${window.__qtWebChannelTransportReady}`);
      }
    }
  }
  
  checkRuntime();
}

// Add a listener for the chrome.runtime.initialized event
document.addEventListener('chrome.runtime.initialized', (event) => {
  log(`chrome.runtime API initialized for extension: ${event.detail.extensionId}`);
});

// Test chrome.runtime.getURL()
document.getElementById('getUrl').addEventListener('click', () => {
  waitForChromeRuntime(() => {
    try {
      const url = chrome.runtime.getURL('popup.html');
      log(`getURL result: ${url}`);
    } catch (error) {
      log(`getURL error: ${error.message}`);
    }
  });
});

// Test chrome.runtime.sendMessage()
document.getElementById('sendMessage').addEventListener('click', () => {
  waitForChromeRuntime(() => {
    try {
      const message = { action: 'test', from: 'popup', timestamp: Date.now() };
      chrome.runtime.sendMessage(message, (response) => {
        if (chrome.runtime.lastError) {
          log(`sendMessage error: ${chrome.runtime.lastError.message}`);
        } else {
          log(`sendMessage response: ${JSON.stringify(response)}`);
        }
      });
      log(`sendMessage sent: ${JSON.stringify(message)}`);
    } catch (error) {
      log(`sendMessage error: ${error.message}`);
    }
  });
});

// Test chrome.runtime.connect()
document.getElementById('connect').addEventListener('click', () => {
  waitForChromeRuntime(() => {
    try {
      const port = chrome.runtime.connect({ name: 'popup-port' });
      log(`connect: Port created with name 'popup-port'`);
      
      // Verify port.onMessage exists before adding listener
      if (!port.onMessage) {
        log('port.onMessage is not available');
        
        // Try to create it if it doesn't exist
        port.onMessage = {
          addListener: function(callback) {
            log('Added listener to newly created port.onMessage');
            if (!this.listeners) this.listeners = [];
            this.listeners.push(callback);
          },
          removeListener: function(callback) {
            if (!this.listeners) return;
            const index = this.listeners.indexOf(callback);
            if (index !== -1) {
              this.listeners.splice(index, 1);
            }
          },
          hasListener: function(callback) {
            return this.listeners && this.listeners.includes(callback);
          },
          listeners: []
        };
      }
      
      // Now try to add the message listener
      try {
        port.onMessage.addListener((message) => {
          log(`Port received message: ${JSON.stringify(message)}`);
        });
        log('Port message listener set up successfully');
      } catch (e) {
        log(`Failed to add port message listener: ${e.message}`);
      }
      
      // Verify port.onDisconnect exists before adding listener
      if (!port.onDisconnect) {
        log('port.onDisconnect is not available');
        
        // Try to create it if it doesn't exist
        port.onDisconnect = {
          addListener: function(callback) {
            log('Added listener to newly created port.onDisconnect');
            if (!this.listeners) this.listeners = [];
            this.listeners.push(callback);
          },
          removeListener: function(callback) {
            if (!this.listeners) return;
            const index = this.listeners.indexOf(callback);
            if (index !== -1) {
              this.listeners.splice(index, 1);
            }
          },
          hasListener: function(callback) {
            return this.listeners && this.listeners.includes(callback);
          },
          listeners: []
        };
      }
      
      // Now try to add the disconnect listener
      try {
        port.onDisconnect.addListener(() => {
          log(`Port disconnected`);
        });
        log('Port disconnect listener set up successfully');
      } catch (e) {
        log(`Failed to add port disconnect listener: ${e.message}`);
      }
      
      // Try to send a message through the port
      try {
        port.postMessage({ action: 'hello', from: 'popup', timestamp: Date.now() });
        log(`Port sent message`);
      } catch (e) {
        log(`Failed to send message through port: ${e.message}`);
      }
    } catch (error) {
      log(`connect error: ${error.message}`);
    }
  });
});

// Test chrome.runtime.getManifest()
document.getElementById('getManifest').addEventListener('click', () => {
  waitForChromeRuntime(() => {
    try {
      const manifest = chrome.runtime.getManifest();
      log(`getManifest result: ${JSON.stringify(manifest, null, 2)}`);
    } catch (error) {
      log(`getManifest error: ${error.message}`);
    }
  });
});

// Test chrome.runtime.getBackgroundPage()
document.getElementById('getBackgroundPage').addEventListener('click', () => {
  waitForChromeRuntime(() => {
    try {
      chrome.runtime.getBackgroundPage((backgroundPage) => {
        if (chrome.runtime.lastError) {
          log(`getBackgroundPage error: ${chrome.runtime.lastError.message}`);
        } else {
          log(`getBackgroundPage success: ${backgroundPage ? 'Background page accessed' : 'null'}`);
        }
      });
    } catch (error) {
      log(`getBackgroundPage error: ${error.message}`);
    }
  });
});

// Clear output
document.getElementById('clearOutput').addEventListener('click', () => {
  document.getElementById('output').innerHTML = '';
});

// Setup message listener when runtime is ready
function setupMessageListener() {
  waitForChromeRuntime(() => {
    // Verify chrome.runtime.onMessage exists before adding listener
    if (!chrome.runtime || !chrome.runtime.onMessage) {
      log('chrome.runtime.onMessage is not available');
      
      // Try to create it if it doesn't exist
      if (chrome.runtime && !chrome.runtime.onMessage) {
        log('Attempting to create chrome.runtime.onMessage');
        chrome.runtime.onMessage = {
          addListener: function(callback) {
            log('Added listener to newly created onMessage');
            if (!this.listeners) this.listeners = [];
            this.listeners.push(callback);
          },
          removeListener: function(callback) {
            if (!this.listeners) return;
            const index = this.listeners.indexOf(callback);
            if (index !== -1) {
              this.listeners.splice(index, 1);
            }
          },
          hasListener: function(callback) {
            return this.listeners && this.listeners.includes(callback);
          },
          listeners: []
        };
      }
    }
    
    // Now try to add the listener
    try {
      chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        log(`Received message from background: ${JSON.stringify(message)}`);
        sendResponse({ received: true, from: 'popup' });
        return true; // Keep the message channel open for async response
      });
      
      log('Message listener set up successfully');
    } catch (e) {
      log(`Failed to add message listener: ${e.message}`);
    }
  });
}

// Log when popup is loaded
document.addEventListener('DOMContentLoaded', () => {
  log('Popup loaded. Click buttons to test chrome.runtime API.');
  
  // Check chrome.runtime API status
  if (isChromeRuntimeReady()) {
    log('chrome.runtime API is already available');
  } else {
    log('Waiting for chrome.runtime API to initialize...');
  }
  
  // Setup message listener
  setupMessageListener();
});