import { e as Context, j as jsxRuntimeExports, M as MathJax, T as ToggleButton } from "./doenetml-BPsLSRHD.js";
import React__default, { useState, useRef, useContext, useEffect } from "react";
import { u as useDoenetRenderer } from "./useDoenetRenderer-BDC0Rur_.js";
import { BoardContext } from "./graph-BgpHyjPe.js";
import { g as getPositionFromAnchorByCoordinate, P as POINTER_DRAG_THRESHOLD } from "./graph-FesVg1vs.js";
import { c as calculateValidationState, u as useSubmitActionWithDelay, a as createCheckWorkComponent } from "./useSubmitActionWithDelay-bJj16Fl0.js";
import { D as DescriptionPopover } from "./Description-D-NiLUUD.js";
const booleanInput = React__default.memo(function BooleanInput(props) {
  let { id, SVs, children, actions, ignoreUpdate, callAction } = useDoenetRenderer(props);
  BooleanInput.baseStateVariable = "value";
  BooleanInput.ignoreActionsWithoutCore = (actionName) => actionName === "moveInput";
  const [rendererValue, setRendererValue] = useState(SVs.value);
  let rendererValueRef = useRef(null);
  rendererValueRef.current = rendererValue;
  let valueWhenSetState = useRef(null);
  let inputJXG = useRef(null);
  let anchorPointJXG = useRef(null);
  let anchorRel = useRef(null);
  const board = useContext(BoardContext);
  let pointerAtDown = useRef(null);
  let pointAtDown = useRef(null);
  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);
  let inputRef = useRef(null);
  fixed.current = SVs.fixed;
  fixLocation.current = !SVs.draggable || SVs.fixLocation || SVs.fixed;
  useEffect(() => {
    return () => {
      if (inputJXG.current !== null) {
        deleteInputJXG();
      }
    };
  }, []);
  if (!ignoreUpdate && valueWhenSetState.current !== SVs.value) {
    setRendererValue(SVs.value);
    valueWhenSetState.current = SVs.value;
  } else {
    valueWhenSetState.current = null;
  }
  function onChangeHandler() {
    let newValue = !rendererValueRef.current;
    setRendererValue(newValue);
    valueWhenSetState.current = SVs.value;
    callAction({
      action: actions.updateBoolean,
      args: {
        boolean: newValue
      },
      baseVariableValue: newValue
    });
  }
  function onFocusChanged(focused) {
    callAction({
      action: actions.focusChanged,
      args: { focused }
    });
  }
  function createInputJXG() {
    if (board === null) {
      return null;
    }
    let jsxInputAttributes = {
      visible: !SVs.hidden,
      fixed: fixed.current,
      disabled: SVs.disabled,
      checked: rendererValue,
      useMathJax: SVs.labelHasLatex,
      strokeColor: "var(--canvasText)",
      highlightStrokeColor: "var(--canvasText)",
      highlight: !fixLocation.current,
      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;
        jsxInputAttributes["visible"] = false;
      }
      if (!Number.isFinite(anchorCoords[1])) {
        anchorCoords[1] = 0;
        jsxInputAttributes["visible"] = false;
      }
      newAnchorPointJXG = board.create("point", anchorCoords, {
        visible: false
      });
    } catch (e) {
      jsxInputAttributes["visible"] = false;
      newAnchorPointJXG = board.create("point", [0, 0], {
        visible: false
      });
      return;
    }
    jsxInputAttributes.anchor = newAnchorPointJXG;
    let { anchorx, anchory } = getPositionFromAnchorByCoordinate(
      SVs.positionFromAnchor
    );
    jsxInputAttributes.anchorx = anchorx;
    jsxInputAttributes.anchory = anchory;
    anchorRel.current = [anchorx, anchory];
    let newInputJXG = board.create(
      "checkbox",
      [0, 0, SVs.label],
      jsxInputAttributes
    );
    newInputJXG.rendNodeCheckbox.addEventListener(
      "change",
      onChangeHandler
    );
    newInputJXG.isDraggable = !fixLocation.current;
    newInputJXG.on("down", function(e) {
      document.activeElement?.blur();
      pointerAtDown.current = [e.x, e.y];
      pointAtDown.current = [
        ...newAnchorPointJXG.coords.scrCoords
      ];
      dragged.current = false;
    });
    newInputJXG.on("hit", function(e) {
      dragged.current = false;
    });
    newInputJXG.on("up", function(e) {
      if (dragged.current) {
        callAction({
          action: actions.moveInput,
          args: {
            x: calculatedX.current,
            y: calculatedY.current
          }
        });
        dragged.current = false;
      }
    });
    newInputJXG.on("keyfocusout", function(e) {
      if (dragged.current) {
        callAction({
          action: actions.moveInput,
          args: {
            x: calculatedX.current,
            y: calculatedY.current
          }
        });
        dragged.current = false;
      }
    });
    newInputJXG.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 = newInputJXG.size[0] / board.unitX;
      let height = newInputJXG.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() + newInputJXG.relativeCoords.usrCoords[1];
        calculatedY.current = newAnchorPointJXG.Y() + newInputJXG.relativeCoords.usrCoords[2];
      }
      calculatedX.current = Math.min(
        xmaxAdjusted,
        Math.max(xminAdjusted, calculatedX.current || 0)
      );
      calculatedY.current = Math.min(
        ymaxAdjusted,
        Math.max(yminAdjusted, calculatedY.current || 0)
      );
      callAction({
        action: actions.moveInput,
        args: {
          x: calculatedX.current,
          y: calculatedY.current,
          transient: true,
          skippable: true
        }
      });
      newInputJXG.relativeCoords.setCoordinates(
        JXG.COORDS_BY_USER,
        [0, 0]
      );
      newAnchorPointJXG.coords.setCoordinates(
        JXG.COORDS_BY_USER,
        lastPositionFromCore.current
      );
    });
    newInputJXG.on("keydown", function(e) {
      if (e.key === "Enter") {
        if (dragged.current) {
          callAction({
            action: actions.moveInput,
            args: {
              x: calculatedX.current,
              y: calculatedY.current
            }
          });
          dragged.current = false;
        }
      }
    });
    inputJXG.current = newInputJXG;
    anchorPointJXG.current = newAnchorPointJXG;
    previousPositionFromAnchor.current = SVs.positionFromAnchor;
    if (SVs.labelHasLatex) {
      setTimeout(() => {
        if (inputJXG.current) {
          inputJXG.current.needsUpdate = true;
          inputJXG.current.setText(SVs.label);
          inputJXG.current.update();
          board?.updateRenderer();
        }
      }, 1e3);
    }
  }
  function deleteInputJXG() {
    if (!inputJXG.current) {
      return;
    }
    inputJXG.current.rendNodeCheckbox.removeEventListener(
      "change",
      onChangeHandler
    );
    inputJXG.current.off("drag");
    inputJXG.current.off("down");
    inputJXG.current.off("hit");
    inputJXG.current.off("up");
    inputJXG.current.off("keyfocusout");
    inputJXG.current.off("keydown");
    board?.removeObject(inputJXG.current);
    inputJXG.current = null;
  }
  if (board) {
    let anchorCoords;
    try {
      let anchor = Context.fromAst(SVs.anchor);
      anchorCoords = [
        anchor.get_component(0).evaluate_to_constant() ?? NaN,
        anchor.get_component(1).evaluate_to_constant() ?? NaN
      ];
    } catch (e) {
      anchorCoords = [NaN, NaN];
    }
    lastPositionFromCore.current = anchorCoords;
    if (inputJXG.current === null) {
      createInputJXG();
    } else {
      if (!anchorPointJXG.current) {
        return;
      }
      if (inputJXG.current.Value() !== rendererValue) {
        inputJXG.current.setAttribute({ checked: rendererValue });
      }
      inputJXG.current.relativeCoords.setCoordinates(
        JXG.COORDS_BY_USER,
        [0, 0]
      );
      anchorPointJXG.current.coords.setCoordinates(
        JXG.COORDS_BY_USER,
        anchorCoords
      );
      inputJXG.current.setText(SVs.label);
      let visible = !SVs.hidden;
      if (Number.isFinite(anchorCoords[0]) && Number.isFinite(anchorCoords[1])) {
        let actuallyChangedVisibility = inputJXG.current.visProp["visible"] !== visible;
        inputJXG.current.visProp["visible"] = visible;
        inputJXG.current.visPropCalc["visible"] = visible;
        if (actuallyChangedVisibility) {
          inputJXG.current.setAttribute({ visible });
        }
      } else {
        inputJXG.current.visProp["visible"] = false;
        inputJXG.current.visPropCalc["visible"] = false;
      }
      if (inputJXG.current.visProp.disabled !== SVs.disabled) {
        inputJXG.current.visProp.disabled = SVs.disabled;
        inputJXG.current.setAttribute({ disabled: SVs.disabled });
      }
      inputJXG.current.visProp.highlight = !fixLocation.current;
      inputJXG.current.visProp.fixed = fixed.current;
      inputJXG.current.isDraggable = !fixLocation.current;
      inputJXG.current.needsUpdate = true;
      if (SVs.positionFromAnchor !== previousPositionFromAnchor.current) {
        let { anchorx, anchory } = getPositionFromAnchorByCoordinate(
          SVs.positionFromAnchor
        );
        inputJXG.current.visProp.anchorx = anchorx;
        inputJXG.current.visProp.anchory = anchory;
        anchorRel.current = [anchorx, anchory];
        previousPositionFromAnchor.current = SVs.positionFromAnchor;
        inputJXG.current.fullUpdate();
      } else {
        inputJXG.current.update();
      }
      anchorPointJXG.current.needsUpdate = true;
      anchorPointJXG.current.update();
      board.updateRenderer();
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { id });
  }
  if (SVs.hidden) {
    return null;
  }
  let disabled = SVs.disabled;
  const inputKey = id + "_input";
  if (disabled) {
    getComputedStyle(
      document.documentElement
    ).getPropertyValue("--mainGray");
  }
  const validationState = calculateValidationState(SVs);
  const { isPending, submitActionWithPending } = useSubmitActionWithDelay({
    actionKey: "submitAnswer",
    actions,
    callAction,
    validationState,
    justSubmitted: SVs.justSubmitted
  });
  const checkWorkComponent = createCheckWorkComponent(
    SVs,
    id,
    validationState,
    submitActionWithPending,
    SVs.forceFullCheckWorkButton,
    isPending
  );
  let input;
  let label = SVs.label;
  if (SVs.labelHasLatex) {
    label = /* @__PURE__ */ jsxRuntimeExports.jsx(MathJax, { hideUntilTypeset: "first", inline: true, dynamic: true, children: label });
  }
  let shortDescription = SVs.shortDescription || void 0;
  const hasLabel = typeof SVs.label === "string" ? SVs.label.trim() !== "" : !!SVs.label;
  const labelId = `${id}-label`;
  const descriptionChild = children.find((child) => child);
  let descriptionId = void 0;
  let description = null;
  if (descriptionChild) {
    descriptionId = `${id}-description-content`;
    description = /* @__PURE__ */ jsxRuntimeExports.jsx(DescriptionPopover, { children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: descriptionId, children: descriptionChild }) });
  }
  if (SVs.asToggleButton) {
    input = /* @__PURE__ */ jsxRuntimeExports.jsx(
      ToggleButton,
      {
        id: inputKey,
        isSelected: rendererValue,
        onClick: onChangeHandler,
        onFocus: () => onFocusChanged(true),
        onBlur: () => onFocusChanged(false),
        value: label,
        disabled,
        ariaLabel: shortDescription
      },
      inputKey
    );
  } else {
    let containerClass = "boolean-container";
    let checkmarkClass = "checkmark";
    if (disabled) {
      containerClass += " boolean-container-disabled";
      checkmarkClass += " checkmark-disabled";
    }
    const checkboxControl = /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "span",
      {
        className: containerClass,
        onMouseDown: (e) => {
          if (e.target instanceof HTMLInputElement) {
            return;
          }
          e.preventDefault();
        },
        onClick: (e) => {
          if (disabled || e.target instanceof HTMLInputElement) {
            return;
          }
          inputRef.current?.focus();
          onChangeHandler();
        },
        id: `${id}-container`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              type: "checkbox",
              id: inputKey,
              checked: rendererValue,
              onChange: onChangeHandler,
              disabled,
              onFocus: () => onFocusChanged(true),
              onBlur: () => onFocusChanged(false),
              "aria-labelledby": hasLabel ? labelId : void 0,
              "aria-label": !hasLabel ? shortDescription : void 0,
              "aria-description": hasLabel ? shortDescription : void 0,
              "aria-details": descriptionId
            },
            inputKey
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: checkmarkClass, "aria-hidden": "true" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-hidden": "true", children: "​" })
        ]
      }
    );
    input = checkboxControl;
  }
  const labelComponent = hasLabel && !SVs.asToggleButton ? /* @__PURE__ */ jsxRuntimeExports.jsx(
    "label",
    {
      id: labelId,
      htmlFor: inputKey,
      style: SVs.labelPosition === "left" ? { marginRight: "2px" } : { marginLeft: "2px" },
      children: label
    }
  ) : null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "span",
    {
      id,
      style: {
        display: "inline-flex",
        alignItems: "baseline"
      },
      children: [
        SVs.labelPosition === "left" ? labelComponent : null,
        input,
        checkWorkComponent,
        description,
        SVs.labelPosition !== "left" ? labelComponent : null
      ]
    }
  );
});
export {
  booleanInput as default
};
