"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var suggestion_popover_exports = {};
__export(suggestion_popover_exports, {
  SuggestionPopover: () => SuggestionPopover
});
module.exports = __toCommonJS(suggestion_popover_exports);
var import_react_dom = require("@floating-ui/react-dom");
var import_react = __toESM(require("react"));
var import_react_dom2 = __toESM(require("react-dom"));
var import_ricos_context = require("./../ricos-context/index.js");
var import_v1 = require("./../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_tiptap = require("./../tiptap/index.js");
const SUGGESTION_OFFSET = 8;
const BUBBLE_DIMENSIONS = 32;
const SUGGESTION_OFFSET_MOBILE = 8;
const SuggestionPopover = ({
  suggestion,
  onClick,
  Component,
  getPortalElement
}) => {
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const portal = getPortalElement();
  const [minimized, setMinimized] = (0, import_react.useState)(false);
  const [isHovered, setIsHovered] = (0, import_react.useState)(false);
  const { isMobile } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const referenceElementLineHeight = (0, import_react.useMemo)(() => {
    let parsedLineHeight = 24;
    try {
      const doc2 = adapter.tiptapEditor.state.doc;
      const fromNode2 = (0, import_tiptap.findChildren)(doc2, (node) => node.attrs.id === suggestion.range.from)[0];
      if (!fromNode2) {
        return parsedLineHeight;
      }
      const fromDomNode = adapter.tiptapEditor.view.nodeDOM(fromNode2.pos);
      if (fromNode2.node.type.name === import_v1.Node_Type.TABLE && fromDomNode?.firstChild) {
        parsedLineHeight = 90;
      } else if (fromDomNode) {
        parsedLineHeight = parseInt(
          window.getComputedStyle(fromDomNode).getPropertyValue("line-height")
        );
      }
    } catch (e) {
      console.log("Failed to calculate line height", e);
    }
    return parsedLineHeight;
  }, []);
  const {
    x,
    y,
    isPositioned,
    refs: { setReference, setFloating },
    strategy
  } = (0, import_react_dom.useFloating)({
    placement: "left-start",
    strategy: portal ? "fixed" : "absolute",
    middleware: [
      (0, import_react_dom.hide)({ strategy: "referenceHidden" }),
      (0, import_react_dom.offset)(({ elements, rects }) => {
        if (isMobile) {
          const editor = adapter.tiptapEditor.view.dom;
          const editorBoundingRect = editor.getBoundingClientRect();
          const refEl2 = elements.reference;
          const refBoundingRect = refEl2.getBoundingClientRect();
          const offset2 = editorBoundingRect.left === refBoundingRect.left ? 0 : editorBoundingRect.left - refBoundingRect.left;
          return {
            mainAxis: rects.floating.width * -1 - SUGGESTION_OFFSET_MOBILE - offset2,
            crossAxis: (BUBBLE_DIMENSIONS - referenceElementLineHeight) * -1 / 2
          };
        }
        const refEl = elements.reference;
        const refForDimensions = refEl.querySelector(`[data-breakout="normal"]`) ?? refEl;
        const computedStyles = window.getComputedStyle(refForDimensions);
        const maybeRefPadding = parseInt(computedStyles.getPropertyValue("padding-inline-start"));
        const maybeRefMargin = parseInt(computedStyles.getPropertyValue("margin-inline-start"));
        const refMargin = isNaN(maybeRefMargin) ? 0 : maybeRefMargin;
        const refPadding = isNaN(maybeRefPadding) ? 0 : maybeRefPadding;
        const refSpacing = refMargin * -1 + refPadding;
        return {
          mainAxis: rects.floating.width * -1 + BUBBLE_DIMENSIONS + (refSpacing * -1 + SUGGESTION_OFFSET),
          crossAxis: (BUBBLE_DIMENSIONS - referenceElementLineHeight) * -1 / 2
        };
      })
    ],
    whileElementsMounted: (referenceEl, floatingEl, update) => (0, import_react_dom.autoUpdate)(referenceEl, floatingEl, update, {
      animationFrame: true
    })
  });
  const doc = adapter.tiptapEditor.state.doc;
  const fromNode = (0, import_tiptap.findChildren)(doc, (node) => node.attrs.id === suggestion.range.from)[0];
  const referenceElement = fromNode ? adapter.tiptapEditor.view.nodeDOM(fromNode.pos) : null;
  (0, import_react.useEffect)(() => {
    setReference(
      referenceElement?.querySelector(`[id="${suggestion.range.from}"]`) ?? referenceElement
    );
  }, [setReference, referenceElement]);
  const handleMouseEnter = () => {
    setIsHovered(true);
    setMinimized(false);
  };
  const handleMouseLeave = () => {
    setIsHovered(false);
    setMinimized(true);
  };
  const handleBlur = () => {
    !isHovered && setMinimized(true);
  };
  if (!referenceElement) {
    return null;
  }
  const content = /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: (ref) => {
        setFloating(ref);
      },
      style: {
        top: y ?? "",
        left: x ?? "",
        width: `${BUBBLE_DIMENSIONS}px`,
        height: `${BUBBLE_DIMENSIONS}px`,
        position: strategy,
        display: "block",
        visibility: isPositioned ? "visible" : "hidden",
        scale: "var(--reverse-zoom-ratio)",
        zIndex: "var(--ricos-internal-suggestion-z-index)"
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          position: "absolute",
          top: 0,
          left: 0
        },
        onMouseEnter: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        onBlur: handleBlur
      },
      /* @__PURE__ */ import_react.default.createElement(Component, { minimized, onClick, title: suggestion.summary })
    )
  );
  return portal ? import_react_dom2.default.createPortal(content, portal) : content;
};
//# sourceMappingURL=suggestion-popover.js.map
