/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The require scope
/******/ 	var __webpack_require__ = {};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
/*!*********************************!*\
  !*** ./extension/js/content.js ***!
  \*********************************/
__webpack_require__.r(__webpack_exports__);
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
// js/content.js
// This is the main content script for the Anotato extension.
// It handles highlighting, clicking, and instant updates.

console.log("Anotato content script loaded!");

// --- Module-level variables ---
var currentAnnotationData = [];
var currentUrlId = '';
var observer; // For the MutationObserver to handle dynamic content

/**
 * Finds text nodes matching anchors and highlights them *within a specific HTML element*.
 *
 * @param {Node} targetNode - The HTML element to search within (e.g., document.body).
 * @param {Array} annotationData - The array of annotation objects.
 * @param {string} urlId - The unique ID for the current URL.
 */
function highlightNode(targetNode, annotationData, urlId) {
  // We only want to scan valid HTML elements
  if (!targetNode || targetNode.nodeType !== Node.ELEMENT_NODE || typeof targetNode.querySelectorAll === 'undefined') {
    return;
  }

  // Disconnect the observer *before* we make changes to the DOM
  // to prevent infinite loops.
  if (observer) {
    observer.disconnect();
  }
  var instance = new Mark(targetNode);

  // --- FIX: Clear existing highlights first ---
  // We wait for unmark to FINISH before drawing new ones.
  instance.unmark({
    className: 'anotato-highlight-class',
    done: function done() {
      // Only draw new marks after old ones are gone
      annotationData.forEach(function (item) {
        var searchText = item.anchor.anchorText;
        if (searchText) {
          instance.mark(searchText, {
            element: 'anotato-highlight',
            className: 'anotato-highlight-class',
            separateWordSearch: false,
            acrossElements: true,
            each: function each(element) {
              element.dataset.urlId = urlId;
              element.dataset.anchorId = item.anchor.id;
              element.dataset.anchorText = item.anchor.anchorText;
              element.dataset.annotations = JSON.stringify(item.annotations);
            }
          });
        }
      });
    }
  });

  // --- Consolidate nested highlights ---
  // This logic merges annotations if one highlight is inside another.
  var nestedHighlights = targetNode.querySelectorAll('anotato-highlight anotato-highlight');
  nestedHighlights.forEach(function (nestedEl) {
    var parentEl = nestedEl.closest('anotato-highlight');
    if (parentEl && parentEl !== nestedEl) {
      try {
        var parentData = JSON.parse(parentEl.dataset.annotations || '[]');
        var nestedData = JSON.parse(nestedEl.dataset.annotations || '[]');

        // Merge data (avoiding duplicates)
        nestedData.forEach(function (nestedAnno) {
          if (!parentData.some(function (parentAnno) {
            return parentAnno.id === nestedAnno.id;
          })) {
            parentData.push(nestedAnno);
          }
        });

        // Save merged data to parent
        parentEl.dataset.annotations = JSON.stringify(parentData);

        // Unwrap the inner highlight visually
        var parent = nestedEl.parentNode;
        while (nestedEl.firstChild) {
          parent.insertBefore(nestedEl.firstChild, nestedEl);
        }
        parent.removeChild(nestedEl);
      } catch (e) {
        console.error("Error consolidating highlights:", e);
      }
    }
  });

  // Re-connect the observer *after* we are finished making changes.
  startObserver();
}

/**
 * Click listener to open the viewer.
 * It handles the logic for preventing conflicts with text selection.
 */
document.body.addEventListener('click', function (event) {
  // 1. Check if user is selecting text (dragging)
  var selection = window.getSelection();
  if (!selection.isCollapsed) return;

  // 2. Check if it's a Left Click
  if (event.button !== 0) return;

  // 3. Check if they clicked a highlight
  var clickedElement = event.target.closest('anotato-highlight');
  if (!clickedElement) return;

  // 4. Merge all annotations for nested highlights (Logic to find all parents)
  var allAnnotations = [];
  var allAnchorIds = [];
  var annotationMap = new Map();
  try {
    // Get data from clicked element
    var clickedData = JSON.parse(clickedElement.dataset.annotations || '[]');
    clickedData.forEach(function (anno) {
      return annotationMap.set(anno.id, anno);
    });
    allAnchorIds.push(clickedElement.dataset.anchorId);

    // Traverse up to find any parent highlights
    var parentElement = clickedElement.parentElement.closest('anotato-highlight');
    while (parentElement) {
      var parentData = JSON.parse(parentElement.dataset.annotations || '[]');
      parentData.forEach(function (anno) {
        return annotationMap.set(anno.id, anno);
      });
      allAnchorIds.push(parentElement.dataset.anchorId);
      parentElement = parentElement.parentElement.closest('anotato-highlight');
    }
  } catch (e) {
    console.error("Error parsing highlight data:", e);
  }
  allAnnotations = Array.from(annotationMap.values());

  // Open the viewer with the collected data
  chrome.runtime.sendMessage({
    type: 'openAnnotationViewer',
    target: 'background',
    data: {
      urlId: clickedElement.dataset.urlId,
      anchorId: allAnchorIds[0],
      anchorText: clickedElement.dataset.anchorText,
      annotations: JSON.stringify(allAnnotations)
    }
  });
});

// --- MutationObserver ---
// Handles dynamic content loading (like infinite scrolls)
var observerCallback = function observerCallback(mutationsList) {
  var _iterator = _createForOfIteratorHelper(mutationsList),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var mutation = _step.value;
      if (mutation.type === 'childList') {
        mutation.addedNodes.forEach(function (node) {
          highlightNode(node, currentAnnotationData, currentUrlId);
        });
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
};
function startObserver() {
  if (!observer) {
    observer = new MutationObserver(observerCallback);
  }
  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
}

// --- CORE: Fetch and Highlight Logic ---
// We wrapped this in a function so it can be called on load AND on update.
function loadAnnotations() {
  var currentUrl = window.location.href;

  // Check if extension is Active (Toggle Switch)
  chrome.storage.local.get(['isActive'], function (result) {
    var isActive = result.isActive !== false;
    if (isActive) {
      // Fetch annotations from backend
      chrome.runtime.sendMessage({
        type: "getAnnotationsForUrl",
        target: "background",
        data: {
          url: currentUrl
        }
      }, function (response) {
        if (chrome.runtime.lastError) return;
        if (response && response.success && response.data.length > 0) {
          currentAnnotationData = response.data;
          currentUrlId = response.urlId;
          highlightNode(document.body, currentAnnotationData, currentUrlId);
        } else if (response && !response.success) {
          console.error("Anotato Error:", response.error);
        }
      });
    } else {
      console.log("Anotato is inactive. Highlighting disabled.");
    }
  });
}

// --- NEW: Listener for Instant Updates ---
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  // Listen for the standard refresh OR our new report signal
  if (message.type === 'REFRESH_ANNOTATIONS' || message.action === 'reportSubmittedSuccessfully') {
    console.log("Anotato: Received state change signal. Reloading highlights in background...");
    loadAnnotations();
  }
});

// --- Initial Execution ---
// Run immediately when page loads
loadAnnotations();
/******/ })()
;
//# sourceMappingURL=content.js.map