// Log when the content script is loaded
console.log('Runtime API Test Extension: Content script loaded');

// 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()) {
      console.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) {
        console.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) {
        console.log('Attempting to trigger chrome.runtime initialization');
        document.dispatchEvent(new CustomEvent('requestWebChannelTransport', {
          detail: { timestamp: Date.now() }
        }));
      }
      
      setTimeout(checkRuntime, 100);
    } else {
      console.error('ERROR: chrome.runtime API failed to initialize after multiple attempts');
      
      // Report initialization status if available
      if (typeof window.reportInitializationStatus === 'function') {
        window.reportInitializationStatus();
      } else {
        console.error('Initialization status:');
        console.error(`- chrome defined: ${typeof chrome !== 'undefined'}`);
        console.error(`- chrome.runtime defined: ${typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined'}`);
        console.error(`- __qtWebChannelTransportReady: ${window.__qtWebChannelTransportReady}`);
      }
    }
  }
  
  checkRuntime();
}

// Function to create a floating control panel
function createControlPanel() {
  // Check if panel already exists
  if (document.getElementById('runtime-api-test-panel')) {
    return;
  }
  
  // Create panel container
  const panel = document.createElement('div');
  panel.id = 'runtime-api-test-panel';
  panel.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 300px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    font-family: Arial, sans-serif;
    font-size: 12px;
    z-index: 9999;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  `;
  
  // Create header
  const header = document.createElement('div');
  header.style.cssText = `
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    border-bottom: 1px solid #ccc;
    padding-bottom: 5px;
  `;
  
  const title = document.createElement('h3');
  title.textContent = 'Runtime API Test';
  title.style.margin = '0';
  
  const closeBtn = document.createElement('button');
  closeBtn.textContent = 'X';
  closeBtn.style.cssText = `
    background: none;
    border: none;
    cursor: pointer;
    font-weight: bold;
  `;
  closeBtn.onclick = () => panel.remove();
  
  header.appendChild(title);
  header.appendChild(closeBtn);
  panel.appendChild(header);
  
  // Create buttons
  const createButton = (text, onClick) => {
    const button = document.createElement('button');
    button.textContent = text;
    button.style.cssText = `
      margin: 5px 0;
      padding: 5px;
      width: 100%;
      cursor: pointer;
    `;
    button.onclick = onClick;
    return button;
  };
  
  // Add buttons for testing runtime API
  panel.appendChild(createButton('Send Message to Background', () => {
    waitForChromeRuntime(() => {
      chrome.runtime.sendMessage(
        { action: 'test', from: 'content', url: window.location.href },
        response => {
          logOutput(`Response: ${JSON.stringify(response)}`);
        }
      );
      logOutput('Message sent to background');
    });
  }));
  
  panel.appendChild(createButton('Connect to Background', () => {
    waitForChromeRuntime(() => {
      const port = chrome.runtime.connect({ name: 'content-port' });
      logOutput('Connected to background with port: content-port');
      
      port.onMessage.addListener(msg => {
        logOutput(`Port message received: ${JSON.stringify(msg)}`);
      });
      
      port.postMessage({ action: 'hello', from: 'content', url: window.location.href });
      logOutput('Message sent through port');
    });
  }));
  
  panel.appendChild(createButton('Get Extension URL', () => {
    waitForChromeRuntime(() => {
      const url = chrome.runtime.getURL('popup.html');
      logOutput(`Extension URL: ${url}`);
    });
  }));
  
  // Create output area
  const output = document.createElement('div');
  output.id = 'runtime-api-test-output';
  output.style.cssText = `
    margin-top: 10px;
    padding: 5px;
    background-color: #fff;
    border: 1px solid #ddd;
    height: 100px;
    overflow-y: auto;
    font-family: monospace;
    font-size: 11px;
    white-space: pre-wrap;
  `;
  panel.appendChild(output);
  
  // Add to page
  document.body.appendChild(panel);
  
  // Log function
  window.logOutput = function(message) {
    const outputDiv = document.getElementById('runtime-api-test-output');
    if (outputDiv) {
      const timestamp = new Date().toLocaleTimeString();
      outputDiv.innerHTML += `[${timestamp}] ${message}\n`;
      outputDiv.scrollTop = outputDiv.scrollHeight;
    }
  };
  
  logOutput('Content script panel initialized');
  
  // Check chrome.runtime API status
  if (isChromeRuntimeReady()) {
    logOutput('chrome.runtime API is already available');
  } else {
    logOutput('Waiting for chrome.runtime API to initialize...');
  }
  
  // Setup message listener
  setupMessageListener();
}

// Setup message listener when runtime is ready
function setupMessageListener() {
  waitForChromeRuntime(() => {
    // Verify chrome.runtime.onMessage exists before adding listener
    if (!chrome.runtime || !chrome.runtime.onMessage) {
      console.error('chrome.runtime.onMessage is not available');
      
      // Try to create it if it doesn't exist
      if (chrome.runtime && !chrome.runtime.onMessage) {
        console.log('Attempting to create chrome.runtime.onMessage');
        chrome.runtime.onMessage = {
          addListener: function(callback) {
            console.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) => {
        console.log('Content script received message:', message);
        
        if (document.getElementById('runtime-api-test-output')) {
          logOutput(`Message from background: ${JSON.stringify(message)}`);
        }
        
        sendResponse({ received: true, from: 'content', url: window.location.href });
        return true; // Keep the message channel open for async response
      });
      
      console.log('Message listener set up successfully');
    } catch (e) {
      console.error('Failed to add message listener:', e);
      if (document.getElementById('runtime-api-test-output')) {
        logOutput(`ERROR: Failed to add message listener: ${e.message}`);
      }
    }
  });
}

// Add a listener for the chrome.runtime.initialized event
document.addEventListener('chrome.runtime.initialized', (event) => {
  console.log(`chrome.runtime API initialized for extension: ${event.detail.extensionId}`);
  if (document.getElementById('runtime-api-test-output')) {
    logOutput(`chrome.runtime API initialized for extension: ${event.detail.extensionId}`);
  }
});

// Wait for page to be fully loaded
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', createControlPanel);
} else {
  createControlPanel();
}