// Background script - handles injection coordination
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url && !tab.url.startsWith('chrome://')) {
    // Inject into main frame
    chrome.scripting.executeScript({
      target: { tabId: tabId },
      func: injectDialogOverrides,
      world: 'MAIN'
    });
    
    // Also inject content script for iframe monitoring
    chrome.scripting.executeScript({
      target: { tabId: tabId },
      func: setupIframeMonitoring,
      world: 'ISOLATED'
    });
  }
});

// Function to inject into page context (MAIN world)
function injectDialogOverrides() {
  if (window.autoDialogHandlerInjected) return;
  window.autoDialogHandlerInjected = true;
  
  const originalAlert = window.alert;
  const originalConfirm = window.confirm;
  const originalPrompt = window.prompt;
  
  function showNotification(type, message, delay) {
    const notification = document.createElement('div');
    notification.style.cssText = `
      position: fixed;
      bottom: 12px;
      right: 12px;
      background: rgba(0,0,0,0.85);
      color: white;
      padding: 10px 15px;
      border-radius: 6px;
      font-family: Arial, sans-serif;
      font-size: 13px;
      z-index: 2147483647;
      max-width: 350px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.3);
      border-left: 4px solid #4CAF50;
    `;
    
    let countdown = delay;
    const updateText = () => {
      notification.textContent = `${type}: "${message}" → Auto-handled in ${countdown}s`;
    };
    updateText();
    
    //document.body.appendChild(notification);
    
    const interval = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(interval);
        notification.textContent = `${type} handled automatically`;
        setTimeout(() => notification.remove(), 2000);
      } else {
        updateText();
      }
    }, 1000);
  }
  
  // Override alert
  window.alert = function(message) {
    const delay = Math.floor(Math.random() * 11) + 5; // 5-15 seconds
    showNotification('Alert', message, delay);
    // Don't show the actual alert
    return;
  };
  
  // Override confirm
  window.confirm = function(message) {
    const delay = Math.floor(Math.random() * 11) + 5;
    showNotification('Confirm', message, delay);
    return true; // Always return true after delay
  };
  
  // Override prompt
  window.prompt = function(message, defaultText = '') {
    const delay = Math.floor(Math.random() * 11) + 5;
    showNotification('Prompt', message, delay);
    return defaultText; // Return default value
  };
  
  console.log('Auto-dialog handler injected (no debug mode)');
}

// Function for iframe monitoring
function setupIframeMonitoring() {
  // Monitor for new iframes
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      mutation.addedNodes.forEach((node) => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          const iframes = node.tagName === 'IFRAME' ? [node] : node.querySelectorAll('iframe');
          iframes.forEach(processIframe);
        }
      });
    });
  });
  
  // Process existing iframes
  document.querySelectorAll('iframe').forEach(processIframe);
  
  // Start observing
  observer.observe(document.body, { childList: true, subtree: true });
  
  function processIframe(iframe) {
    iframe.addEventListener('load', () => {
      try {
        // Only works for same-origin iframes
        if (iframe.contentWindow && iframe.contentDocument) {
          const script = iframe.contentDocument.createElement('script');
          script.textContent = `(${injectDialogOverrides.toString()})()`;
          iframe.contentDocument.head.appendChild(script);
        }
      } catch (e) {
        // Cross-origin iframe - can't inject
        console.log('Cross-origin iframe detected, cannot inject dialog handlers');
      }
    });
  }
}