'use strict';

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

const index = require('./index-8277cbb3.js');
const global = 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');
const utils = require('./utils-6847bc06.js');
const JSS = require('./JSS-8503a151.js');
const mixins = require('./mixins-4761d472.js');
const sqmTextSpanView = require('./sqm-text-span-view-b9e10f5d.js');
const keys = require('./keys-cff24974.js');
const useVerificationEmail = require('./useVerificationEmail-5d19aa99.js');

const style = {
  Wrapper: {
    display: "flex",
    flexDirection: "column",
    gap: "var(--sl-spacing-medium)",
    maxWidth: "550px",
  },
  HeaderContainer: {
    display: "flex",
    flexDirection: "column",
  },
  InputsContainer: {
    display: "flex",
    gap: "var(--sl-spacing-medium)",
    position: "relative",
    flexDirection: "column",
  },
  CodeInputContainer: {
    display: "flex",
    gap: "var(--sl-spacing-medium)",
  },
  CodeInput: {
    maxWidth: "40px",
    "&::part(base)": {
      borderRadius: "4px !important",
    },
    "&::part(input)": {
      margin: "0",
      padding: "0 var(--sl-input-spacing-small)",
      fontSize: "var(--sl-font-size-large)",
    },
  },
  CodeInputError: {
    ...mixins.ErrorStyles,
    maxWidth: "40px",
    "&::part(base)": {
      borderRadius: "4px !important",
    },
    "&::part(input)": {
      margin: "0",
      padding: "0 var(--sl-input-spacing-small)",
      fontSize: "var(--sl-font-size-large)",
    },
  },
  ErrorText: {
    color: "var(--sqm-danger-color-text)",
    fontSize: "var(--sl-font-size-small)",
    margin: "0",
  },
  ContinueButton: {
    width: "100%",
    maxWidth: "100px",
  },
  FooterContainer: {
    display: "flex",
    flexDirection: "column",
  },
  SkeletonOne: {
    width: "50%",
    height: "16px",
  },
  SkeletonTwo: {
    width: "30%",
    height: "34px",
  },
  SkeletonThree: {
    width: "15%",
    height: "24px",
  },
};
const vanillaStyle = `
:host {
  display: block;
}
:host([hidden]): {
  display: none;
}


`;
const sheet = JSS.createStyleSheet(style);
const styleString = sheet.toString();
function WidgetCodeVerificationView(props) {
  const { states, refs, callbacks, text } = props;
  const resendCodeText = global.intl.formatMessage({
    id: "resendCodeText",
    defaultMessage: text.resendCodeText,
  }, {
    resendCodeLink: (index.h("a", { href: "", style: {
        textDecoration: "underline",
        color: "inherit",
        cursor: "pointer",
      }, onClick: (e) => {
        e.preventDefault();
        callbacks.resendEmail();
      } }, text.resendCodeLabel)),
  });
  const codeResentSuccessfully = global.intl.formatMessage({
    id: "codeResentSuccessfully",
    defaultMessage: text.codeResentSuccessfullyText,
  }, {
    email: states.email,
  });
  const inputClass = states.verifyFailed
    ? sheet.classes.CodeInputError
    : sheet.classes.CodeInput;
  return (index.h("div", { part: "sqm-base" },
    index.h("style", { type: "text/css" },
      vanillaStyle,
      styleString),
    index.h("div", { class: sheet.classes.Wrapper },
      index.h("div", { class: sheet.classes.HeaderContainer },
        index.h(sqmTextSpanView.TextSpanView, { type: "p" }, global.intl.formatMessage({
          id: `emailHeaderText`,
          defaultMessage: states.verifyFailed
            ? text.reverifyCodeHeaderText
            : text.verifyCodeHeaderText,
        }, { email: states.email }))),
      states.emailResent && (index.h("sqm-form-message", { type: "success", exportparts: "successalert-icon" },
        index.h("b", null, codeResentSuccessfully))),
      index.h("div", { class: sheet.classes.InputsContainer },
        index.h("div", { ref: refs.codeWrapperRef, class: sheet.classes.CodeInputContainer },
          index.h("sl-input", { class: inputClass, name: "code" }),
          index.h("sl-input", { class: inputClass, name: "code" }),
          index.h("sl-input", { class: inputClass, name: "code" }),
          index.h("sl-input", { class: inputClass, name: "code" }),
          index.h("sl-input", { class: inputClass, name: "code" }),
          index.h("sl-input", { class: inputClass, name: "code" })),
        states.verifyFailed && (index.h("p", { class: sheet.classes.ErrorText }, text.invalidCodeText)),
        index.h("sl-button", { class: sheet.classes.ContinueButton, onClick: callbacks.submitCode, disabled: states.loading || states.initialiseLoading, loading: states.loading || states.initialiseLoading, exportparts: "base: primarybutton-base", type: "primary" }, text.verifyText)),
      index.h("div", { class: sheet.classes.FooterContainer },
        index.h(sqmTextSpanView.TextSpanView, { type: "p" }, resendCodeText)))));
}

