import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { memo, useEffect, useState, useRef, useContext } from "react";
import styled, { ThemeContext } from "styled-components";
import { DSBackdrop } from "@elliemae/ds-backdrop";
import { DSCircularIndeterminateIndicator } from "@elliemae/ds-circular-progress-indicator";
import { useAppSelector } from "../../data/react.js";
import { useHTMLWaitMessage } from "./use-html-wait-message.js";
import {
  waitStartEvent,
  waitEndEvent
} from "../../analytics/user-wait-event.js";
import { lrTrack } from "../../utils/logrocket.js";
const StyledCircularIndicator = styled(DSCircularIndeterminateIndicator)`
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
`;
const WaitMessage = memo(
  ({
    size = "xl",
    color = "light",
    showText = true,
    withTooltip = false,
    tooltipStartPlacementPreference = "center",
    ...rest
  }) => {
    const theme = useContext(ThemeContext);
    const ref = useRef(false);
    const [show, setShow] = useState(false);
    const isOpen = useAppSelector((state) => state.waitMessage?.isOpen);
    const delay = useAppSelector((state) => state.waitMessage?.delay);
    ref.current = isOpen ?? false;
    const message = useAppSelector((state) => state.waitMessage?.message);
    useEffect(() => {
      setTimeout(
        () => {
          if (isOpen && ref.current) {
            setShow(true);
            waitStartEvent();
            lrTrack("wait-spinner-start");
          }
        },
        delay ? 1e3 : 0
      );
      if (!isOpen) {
        setShow(false);
        waitEndEvent();
        lrTrack("wait-spinner-end");
      }
    }, [delay, isOpen]);
    useHTMLWaitMessage(isOpen !== null);
    return show ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(DSBackdrop, { zIndex: theme.zIndex.loader }),
      /* @__PURE__ */ jsx(
        StyledCircularIndicator,
        {
          id: "em-loading",
          size,
          color,
          showText,
          withTooltip,
          tooltipStartPlacementPreference,
          ...rest,
          text: message
        }
      )
    ] }) : null;
  }
);
export {
  WaitMessage
};
