import { sanitizeHtml as O } from "./index-sanitize-html.js";
import { L as w } from "./index-LexicalCode.js";
import { L as k } from "./index-LexicalHtml.js";
import { L as p } from "./index-LexicalLink.js";
import { L as E } from "./index-LexicalUtils2.js";
import { L as n } from "./index-Lexical2.js";
import { L as x } from "./index-LexicalToolkit.js";
import { useState as a, useCallback as S, useEffect as d } from "react";
const b = (R) => {
  const {
    anchorElem: m,
    editor: e
  } = R, [v, u] = a(), [C, N] = a(""), [T, l] = a(!1), [f, L] = a(!1), [g, $] = a(!1), i = S(() => {
    const t = n.$getSelection(), o = window.getSelection(), s = e.getRootElement();
    if (t !== null && o !== null && !o.isCollapsed && s !== null && s.contains(o.anchorNode)) {
      const r = x.getDOMRangeRect(o, s);
      u(r);
      return;
    }
    u(void 0);
  }, [e, m, f]);
  d(() => {
    const t = m.parentElement, o = () => {
      e.getEditorState().read(() => {
        i();
      });
    };
    return window.addEventListener("resize", o), t && t.addEventListener("scroll", o), () => {
      window.removeEventListener("resize", o), t && t.removeEventListener("scroll", o);
    };
  }, [e, i, m]), d(() => (e.getEditorState().read(() => {
    i();
  }), E.mergeRegister(e.registerUpdateListener(({
    editorState: t
  }) => {
    t.read(() => {
      i();
    });
  }), e.registerCommand(n.SELECTION_CHANGE_COMMAND, () => (i(), !1), n.COMMAND_PRIORITY_LOW))), [e, i]);
  const c = S(() => {
    e.getEditorState().read(() => {
      if (e.isComposing() || g)
        return;
      const t = n.$getSelection(), o = window.getSelection(), s = e.getRootElement();
      if (o !== null && (!n.$isRangeSelection(t) || s === null || !s.contains(o.anchorNode))) {
        l(!1);
        return;
      }
      if (!n.$isRangeSelection(t))
        return;
      const r = x.getSelectedNode(t), h = r.getParent();
      if (p.$isLinkNode(h) || p.$isLinkNode(r) ? L(!0) : L(!1), !w.$isCodeHighlightNode(t.anchor.getNode()) && t.getTextContent() !== "")
        l(n.$isTextNode(r) || n.$isParagraphNode(r));
      else {
        l(!1);
        return;
      }
      const M = t.getTextContent();
      !t.isCollapsed() && M === "" && l(!1);
    });
  }, [e, g]);
  return d(() => (document.addEventListener("selectionchange", c), () => {
    document.removeEventListener("selectionchange", c);
  }), [c]), d(() => E.mergeRegister(e.registerUpdateListener(() => {
    c();
  }), e.registerRootListener(() => {
    e.getRootElement() === null && l(!1);
  }), e.registerUpdateListener(() => e.update(() => {
    const t = n.$getSelection(), o = k.$generateHtmlFromNodes(e, t), s = O(o);
    N(s);
  }))), [e, c]), {
    isMouseOver: g,
    setIsMouseOver: $,
    isLink: f,
    isText: T,
    selection: C,
    updatePosition: i,
    selectionRect: v
  };
};
export {
  b as useAiAssistantSelection
};