const VerifyEmailWithCodeMutation = index_module.dist.gql `
  mutation submitImpactPublisherEmail2FACode(
    $user: UserIdInput!
    $code: String!
  ) {
    submitImpactPublisherEmail2FACode(user: $user, code: $code) {
      verifiedEmail
      accessKey
    }
  }
`;
function useWidgetCodeVerification(props) {
  const host = domContextHooks_module.l();
  const [_, setShowCode] = index_module.Pn(keys.SHOW_CODE_NAMESPACE);
  const email = index_module.Fn(keys.VERIFICATION_EMAIL_NAMESPACE);
  const [emailSent, setEmailSent] = domContextHooks_module.useState(false);
  const [emailResent, setEmailResent] = domContextHooks_module.useState(false);
  const [codeRef, setCodeRef] = domContextHooks_module.useState(null);
  const [validationError, setValidationError] = domContextHooks_module.useState(false);
  const [emailError, setEmailError] = domContextHooks_module.useState(false);
  const { initialized, verificationEmail, send: [sendEmail, { loading: sendLoading, errors: sendErrors }], verify: [verifyEmail, { loading: verifyLoading, errors: verifyErrors }], } = useVerificationEmail.useVerificationEmail();
  domContextHooks_module.useEffect(() => {
    if (!codeRef)
      return;
    const slInputs = codeRef.querySelectorAll("sl-input");
    const codeElements = Array.from(slInputs).map((node) => node.shadowRoot.querySelector(`input[name="code"]`));
    codeElements.forEach((element, idx) => {
      element.addEventListener("focus", (e) => {
        e.target.select();
      });
      element.addEventListener("keydown", (e) => {
        if (e.key === "Backspace" && e.target.value === "") {
          codeElements[Math.max(0, idx - 1)].focus();
        }
      });
      element.addEventListener("input", (e) => {
        const input = e.data;
        if (!input)
          return;
        if (idx === codeElements.length - 1) {
          e.target.value = input.slice(0, 1);
          return;
        }
        if (input.length > 1) {
          const rest = input.slice(1);
          e.target.value = input.slice(0, 1);
          codeElements[idx + 1].dispatchEvent(new InputEvent("input", {
            inputType: "insertFromPaste",
            data: rest,
          }));
        }
        codeElements[idx + 1].focus();
      });
    });
  }, [codeRef]);
  const reset = () => {
    setShowCode(false);
    setValidationError(false);
  };
  const resendEmail = async () => {
    // UI should only allow this to be called if initialized, but checking just in case
    if (!initialized)
      return;
    const result = await sendEmail();
    if (!result) {
      setEmailError(true);
      return;
    }
    if (emailSent)
      setEmailResent(true);
    setEmailSent(true);
  };
  const submitCode = async () => {
    const slInputs = codeRef.querySelectorAll("sl-input");
    const codeElements = Array.from(slInputs).map((node) => node.shadowRoot.querySelector(`input[name="code"]`));
    if (codeElements.find((el) => !el.value)) {
      setValidationError(true);
      return;
    }
    let code = "";
    codeElements.forEach((element) => {
      code = `${code}${element.value}`;
    });
    // UI should only allow this to be called if initialized, but checking just in case
    if (!initialized)
      return;
    setValidationError(false);
    const res = await verifyEmail(code);
    if (res === null || res === void 0 ? void 0 : res.success) {
      props.onVerification(res.accessKey);
      reset();
    }
    else {
      setValidationError(true);
    }
  };
  domContextHooks_module.useEffect(() => {
    // Wait for mutations to be determined from user lookup
    if (!initialized)
      return;
    // email should already exist if user has completed email-verification
    if (!email)
      resendEmail();
    else
      setEmailSent(true);
  }, [initialized]);
  return {
    refs: {
      codeWrapperRef: setCodeRef,
    },
    states: {
      email: verificationEmail,
      emailResent,
      resendError: sendErrors || verifyErrors,
      initialiseLoading: !initialized,
      loading: sendLoading || verifyLoading,
      verifyFailed: !!validationError,
    },
    callbacks: {
      resendEmail,
      submitCode,
    },
    text: props.getTextProps(),
  };
}

const WidgetCodeVerification = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    /**
     * @uiName Verify code widget header text
     */
    this.verifyCodeHeaderText = "Enter the code sent to {email} from our referral provider, impact.com.";
    /**
     * @uiName Reverify code widget header text
     */
    this.reverifyCodeHeaderText = "Enter the code sent to {email} from our referral provider, impact.com.";
    /**
     * Text displayed under verify button
     * @uiName Resend code text
     */
    this.resendCodeText = "Didn't receive your code? {resendCodeLink}";
    /**
     * The link that appears in the resend code link
     * @uiName Resend code label
     */
    this.resendCodeLabel = "Resend code";
    /**
     * Link text displayed under verify button
     * @uiName Resend code text
     */
    this.codeResentSuccessfullyText = "Another code has been sent to {email}";
    /**
     * Error text displayed under verification input
     * @uiName Invalid code text
     */
    this.invalidCodeText = "Please check your code and try again. If you’re still having trouble, try resending your code.";
    /**
     * @uiName Verify code button text
     */
    this.verifyText = "Verify";
    /**
     * Displayed when the email verification fails due to a network error. The participant can try refreshing the page.
     * @uiName Network error message
     */
    this.networkErrorMessage = "An error occurred while verifying your email. Please refresh the page and try again.";
    domContextHooks_module.h$1(this);
  }
  disconnectedCallback() { }
  getTextProps() {
    return utils.getProps(this);
  }
  render() {
    const props = index_module.isDemo()
      ? useDemoWidgetCodeVerification(this)
      : useWidgetCodeVerification(this);
    return index.h(WidgetCodeVerificationView, Object.assign({}, props));
  }
};
function useDemoWidgetCodeVerification(props) {
  const [emailResent, setEmailResent] = domContextHooks_module.useState(false);
  const setVerifiedContext = index_module.En(keys.VERIFICATION_PARENT_NAMESPACE);
  return cjs.cjs({
    states: {
      initialiseLoading: false,
      loading: false,
      email: "test@example.com",
      emailResent,
      verifyFailed: false,
    },
    refs: {
      codeWrapperRef: () => { },
    },
    callbacks: {
      resendEmail: async () => setEmailResent(true),
      submitCode: async () => setVerifiedContext(true),
    },
    text: props.getTextProps(),
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
}

exports.sqm_code_verification = WidgetCodeVerification;
