import { j as jsxRuntimeExports } from "./doenetml-BPsLSRHD.js";
import { F as FontAwesomeIcon } from "./index.es-XE1CVwqn.js";
import { d as faSpinner, e as faLevelDownAlt, g as faCheck, h as faTimes, i as faCloud } from "./index-BDlitCgu.js";
import React__default, { useCallback } from "react";
function calculateValidationState(SVs) {
  let validationState = "unvalidated";
  if (SVs.justSubmitted || SVs.numAttemptsLeft < 1) {
    if (SVs.creditAchieved === 1) {
      validationState = "correct";
    } else if (SVs.creditAchieved === 0) {
      validationState = "incorrect";
    } else {
      validationState = "partialcorrect";
    }
  }
  return validationState;
}
function createCheckWorkComponent(SVs, id, validationState, submitAnswer, showText, isPending = false) {
  if (!SVs.showCheckWork) {
    return null;
  }
  const buttonClassNames = ["check-work"];
  const tabIndex = SVs.disabled ? -1 : 0;
  let buttonContent = null;
  let liveLabel = void 0;
  let otherLabel = void 0;
  if (isPending) {
    buttonClassNames.push("check-work-pending");
    const pendingText = SVs.showCorrectness ? "Checking..." : "Submitting...";
    liveLabel = SVs.showCorrectness ? "Checking answer" : "Submitting answer";
    buttonContent = showText ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      "  ",
      pendingText
    ] }) : null;
    buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FontAwesomeIcon, { icon: faSpinner, spin: true }),
      buttonContent
    ] });
  } else if (validationState === "unvalidated") {
    buttonClassNames.push("check-work-unvalidated");
    const checkWorkText = SVs.showCorrectness ? SVs.submitLabel : SVs.submitLabelNoCorrectness;
    otherLabel = checkWorkText;
    buttonContent = showText ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      "  ",
      checkWorkText
    ] }) : null;
    buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        FontAwesomeIcon,
        {
          icon: faLevelDownAlt,
          transform: { rotate: 90 },
          title: otherLabel
        }
      ),
      buttonContent
    ] });
  } else if (SVs.showCorrectness) {
    buttonClassNames.push(`check-work-${validationState}`);
    if (validationState === "correct") {
      liveLabel = "Correct";
      buttonContent = showText ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: "  Correct" }) : null;
      buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "aria-hidden": true, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          FontAwesomeIcon,
          {
            icon: faCheck,
            title: liveLabel
          }
        ),
        buttonContent
      ] });
    } else if (validationState === "incorrect") {
      liveLabel = "Incorrect";
      buttonContent = showText ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: "  Incorrect" }) : null;
      buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "aria-hidden": true, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          FontAwesomeIcon,
          {
            icon: faTimes,
            title: liveLabel
          }
        ),
        buttonContent
      ] });
    } else {
      const percent = Math.round(SVs.creditAchieved * 100);
      const partialText = SVs.creditIsReducedByAttempt ? `${percent}% Credit` : `${percent}% Correct`;
      buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-hidden": true, children: showText ? partialText : `${percent} %` });
      liveLabel = partialText;
    }
  } else {
    buttonClassNames.push("check-work-response-saved");
    liveLabel = "Response Saved";
    buttonContent = showText ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: "  Response Saved" }) : null;
    buttonContent = /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FontAwesomeIcon, { icon: faCloud, title: liveLabel }),
      buttonContent
    ] });
  }
  let button = /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "button",
    {
      className: buttonClassNames.join(" "),
      id: id + "_button",
      tabIndex,
      disabled: SVs.disabled,
      "aria-disabled": isPending ? true : void 0,
      onClick: submitAnswer,
      children: [
        buttonContent,
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "visually-hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { "aria-live": "polite", "aria-atomic": true, children: liveLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: otherLabel })
        ] })
      ]
    }
  );
  let messages = [];
  if (SVs.creditIsReducedByAttempt) {
    if (SVs.numIncorrectSubmissions === 0) {
      messages.push("Max credit available: 100%");
    } else if (SVs.creditAchieved > 0) {
      messages.push(
        `Max credit available: ${Math.round(100 * SVs.creditFactorUsed)}%`
      );
    } else {
      messages.push(
        `Max credit available: ${Math.round(100 * SVs.nextCreditFactor)}%`
      );
    }
  }
  if (SVs.numAttemptsLeft < 1) {
    messages.push("no attempts remaining");
  } else if (SVs.numAttemptsLeft === 1) {
    messages.push("1 attempt remaining");
  } else if (Number.isFinite(SVs.numAttemptsLeft)) {
    messages.push(`${SVs.numAttemptsLeft} attempts remaining`);
  }
  if (messages.length > 0) {
    const message = messages.join("; ");
    button = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      button,
      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { "data-test": "attempts-remaining", children: [
        "(",
        message,
        ")"
      ] })
    ] });
  }
  return button;
}
function useDelayedSubmissionPending({
  delayMs = 500,
  submitAction,
  validationState,
  justSubmitted
}) {
  const [isPending, setIsPending] = React__default.useState(false);
  const isSubmissionInFlight = React__default.useRef(false);
  const timeoutRef = React__default.useRef(null);
  const clearPending = React__default.useCallback(() => {
    isSubmissionInFlight.current = false;
    setIsPending(false);
    if (timeoutRef.current !== null) {
      window.clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, []);
  React__default.useEffect(() => {
    if (!isSubmissionInFlight.current) {
      return;
    }
    if (justSubmitted || validationState !== "unvalidated") {
      clearPending();
    }
  }, [clearPending, justSubmitted, validationState]);
  React__default.useEffect(() => {
    return () => {
      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current);
      }
    };
  }, []);
  const submitActionWithPending = React__default.useCallback(() => {
    if (validationState !== "unvalidated") {
      return;
    }
    if (isSubmissionInFlight.current) {
      return;
    }
    isSubmissionInFlight.current = true;
    setIsPending(false);
    if (timeoutRef.current !== null) {
      window.clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    timeoutRef.current = window.setTimeout(() => {
      if (isSubmissionInFlight.current) {
        setIsPending(true);
      }
      timeoutRef.current = null;
    }, delayMs);
    submitAction();
  }, [delayMs, submitAction, validationState]);
  return {
    isPending,
    submitActionWithPending
  };
}
function useSubmitActionWithDelay({
  actionKey,
  actions,
  callAction,
  validationState,
  justSubmitted,
  delayMs = 500
}) {
  const submitCallback = useCallback(
    () => callAction({ action: actions[actionKey] }),
    [actions[actionKey], callAction]
  );
  const { isPending, submitActionWithPending } = useDelayedSubmissionPending({
    submitAction: submitCallback,
    validationState,
    justSubmitted,
    delayMs
  });
  return { isPending, submitActionWithPending };
}
export {
  createCheckWorkComponent as a,
  calculateValidationState as c,
  useSubmitActionWithDelay as u
};
