// PhishProtect Evidence: Frame Context Collector
// Runs in each frame's content script context (loaded at document_idle)
// Collects frame dimensions, child iframe rects, and computed styles

(function() {
  'use strict';

  /**
   * Collect context about this frame and its child iframes.
   * Sends a frame_context_report message to background.
   */
  function collectFrameContext() {
    const report = {
      frameUrl: window.location.href,
      isTopFrame: window === window.top,
      documentTitle: document.title || null,
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight
      },
      childIframes: []
    };

    // Enumerate child <iframe> elements in this frame
    const iframes = document.querySelectorAll('iframe');
    for (const iframe of iframes) {
      const rect = iframe.getBoundingClientRect();
      const styles = window.getComputedStyle(iframe);
      const parentArea = report.viewport.width * report.viewport.height;
      const iframeArea = rect.width * rect.height;

      report.childIframes.push({
        src: iframe.src || null,
        name: iframe.name || null,
        id: iframe.id || null,
        sandbox: iframe.sandbox ? iframe.sandbox.value : null,
        allow: iframe.allow || null,
        dimensions: {
          x: Math.round(rect.x),
          y: Math.round(rect.y),
          width: Math.round(rect.width),
          height: Math.round(rect.height)
        },
        displayRatio: parentArea > 0 ? +(iframeArea / parentArea).toFixed(4) : 0,
        computedStyles: {
          opacity: styles.opacity,
          zIndex: styles.zIndex,
          position: styles.position,
          visibility: styles.visibility,
          pointerEvents: styles.pointerEvents,
          display: styles.display
        }
      });
    }

    // Send to background
    try {
      chrome.runtime.sendMessage({
        type: 'frame_context_report',
        data: report
      }).catch(() => {});
    } catch (e) {
      // Extension context may be invalidated
    }
  }

  // Collect immediately (this script runs at document_idle, so DOM is ready)
  collectFrameContext();

  // Respond to on-demand collection requests from background
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'collect_evidence') {
      collectFrameContext();
      sendResponse({ ok: true });
      return true;
    }
  });
})();
