(function () {
  // Set up logging bridge to Objective-C with fallback to console
  const log = (message) => {
    // Try to send to Objective-C first (legacy WebView approach)
    if (window.contentExtractor && window.contentExtractor.log) {
      try {
        window.contentExtractor.log(message);
      } catch (e) {
        console.log("[Content Extractor JS] " + message);
      }
    } else {
      console.log("[Content Extractor JS] " + message);
    }
  };

  // Test the bridge with a simple message first
  log("BRIDGE_TEST_MESSAGE");
  log("=== Content extraction started ===");

  // State variables for content selection
  let isSelecting = false;
  let selectedElement = null;
  let hoveredElement = null;
  let originalStyles = new Map();
  let isCommandHeld = false;

  function clearHoverHighlight() {
    if (hoveredElement && hoveredElement !== selectedElement) {
      if (originalStyles.has(hoveredElement)) {
        const styles = originalStyles.get(hoveredElement);
        hoveredElement.style.outline = styles.outline;
        hoveredElement.style.backgroundColor = styles.backgroundColor;
        originalStyles.delete(hoveredElement);
      }
    }
    hoveredElement = null;
  }

  function clearSelection() {
    if (selectedElement) {
      if (originalStyles.has(selectedElement)) {
        const styles = originalStyles.get(selectedElement);
        selectedElement.style.outline = styles.outline;
        selectedElement.style.backgroundColor = styles.backgroundColor;
        originalStyles.delete(selectedElement);
      }
    }
    selectedElement = null;
  }

  function isCommandKeyHeld(event) {
    return event && (event.metaKey || event.ctrlKey);
  }

  function saveOriginalStyles(element) {
    if (!originalStyles.has(element)) {
      originalStyles.set(element, {
        outline: element.style.outline,
        backgroundColor: element.style.backgroundColor,
      });
    }
  }

  function findBestContentContainer(target) {
    if (
      window.__mkSelectionShared &&
      window.__mkSelectionShared.findBestContentContainer
    ) {
      return window.__mkSelectionShared.findBestContentContainer(target);
    }
    return document.body;
  }

  document.addEventListener("mouseover", function (e) {
    if (isSelecting) {
      clearHoverHighlight();
      if (e.target !== selectedElement) {
        const contentElement = findBestContentContainer(e.target);
        hoveredElement = contentElement;
        saveOriginalStyles(hoveredElement);
        hoveredElement.style.outline = "1px solid #007AFF";
        hoveredElement.style.backgroundColor = "rgba(0, 122, 255, 0.05)";
      }
    }
  });

  document.addEventListener("mouseout", function (e) {
    if (isSelecting && e.target === hoveredElement) {
      clearHoverHighlight();
    }
  });

  // Global listeners to toggle selection/navigation with Command key
  document.addEventListener("keydown", function (event) {
    if (isCommandKeyHeld(event) && !isCommandHeld) {
      isCommandHeld = true;
      // No-op UI change here; shared status bar handles messaging
    }
  });

  document.addEventListener("keyup", function (event) {
    if (!isCommandKeyHeld(event) && isCommandHeld) {
      isCommandHeld = false;
    }
  });

  document.addEventListener("click", function (e) {
    if (isSelecting) {
      // Allow normal navigation when Command is held (Cmd+Click)
      if (isCommandHeld) {
        log("Command held on click - allowing normal navigation");
        return;
      }
      // Check if the clicked element is a form element or interactive element
      const interactiveElements = [
        "BUTTON",
        "INPUT",
        "SELECT",
        "TEXTAREA",
        "A",
        "LABEL",
      ];
      const isInteractiveElement = interactiveElements.includes(
        e.target.tagName
      );

      // Check if the clicked element has clickable attributes
      const hasClickableAttributes =
        e.target.hasAttribute("onclick") ||
        e.target.hasAttribute("href") ||
        e.target.type === "button" ||
        e.target.type === "submit" ||
        e.target.type === "reset";

      if (isInteractiveElement || hasClickableAttributes) {
        log(
          `Clicked interactive element (${e.target.tagName}), allowing normal behavior`
        );
        return; // Allow normal click behavior for form elements
      }

      e.preventDefault();
      e.stopPropagation();
      clearHoverHighlight();
      clearSelection();

      const contentElement = findBestContentContainer(e.target);
      selectedElement = contentElement;
      saveOriginalStyles(selectedElement);
      selectedElement.style.outline = "2px solid #007AFF";
      selectedElement.style.backgroundColor = "rgba(0, 122, 255, 0.1)";

      // Temporarily disable CSS to prevent background images from causing crashes
      const stylesheets = document.querySelectorAll(
        'link[rel="stylesheet"], style'
      );
      for (let i = 0; i < stylesheets.length; i++) {
        stylesheets[i].disabled = true;
      }

      const html = selectedElement.outerHTML;
      log(`Selected element HTML length: ${html.length}`);

      // Re-enable CSS after HTML extraction
      for (let i = 0; i < stylesheets.length; i++) {
        stylesheets[i].disabled = false;
      }
      log(`Selected element tag: ${selectedElement.tagName}`);
      log(`Selected element class: ${selectedElement.className}`);
      log(
        `Selected element children count: ${selectedElement.children.length}`
      );
      log(
        `Selected element text content length: ${selectedElement.textContent.length}`
      );
      log(
        `Selected element innerHTML length: ${selectedElement.innerHTML.length}`
      );
      log(
        `Content element found by smart selection: ${
          contentElement !== e.target
        }`
      );

      // Log HTML structure details
      log(`HTML starts with: ${html.substring(0, 100)}`);
      log(`HTML ends with: ${html.substring(Math.max(0, html.length - 100))}`);
      log(
        `HTML contains closing tag: ${html.includes(
          "</" + selectedElement.tagName.toLowerCase() + ">"
        )}`
      );

      // Check for common content patterns
      const hasParagraphs = html.includes("<p>") || html.includes("<P>");
      const hasHeadings =
        html.includes("<h1>") || html.includes("<h2>") || html.includes("<h3>");
      const hasLinks = html.includes("<a ");
      const hasImages = html.includes("<img ");

      log(
        `Content analysis - Paragraphs: ${hasParagraphs}, Headings: ${hasHeadings}, Links: ${hasLinks}, Images: ${hasImages}`
      );

      if (window.contentExtractor && window.contentExtractor.contentSelected) {
        log("Calling contentExtractor.contentSelected bridge function");
        window.contentExtractor.contentSelected({
          html: html,
          tagName: selectedElement.tagName,
          className: selectedElement.className,
          id: selectedElement.id,
        });
      } else {
        log("contentExtractor.contentSelected bridge function not available");
      }
    }
  });

  function enableSelection() {
    isSelecting = true;
    log("Content selection enabled");
  }

  function disableSelection() {
    isSelecting = false;
    clearHoverHighlight();
    clearSelection();
    log("Content selection disabled");
  }

  // Expose functions to be called from Objective-C
  window.enableContentSelection = enableSelection;
  window.disableContentSelection = disableSelection;

  // Don't automatically start selection - wait for the page to be loaded
  // The selection will be started by the Objective-C code when needed
  log("Content extractor script loaded and ready");
})();
