import { d as DocContext, e as Context, j as jsxRuntimeExports, t as textRendererStyle, M as MathJax } from "./doenetml-cB_aZGJ5.js";
import React__default, { useRef, useContext, useEffect } from "react";
import { BoardContext, TEXT_LAYER_OFFSET } from "./graph-DQks9OE0.js";
import { u as useDoenetRenderer } from "./useDoenetRenderer-DN3Z9CW3.js";
import { P as POINTER_DRAG_THRESHOLD, g as getPositionFromAnchorByCoordinate } from "./graph-FesVg1vs.js";
import { ChoiceInputInlineContext } from "./choiceInput-sdr8Da04.js";
const math = React__default.memo(function MathComponent(props) {
  let { componentIdx, id, SVs, actions, callAction } = useDoenetRenderer(props);
  MathComponent.ignoreActionsWithoutCore = () => true;
  let mathJXG = useRef(null);
  let anchorPointJXG = useRef(null);
  let anchorRel = useRef(null);
  const board = useContext(BoardContext);
  const choiceInputInlineContext = useContext(ChoiceInputInlineContext);
  let pointerAtDown = useRef(null);
  let pointAtDown = useRef(null);
  let pointerIsDown = useRef(false);
  let pointerMovedSinceDown = useRef(false);
  let dragged = useRef(false);
  let calculatedX = useRef(null);
  let calculatedY = useRef(null);
  let lastPositionFromCore = useRef(null);
  let previousPositionFromAnchor = useRef(null);
  let fixed = useRef(false);
  let fixLocation = useRef(false);
  fixed.current = SVs.fixed;
  fixLocation.current = !SVs.draggable || SVs.fixLocation || SVs.fixed;
  const { darkMode } = useContext(DocContext) || {};
  useEffect(() => {
    return () => {
      if (mathJXG.current !== null) {
        deleteMathJXG();
      }
      if (board) {
        board.off("move", boardMoveHandler);
      }
    };
  }, []);
  useEffect(() => {
    if (board) {
      board.on("move", boardMoveHandler);
    }
  }, [board]);
  function createMathJXG() {
    if (board === null) {
      return null;
    }
    let textColor = darkMode === "dark" ? SVs.selectedStyle.textColorDarkMode : SVs.selectedStyle.textColor;
    let backgroundColor = darkMode === "dark" ? SVs.selectedStyle.backgroundColorDarkMode : SVs.selectedStyle.backgroundColor;
    let cssStyle = ``;
    if (backgroundColor) {
      cssStyle += `background-color: ${backgroundColor}`;
    }
    let jsxMathAttributes = {
      visible: !SVs.hidden,
      fixed: fixed.current,
      layer: 10 * SVs.layer + TEXT_LAYER_OFFSET,
      cssStyle,
      highlightCssStyle: cssStyle,
      strokeColor: textColor,
      strokeOpacity: 1,
      highlightStrokeColor: textColor,
      highlightStrokeOpacity: 0.5,
      highlight: !fixLocation.current,
      useMathJax: true,
      parse: false
    };
    let newAnchorPointJXG;
    try {
      let anchor = Context.fromAst(SVs.anchor);
      let anchorCoords = [
        anchor.get_component(0).evaluate_to_constant(),
        anchor.get_component(1).evaluate_to_constant()
      ];
      if (!Number.isFinite(anchorCoords[0])) {
        anchorCoords[0] = 0;
        jsxMathAttributes["visible"] = false;
      }
      if (!Number.isFinite(anchorCoords[1])) {
        anchorCoords[1] = 0;
        jsxMathAttributes["visible"] = false;
      }
      newAnchorPointJXG = board.create("point", anchorCoords, {
        visible: false
      });
    } catch (e) {
      jsxMathAttributes["visible"] = false;
      newAnchorPointJXG = board.create("point", [0, 0], {
        visible: false
      });
    }
    jsxMathAttributes.anchor = newAnchorPointJXG;
    let { anchorx, anchory } = getPositionFromAnchorByCoordinate(
      SVs.positionFromAnchor
    );
    jsxMathAttributes.anchorx = anchorx;
    jsxMathAttributes.anchory = anchory;
    anchorRel.current = [anchorx, anchory];
    let beginDelim2, endDelim2;
    if (SVs.renderMode === "inline") {
      beginDelim2 = "\\(";
      endDelim2 = "\\)";
    } else if (SVs.renderMode === "display") {
      beginDelim2 = "\\[";
      endDelim2 = "\\]";
    } else if (SVs.renderMode === "numbered") {
      beginDelim2 = `\\begin{gather}\\tag{${SVs.equationTag}}`;
      endDelim2 = "\\end{gather}";
    } else if (SVs.renderMode === "align") {
      beginDelim2 = "\\begin{align}";
      endDelim2 = "\\end{align}";
    } else {
      beginDelim2 = "\\(";
      endDelim2 = "\\)";
    }
    let newMathJXG = board.create(
      "text",
      [0, 0, beginDelim2 + SVs.latex + endDelim2],
      jsxMathAttributes
    );
    newMathJXG.isDraggable = !fixLocation.current;
    newMathJXG.on("down", function(e) {
      document.activeElement?.blur();
      pointerAtDown.current = [e.x, e.y];
      pointAtDown.current = [
        ...newAnchorPointJXG.coords.scrCoords
      ];
      dragged.current = false;
      pointerIsDown.current = true;
      pointerMovedSinceDown.current = false;
      if (!fixed.current) {
        callAction({
          action: actions.mathFocused,
          args: { componentIdx }
          // send componentIdx so get original componentIdx if adapted
        });
      }
    });
    newMathJXG.on("hit", function(e) {
      pointAtDown.current = [
        ...newAnchorPointJXG.coords.scrCoords
      ];
      dragged.current = false;
      callAction({
        action: actions.mathFocused,
        args: { componentIdx }
        // send componentIdx so get original componentIdx if adapted
      });
    });
    newMathJXG.on("up", function(e) {
      if (dragged.current) {
        callAction({
          action: actions.moveMath,
          args: {
            x: calculatedX.current,
            y: calculatedY.current
          }
        });
        dragged.current = false;
      } else if (!pointerMovedSinceDown.current && !fixed.current) {
        callAction({
          action: actions.mathClicked,
          args: { componentIdx }
          // send componentIdx so get original componentIdx if adapted
        });
      }
      pointerIsDown.current = false;
    });
    newMathJXG.on("keyfocusout", function(e) {
      if (dragged.current) {
        callAction({
          action: actions.moveMath,
          args: {
            x: calculatedX.current,
            y: calculatedY.current
          }
        });
        dragged.current = false;
      }
    });
    newMathJXG.on("drag", function(e) {
      let viaPointer = e.type === "pointermove";
      if (!viaPointer || Math.abs(e.x - pointerAtDown.current[0]) > POINTER_DRAG_THRESHOLD || Math.abs(e.y - pointerAtDown.current[1]) > POINTER_DRAG_THRESHOLD) {
        dragged.current = true;
      }
      let [xMin, yMax, xMax, yMin] = board.getBoundingBox();
      let width = newMathJXG.size[0] / board.unitX;
      let height = newMathJXG.size[1] / board.unitY;
      let anchorx2 = anchorRel.current?.[0];
      let anchory2 = anchorRel.current?.[1];
      let offsetx = 0;
      if (anchorx2 === "middle") {
        offsetx = -width / 2;
      } else if (anchorx2 === "right") {
        offsetx = -width;
      }
      let offsety = 0;
      if (anchory2 === "middle") {
        offsety = -height / 2;
      } else if (anchory2 === "top") {
        offsety = -height;
      }
      let xminAdjusted = xMin + 0.04 * (xMax - xMin) - offsetx - width;
      let xmaxAdjusted = xMax - 0.04 * (xMax - xMin) - offsetx;
      let yminAdjusted = yMin + 0.04 * (yMax - yMin) - offsety - height;
      let ymaxAdjusted = yMax - 0.04 * (yMax - yMin) - offsety;
      if (viaPointer && pointAtDown.current && pointerAtDown.current) {
        var o = board.origin.scrCoords;
        calculatedX.current = (pointAtDown.current[1] + e.x - pointerAtDown.current[0] - o[1]) / board.unitX;
        calculatedY.current = (o[2] - (pointAtDown.current[2] + e.y - pointerAtDown.current[1])) / board.unitY;
      } else {
        calculatedX.current = newAnchorPointJXG.X() + newMathJXG.relativeCoords.usrCoords[1];
        calculatedY.current = newAnchorPointJXG.Y() + newMathJXG.relativeCoords.usrCoords[2];
      }
      calculatedX.current = Math.min(
        xmaxAdjusted,
        Math.max(xminAdjusted, calculatedX.current)
      );
      calculatedY.current = Math.min(
        ymaxAdjusted,
        Math.max(yminAdjusted, calculatedY.current)
      );
      callAction({
        action: actions.moveMath,
        args: {
          x: calculatedX.current,
          y: calculatedY.current,
          transient: true,
          skippable: true
        }
      });
      newMathJXG.relativeCoords.setCoordinates(
        JXG.COORDS_BY_USER,
        [0, 0]
      );
      newAnchorPointJXG.coords.setCoordinates(
        JXG.COORDS_BY_USER,
        lastPositionFromCore.current
      );
    });
    newMathJXG.on("keydown", function(e) {
      if (e.key === "Enter") {
        if (dragged.current) {
          callAction({
            action: actions.moveMath,
            args: {
              x: calculatedX.current,
              y: calculatedY.current
            }
          });
          dragged.current = false;
        }
        callAction({
          action: actions.mathClicked,
          args: { componentIdx }
          // send componentIdx so get original componentIdx if adapted
        });
      }
    });
    mathJXG.current = newMathJXG;
    anchorPointJXG.current = newAnchorPointJXG;
    previousPositionFromAnchor.current = SVs.positionFromAnchor;
    setTimeout(() => {
      if (mathJXG.current) {
        mathJXG.current.needsUpdate = true;
        mathJXG.current.setText(beginDelim2 + SVs.latex + endDelim2);
        mathJXG.current.update();
        board.updateRenderer();
      }
    }, 1e3);
  }
  function boardMoveHandler(e) {
    if (pointerIsDown.current && pointerAtDown.current) {
      if (Math.abs(e.x - pointerAtDown.current[0]) > POINTER_DRAG_THRESHOLD || Math.abs(e.y - pointerAtDown.current[1]) > POINTER_DRAG_THRESHOLD) {
        pointerMovedSinceDown.current = true;
      }
    }
  }
  function deleteMathJXG() {
    if (!mathJXG.current) {
      return;
    }
    mathJXG.current.off("drag");
    mathJXG.current.off("down");
    mathJXG.current.off("hit");
    mathJXG.current.off("up");
    mathJXG.current.off("keyfocusout");
    mathJXG.current.off("keydown");
    board?.removeObject(mathJXG.current);
    mathJXG.current = null;
  }
  if (board) {
    let anchorCoords;
    try {
      let anchor = Context.fromAst(SVs.anchor);
      anchorCoords = [
        anchor.get_component(0).evaluate_to_constant(),
        anchor.get_component(1).evaluate_to_constant()
      ];
    } catch (e) {
      anchorCoords = [NaN, NaN];
    }
    lastPositionFromCore.current = anchorCoords;
    if (mathJXG.current === null) {
      createMathJXG();
    } else {
      mathJXG.current.relativeCoords.setCoordinates(
        JXG.COORDS_BY_USER,
        [0, 0]
      );
      anchorPointJXG.current?.coords.setCoordinates(
        JXG.COORDS_BY_USER,
        anchorCoords
      );
      let beginDelim2, endDelim2;
      if (SVs.renderMode === "inline") {
        beginDelim2 = "\\(";
        endDelim2 = "\\)";
      } else if (SVs.renderMode === "display") {
        beginDelim2 = "\\[";
        endDelim2 = "\\]";
      } else if (SVs.renderMode === "numbered") {
        beginDelim2 = `\\begin{gather}\\tag{${SVs.equationTag}}`;
        endDelim2 = "\\end{gather}";
      } else if (SVs.renderMode === "align") {
        beginDelim2 = "\\begin{align}";
        endDelim2 = "\\end{align}";
      } else {
        beginDelim2 = "\\(";
        endDelim2 = "\\)";
      }
      mathJXG.current.setText(beginDelim2 + SVs.latex + endDelim2);
      let visible = !SVs.hidden;
      if (Number.isFinite(anchorCoords[0]) && Number.isFinite(anchorCoords[1])) {
        let actuallyChangedVisibility = mathJXG.current.visProp["visible"] !== visible;
        mathJXG.current.visProp["visible"] = visible;
        mathJXG.current.visPropCalc["visible"] = visible;
        if (actuallyChangedVisibility) {
          mathJXG.current.setAttribute({ visible });
        }
      } else {
        mathJXG.current.visProp["visible"] = false;
        mathJXG.current.visPropCalc["visible"] = false;
      }
      let layer = 10 * SVs.layer + TEXT_LAYER_OFFSET;
      let layerChanged = mathJXG.current.visProp.layer !== layer;
      if (layerChanged) {
        mathJXG.current.setAttribute({ layer });
      }
      let textColor = darkMode === "dark" ? SVs.selectedStyle.textColorDarkMode : SVs.selectedStyle.textColor;
      let backgroundColor = darkMode === "dark" ? SVs.selectedStyle.backgroundColorDarkMode : SVs.selectedStyle.backgroundColor;
      let cssStyle = ``;
      if (backgroundColor) {
        cssStyle += `background-color: ${backgroundColor}`;
      } else {
        cssStyle += `background-color: transparent`;
      }
      if (mathJXG.current.visProp.strokecolor !== textColor) {
        mathJXG.current.visProp.strokecolor = textColor;
        mathJXG.current.visProp.highlightstrokecolor = textColor;
      }
      if (mathJXG.current.visProp.cssstyle !== cssStyle) {
        mathJXG.current.visProp.cssstyle = cssStyle;
        mathJXG.current.visProp.highlightcssstyle = cssStyle;
      }
      mathJXG.current.visProp.highlight = !fixLocation.current;
      mathJXG.current.visProp.fixed = fixed.current;
      mathJXG.current.isDraggable = !fixLocation.current;
      mathJXG.current.needsUpdate = true;
      if (SVs.positionFromAnchor !== previousPositionFromAnchor.current) {
        let { anchorx, anchory } = getPositionFromAnchorByCoordinate(
          SVs.positionFromAnchor
        );
        mathJXG.current.visProp.anchorx = anchorx;
        mathJXG.current.visProp.anchory = anchory;
        anchorRel.current = [anchorx, anchory];
        previousPositionFromAnchor.current = SVs.positionFromAnchor;
        mathJXG.current.fullUpdate();
      } else {
        mathJXG.current.update();
      }
      if (anchorPointJXG.current) {
        anchorPointJXG.current.needsUpdate = true;
        anchorPointJXG.current.update();
      }
      board.updateRenderer();
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { id });
  }
  if (SVs.hidden) {
    return null;
  }
  let beginDelim, endDelim;
  if (SVs.renderMode === "inline") {
    beginDelim = "\\(";
    endDelim = "\\)";
  } else if (SVs.renderMode === "display") {
    beginDelim = "\\[";
    endDelim = "\\]";
  } else if (SVs.renderMode === "numbered") {
    beginDelim = `\\begin{gather}\\tag{${SVs.equationTag}}`;
    endDelim = "\\end{gather}";
  } else if (SVs.renderMode === "align") {
    beginDelim = "\\begin{align}";
    endDelim = "\\end{align}";
  } else {
    beginDelim = "\\(";
    endDelim = "\\)";
  }
  let latexWithDelims = beginDelim + SVs.latex + endDelim;
  let anchors = [];
  if (SVs.mrowChildRendererIds) {
    anchors.push(
      ...SVs.mrowChildRendererIds.map((rowId) => {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { id: rowId }, rowId);
      })
    );
  }
  const style = !choiceInputInlineContext.inOption ? textRendererStyle(darkMode, SVs.selectedStyle) : void 0;
  const hideUntilTypeset = !choiceInputInlineContext.isHidden ? "first" : void 0;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    anchors,
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style, id, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MathJax, { hideUntilTypeset, inline: true, dynamic: true, children: latexWithDelims }) })
  ] });
});
export {
  math as default
};
