// Enhanced content script with iframe communication
(function() {
  'use strict';
  
  // Inject into page context
  const script = document.createElement('script');
  script.textContent = `
    (function() {
      if (window.dialogHandlerActive) return;
      window.dialogHandlerActive = true;
      
      const originalAlert = window.alert;
      const originalConfirm = window.confirm;
      const originalPrompt = window.prompt;
      
      function notifyHandler(type, message, result) {
        window.postMessage({
          type: 'DIALOG_INTERCEPTED',
          dialogType: type,
          message: message,
          result: result,
          timestamp: Date.now()
        }, '*');
      }
      
      window.alert = function(message) {
        const delay = Math.floor(Math.random() * 11) + 5;
        notifyHandler('alert', message, null);
        return; // Suppress the alert
      };
      
      window.confirm = function(message) {
        const delay = Math.floor(Math.random() * 11) + 5;
        notifyHandler('confirm', message, true);
        return true;
      };
      
      window.prompt = function(message, defaultText = '') {
        const delay = Math.floor(Math.random() * 11) + 5;
        notifyHandler('prompt', message, defaultText);
        return defaultText;
      };
      
      // Handle iframe communication
      window.addEventListener('message', function(event) {
        if (event.data.type === 'INJECT_DIALOG_HANDLER') {
          // Re-inject handlers (for dynamically created iframes)
          const iframes = document.querySelectorAll('iframe');
          iframes.forEach(iframe => {
            try {
              if (iframe.contentWindow) {
                iframe.contentWindow.postMessage({
                  type: 'INJECT_HANDLERS'
                }, '*');
              }
            } catch (e) {
              // Cross-origin iframe
            }
          });
        }
        
        // Handle requests from iframes to inject handlers
        if (event.data.type === 'INJECT_HANDLERS' && event.source !== window) {
          try {
            const iframeScript = document.createElement('script');
            iframeScript.textContent = arguments.callee.toString().replace('arguments.callee', 'function');
            event.source.document.head.appendChild(iframeScript);
            iframeScript.remove();
          } catch (e) {
            console.log('Could not inject into iframe:', e.message);
          }
        }
      });
      
      // Auto-inject into existing iframes
      setTimeout(() => {
        const iframes = document.querySelectorAll('iframe');
        iframes.forEach(iframe => {
          try {
            if (iframe.contentWindow && iframe.contentDocument) {
              const iframeScript = iframe.contentDocument.createElement('script');
              iframeScript.textContent = arguments.callee.toString().replace('arguments.callee', 'function anonymous');
              iframe.contentDocument.head.appendChild(iframeScript);
              iframeScript.remove();
            }
          } catch (e) {
            // Cross-origin or restricted iframe
          }
        });
      }, 100);
      
      console.log('Dialog handlers injected successfully');
    })();
  `;
  
  // Inject the script
  (document.head || document.documentElement).appendChild(script);
  script.remove();
  
  // Listen for dialog interceptions
  window.addEventListener('message', function(event) {
    if (event.data && event.data.type === 'DIALOG_INTERCEPTED') {
      const { dialogType, message, result } = event.data;
      showDialogNotification(dialogType, message);
    }
  });
  
  // Monitor for new iframes and inject handlers
  const iframeObserver = 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(setupIframeHandler);
        }
      });
    });
  });
  
  // Setup existing iframes
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      document.querySelectorAll('iframe').forEach(setupIframeHandler);
    });
  } else {
    document.querySelectorAll('iframe').forEach(setupIframeHandler);
  }
  
  // Start observing for new iframes
  if (document.body) {
    iframeObserver.observe(document.body, { childList: true, subtree: true });
  } else {
    document.addEventListener('DOMContentLoaded', () => {
      iframeObserver.observe(document.body, { childList: true, subtree: true });
    });
  }
  
  function setupIframeHandler(iframe) {
    // Skip if already processed
    if (iframe.dataset.dialogHandlerInjected) return;
    iframe.dataset.dialogHandlerInjected = 'true';
    
    const injectIntoIframe = () => {
      try {
        // For same-origin iframes, inject handlers directly
        if (iframe.contentWindow && iframe.contentDocument) {
          const iframeScript = iframe.contentDocument.createElement('script');
          iframeScript.textContent = script.textContent;
          iframe.contentDocument.head.appendChild(iframeScript);
          iframeScript.remove();
          console.log('Dialog handlers injected into same-origin iframe');
        }
      } catch (e) {
        // Cross-origin iframe - try postMessage approach
        try {
          iframe.contentWindow.postMessage({
            type: 'INJECT_HANDLERS'
          }, '*');
          console.log('Attempted cross-origin iframe injection via postMessage');
        } catch (e2) {
          console.log('Cannot inject into cross-origin iframe:', e2.message);
        }
      }
    };
    
    if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
      injectIntoIframe();
    } else {
      iframe.addEventListener('load', injectIntoIframe);
    }
  }
  
  function showDialogNotification(type, message) {
    const delay = Math.floor(Math.random() * 11) + 5;
    
    // Remove existing notification
    const existingNotification = document.getElementById('dialog-auto-handler-notification');
    if (existingNotification) {
      existingNotification.remove();
    }
    
    const notification = document.createElement('div');
    notification.id = 'dialog-auto-handler-notification';
    notification.style.cssText = `
      position: fixed;
      bottom: 12px;
      right: 12px;
      background: linear-gradient(135deg, rgba(0,0,0,0.9), rgba(40,40,40,0.9));
      color: white;
      padding: 12px 16px;
      border-radius: 8px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      font-size: 13px;
      z-index: 2147483647;
      max-width: 400px;
      box-shadow: 0 6px 20px rgba(0,0,0,0.4);
      border: 1px solid rgba(255,255,255,0.1);
      backdrop-filter: blur(10px);
      transition: all 0.3s ease;
      opacity: 0;
      transform: translateY(20px);
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    requestAnimationFrame(() => {
      notification.style.opacity = '1';
      notification.style.transform = 'translateY(0)';
    });
    
    let countdown = delay;
    const updateNotification = () => {
      const truncatedMessage = message.length > 50 ? message.substring(0, 50) + '...' : message;
      notification.innerHTML = `
        <div style="display: flex; align-items: center; gap: 8px;">
          <div style="width: 8px; height: 8px; background: #4CAF50; border-radius: 50%; animation: pulse 2s infinite;"></div>
          <div>
            <div style="font-weight: 600; margin-bottom: 2px;">${type.toUpperCase()} Intercepted</div>
            <div style="opacity: 0.8; font-size: 11px;">"${truncatedMessage}"</div>
            <div style="opacity: 0.6; font-size: 10px; margin-top: 4px;">Auto-handled in ${countdown}s</div>
          </div>
        </div>
      `;
    };
    
    updateNotification();
    
    const interval = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(interval);
        notification.innerHTML = `
          <div style="display: flex; align-items: center; gap: 8px;">
            <div style="width: 8px; height: 8px; background: #2196F3; border-radius: 50%;"></div>
            <div style="font-weight: 600;">${type.toUpperCase()} Handled ✓</div>
          </div>
        `;
        setTimeout(() => {
          notification.style.opacity = '0';
          notification.style.transform = 'translateY(-20px)';
          setTimeout(() => {
            if (notification.parentNode) {
              notification.remove();
            }
          }, 300);
        }, 2000);
      } else {
        updateNotification();
      }
    }, 1000);
    
    // Add pulse animation if not already added
    if (!document.getElementById('dialog-handler-styles')) {
      const styles = document.createElement('style');
      styles.id = 'dialog-handler-styles';
      styles.textContent = `
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
      `;
      document.head.appendChild(styles);
    }
  }
  
  // Handle cases where document.body doesn't exist yet
  if (!document.body) {
    const bodyObserver = new MutationObserver((mutations, observer) => {
      if (document.body) {
        observer.disconnect();
        iframeObserver.observe(document.body, { childList: true, subtree: true });
      }
    });
    bodyObserver.observe(document.documentElement, { childList: true });
  }
  
  console.log('Content script loaded - Dialog auto-handler active');
})();