(function () {
  if (window.__mkSharedSelectionInstalled) return;
  window.__mkSharedSelectionInstalled = true;

  const log = (msg) => {
    try {
      console.log("[SharedSelection] " + msg);
    } catch (e) {}
  };

  const isContainerTag = (el) => {
    if (!el || !el.tagName) return false;
    const t = el.tagName.toUpperCase();
    return (
      t === "ARTICLE" ||
      t === "MAIN" ||
      t === "SECTION" ||
      t === "DIV" ||
      t === "BODY"
    );
  };

  function findNearestContainer(element) {
    let current = element;
    while (current) {
      if (isContainerTag(current)) return current;
      current = current.parentElement;
    }
    return null;
  }

  function findBestContentContainer(target) {
    let current = target;
    while (current && current !== document.documentElement) {
      if (isContainerTag(current)) return current;
      current = current.parentElement;
    }
    return document.body;
  }

  function setupSharedSelectionAPI() {
    window.__mkSelectionShared = {
      isContainerTag,
      findNearestContainer,
      findBestContentContainer,
    };
    log("Shared selection API installed");
  }

  setupSharedSelectionAPI();
})();
