'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-8277cbb3.js');
require('./global-b7b1b8fe.js');
const domContextHooks_module = require('./dom-context-hooks.module-e7b6727c.js');
const index_module = require('./index.module-f8c8495f.js');
const cjs = require('./cjs-1066ec21.js');
require('./JSS-8503a151.js');
require('./mixins-4761d472.js');
require('./sqm-text-span-view-b9e10f5d.js');
const sqmPortalEmailVerificationView = require('./sqm-portal-email-verification-view-abb773a7.js');

function usePortalEmailVerification(props) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
  const [request, { loading, data, errors }] = index_module.ln();
  const [getVerificationStatus, { data: user, loading: loadingVerification }] = index_module.nn();
  const userIdent = index_module.J();
  const email = (_a = userIdent === null || userIdent === void 0 ? void 0 : userIdent.managedIdentity) === null || _a === void 0 ? void 0 : _a.email;
  const urlParams = new URLSearchParams(index_module.jn.location.search);
  const nextPage = urlParams.get("nextPage");
  const [success, setSuccess] = domContextHooks_module.useState(false);
  const [error, setError] = domContextHooks_module.useState("");
  const [countdown, setCountdown] = domContextHooks_module.useState(10);
  const timerRef = domContextHooks_module.useRef(undefined);
  const countdownRef = domContextHooks_module.useRef(undefined);
  const submit = async () => {
    var _a;
    if (!email)
      return;
    setError("");
    setSuccess(false);
    const urlParams = nextPage ? { nextPage } : null;
    const redirectPath = props.redirectPath;
    const variables = { email, urlParams, redirectPath };
    const result = await request(variables);
    if (result instanceof Error) {
      if (result.message)
        setError(props.networkErrorMessage);
      return;
    }
    if ((_a = result.requestManagedIdentityVerificationEmail) === null || _a === void 0 ? void 0 : _a.success)
      setSuccess(true);
  };
  async function checkVerification() {
    var _a;
    const data = (await getVerificationStatus());
    if ((_a = data === null || data === void 0 ? void 0 : data.managedIdentitySession) === null || _a === void 0 ? void 0 : _a.emailVerified) {
      clearInterval(timerRef.current);
      return index_module.jn.push({
        pathname: props.redirectPath,
        search: urlParams.toString() && "?" + urlParams.toString(),
      });
    }
    resyncTimers(10);
  }
  const startTimer = (countdown = 10000) => setInterval(checkVerification, countdown);
  const startCountdown = (countdown) => setInterval(() => setCountdown(countdown), 1000);
  function resyncTimers(restartCountdown) {
    // Clear existing timers
    clearInterval(countdownRef.current);
    clearInterval(timerRef.current);
    // Do nothing if the tab is currently hidden
    if (document.visibilityState === "hidden")
      return;
    // Restart the timer if verification has just been checked
    if (restartCountdown)
      setCountdown(restartCountdown);
    // Default back to 10 if the countdown got to zero
    let newCountdown = countdown || 10;
    // Start timers from either the beginning or based on the previous value
    countdownRef.current = startCountdown(restartCountdown - 1 || newCountdown - 1);
    timerRef.current = startTimer(restartCountdown * 1000 || newCountdown * 1000);
  }
  const resyncTimersCallback = index_module.useCallback(() => resyncTimers(), [countdown]);
  // Refetch validation status timer
  domContextHooks_module.useEffect(() => {
    if (!timerRef.current) {
      checkVerification();
      timerRef.current = startTimer();
    }
    return () => {
      clearInterval(timerRef.current);
    };
  }, []);
  // Countdown timer
  domContextHooks_module.useEffect(() => {
    if (countdown > 0) {
      clearInterval(countdownRef.current);
      countdownRef.current = startCountdown(countdown - 1);
    }
    // Re-sync the timers if tab visibility has changed
    document.addEventListener("visibilitychange", resyncTimersCallback);
    return () => {
      clearInterval(countdownRef.current);
      document.removeEventListener("visibilitychange", resyncTimersCallback);
    };
  }, [countdown]);
  return {
    states: {
      loading,
      error: ((_e = (_d = (_c = (_b = errors === null || errors === void 0 ? void 0 : errors.response) === null || _b === void 0 ? void 0 : _b.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.extensions) === null || _e === void 0 ? void 0 : _e.message) || ((_h = (_g = (_f = errors === null || errors === void 0 ? void 0 : errors.response) === null || _f === void 0 ? void 0 : _f.errors) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.message) ||
        error,
      success,
      loadingVerification,
      isVerified: !!((_j = user === null || user === void 0 ? void 0 : user.managedIdentitySession) === null || _j === void 0 ? void 0 : _j.emailVerified),
      countdown,
    },
    callbacks: {
      submit,
    },
    content: {
      email,
      verifyMessage: props.verifyMessage,
      emailVerificationHeader: props.emailVerificationHeader,
      resendEmailButtonText: props.resendEmailButtonText,
      verificationLoadingMessage: props.verificationLoadingMessage,
      verificationStatusMessage: props.verificationStatusMessage,
      verificationResentMessage: props.verificationResentMessage,
      networkErrorMessage: props.networkErrorMessage,
    },
  };
}

const PortalEmailVerification = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.ignored = true;
    /**
     * Redirect participants to this page from their verification email.
     *
     * @uiName Email redirect
     * @uiWidget pageSelect
     */
    this.redirectPath = "/verifyEmail";
    /**
     * @uiName Email verification header text
     */
    this.emailVerificationHeader = "Verify your email";
    /**
     * @uiName Re-send email button text
     */
    this.resendEmailButtonText = "Re-send Email";
    /**
     * @uiName Email verification body text
     * @uiWidget textArea
     */
    this.verifyMessage = "A verification email was sent to {email}. Please verify your email to continue to the portal. Resending an email will invalidate the previous email.";
    /**
     * @uiName Email verification status text
     * @uiWidget textArea
     */
    this.verificationStatusMessage = "Checking verification status in {countdown}";
    /**
     * @uiName Email verification checking text
     * @uiWidget textArea
     */
    this.verificationLoadingMessage = "Checking verification status";
    /**
     * @uiName Email verification resent text
     * @uiWidget textArea
     */
    this.verificationResentMessage = "Your verification email has been resent successfully";
    /**
     * Displayed when your verification email fails to send due to a network error. The participant can try refreshing the page.
     * @uiName Network error message
     */
    this.networkErrorMessage = "An error occurred while verifying your password. Please refresh the page.";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  render() {
    const { states, callbacks, content } = index_module.isDemo()
      ? usePortalEmailVerificationDemo(this)
      : usePortalEmailVerification(this);
    return (index.h(sqmPortalEmailVerificationView.PortalEmailVerificationView, { states: states, callbacks: callbacks, content: content }));
  }
};
function usePortalEmailVerificationDemo(props) {
  return cjs.cjs({
    states: { error: "", loading: false, success: false, countdown: 10 },
    callbacks: {
      submit: async (_event) => { },
    },
    content: {
      email: "test@example.com",
      verifyMessage: props.verifyMessage,
      emailVerificationHeader: props.emailVerificationHeader,
      resendEmailButtonText: props.resendEmailButtonText,
      verificationLoadingMessage: props.verificationLoadingMessage,
      verificationStatusMessage: props.verificationStatusMessage,
      verificationResentMessage: props.verificationResentMessage,
      networkErrorMessage: props.networkErrorMessage,
    },
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
}

exports.sqm_portal_email_verification = PortalEmailVerification;
