/* eslint-disable */
// scroll-into-view-helper.js
// This script is injected into the page to handle scroll into view operations

if (window.__SCROLL_INTO_VIEW_HELPER_INITIALIZED__) {
  // Already initialized, skip
} else {
  window.__SCROLL_INTO_VIEW_HELPER_INITIALIZED__ = true;

  /**
   * Scroll an element into view with specified options
   * @param {string} selector - CSS selector for the element to scroll into view
   * @param {string} behavior - Scroll behavior: 'auto' or 'smooth'
   * @param {string} block - Vertical alignment: 'start', 'center', 'end', 'nearest'
   * @param {string} inline - Horizontal alignment: 'start', 'center', 'end', 'nearest'
   * @returns {Promise<Object>} - Result of the scroll into view operation
   */
  async function scrollElementIntoView(
    selector,
    behavior = 'smooth',
    block = 'center',
    inline = 'center',
  ) {
    try {
      // Find the element
      const element = document.querySelector(selector);
      if (!element) {
        return {
          error: `Element with selector "${selector}" not found`,
        };
      }

      // Get element information before scrolling
      const rect = element.getBoundingClientRect();
      const elementInfo = {
        tagName: element.tagName,
        id: element.id,
        className: element.className,
        text: element.textContent?.trim().substring(0, 100) || '',
        isVisible: isElementVisible(element),
        rect: {
          x: rect.x,
          y: rect.y,
          width: rect.width,
          height: rect.height,
          top: rect.top,
          right: rect.right,
          bottom: rect.bottom,
          left: rect.left,
        },
      };

      // Check if element is visible
      if (!elementInfo.isVisible) {
        console.warn(
          `Element with selector "${selector}" is not visible, but attempting to scroll anyway`,
        );
      }

      // Store position before scrolling
      const previousPosition = {
        elementRect: { ...rect },
        scrollX: window.scrollX,
        scrollY: window.scrollY,
      };

      // Check if element is already in view
      const isInView = isElementInViewport(element);

      if (isInView) {
        return {
          success: true,
          message: 'Element is already in view',
          elementInfo,
          scrolled: false,
          previousPosition,
          currentPosition: previousPosition,
        };
      }

      // Scroll element into view
      element.scrollIntoView({
        behavior: behavior,
        block: block,
        inline: inline,
      });

      // Wait a moment for scroll to complete (especially for smooth scrolling)
      await new Promise((resolve) => setTimeout(resolve, behavior === 'smooth' ? 500 : 100));

      // Get position after scrolling
      const newRect = element.getBoundingClientRect();
      const currentPosition = {
        elementRect: {
          x: newRect.x,
          y: newRect.y,
          width: newRect.width,
          height: newRect.height,
          top: newRect.top,
          right: newRect.right,
          bottom: newRect.bottom,
          left: newRect.left,
        },
        scrollX: window.scrollX,
        scrollY: window.scrollY,
      };

      return {
        success: true,
        message: 'Element scrolled into view successfully',
        elementInfo: {
          ...elementInfo,
          rect: currentPosition.elementRect, // Update with new position
        },
        scrolled: true,
        previousPosition,
        currentPosition,
      };
    } catch (error) {
      return {
        error: `Error scrolling element into view: ${error.message}`,
      };
    }
  }

  /**
   * Check if an element is visible
   * @param {Element} element - The element to check
   * @returns {boolean} - Whether the element is visible
   */
  function isElementVisible(element) {
    if (!element) return false;

    const style = window.getComputedStyle(element);
    if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
      return false;
    }

    const rect = element.getBoundingClientRect();
    if (rect.width === 0 || rect.height === 0) {
      return false;
    }

    return true;
  }

  /**
   * Check if an element is in the viewport
   * @param {Element} element - The element to check
   * @returns {boolean} - Whether the element is in viewport
   */
  function isElementInViewport(element) {
    if (!element) return false;

    const rect = element.getBoundingClientRect();

    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

  // Listen for messages from the extension
  chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
    if (request.action === 'scrollIntoView') {
      scrollElementIntoView(request.selector, request.behavior, request.block, request.inline)
        .then(sendResponse)
        .catch((error) => {
          sendResponse({
            error: `Unexpected error: ${error.message}`,
          });
        });
      return true; // Indicates async response
    } else if (request.action === 'chrome_scroll_into_view_ping') {
      sendResponse({ status: 'pong' });
      return false;
    }
  });
}
