import { h, r as registerInstance } from './index-38ad4957.js';
import { i as intl } from './global-96c14d63.js';
import { l, k as useState, f as useEffect, n as h$1 } from './dom-context-hooks.module-50442785.js';
import { d as dist, q as Pn, F as Fn, i as isDemo, o as En } from './index.module-b23fdad8.js';
import { c as cjs } from './cjs-bdfb4486.js';
import { g as getProps } from './utils-334c1e34.js';
import { c as createStyleSheet } from './JSS-67b5cff8.js';
import { E as ErrorStyles } from './mixins-f750863a.js';
import { T as TextSpanView } from './sqm-text-span-view-72f43dff.js';
import { V as VERIFICATION_EMAIL_NAMESPACE, S as SHOW_CODE_NAMESPACE, a as VERIFICATION_PARENT_NAMESPACE } from './keys-406491dc.js';
import { u as useVerificationEmail } from './useVerificationEmail-c13c3b51.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: {
    ...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 = createStyleSheet(style);
const styleString = sheet.toString();
function WidgetCodeVerificationView(props) {
  const { states, refs, callbacks, text } = props;
  const resendCodeText = intl.formatMessage({
    id: "resendCodeText",
    defaultMessage: text.resendCodeText,
  }, {
    resendCodeLink: (h("a", { href: "", style: {
        textDecoration: "underline",
        color: "inherit",
        cursor: "pointer",
      }, onClick: (e) => {
        e.preventDefault();
        callbacks.resendEmail();
      } }, text.resendCodeLabel)),
  });
  const codeResentSuccessfully = intl.formatMessage({
    id: "codeResentSuccessfully",
    defaultMessage: text.codeResentSuccessfullyText,
  }, {
    email: states.email,
  });
  const inputClass = states.verifyFailed
    ? sheet.classes.CodeInputError
    : sheet.classes.CodeInput;
  return (h("div", { part: "sqm-base" },
    h("style", { type: "text/css" },
      vanillaStyle,
      styleString),
    h("div", { class: sheet.classes.Wrapper },
      h("div", { class: sheet.classes.HeaderContainer },
        h(TextSpanView, { type: "p" }, intl.formatMessage({
          id: `emailHeaderText`,
          defaultMessage: states.verifyFailed
            ? text.reverifyCodeHeaderText
            : text.verifyCodeHeaderText,
        }, { email: states.email }))),
      states.emailResent && (h("sqm-form-message", { type: "success", exportparts: "successalert-icon" },
        h("b", null, codeResentSuccessfully))),
      h("div", { class: sheet.classes.InputsContainer },
        h("div", { ref: refs.codeWrapperRef, class: sheet.classes.CodeInputContainer },
          h("sl-input", { class: inputClass, name: "code" }),
          h("sl-input", { class: inputClass, name: "code" }),
          h("sl-input", { class: inputClass, name: "code" }),
          h("sl-input", { class: inputClass, name: "code" }),
          h("sl-input", { class: inputClass, name: "code" }),
          h("sl-input", { class: inputClass, name: "code" })),
        states.verifyFailed && (h("p", { class: sheet.classes.ErrorText }, text.invalidCodeText)),
        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)),
      h("div", { class: sheet.classes.FooterContainer },
        h(TextSpanView, { type: "p" }, resendCodeText)))));
}

const VerifyEmailWithCodeMutation = dist.gql `
  mutation submitImpactPublisherEmail2FACode(
    $user: UserIdInput!
    $code: String!
  ) {
    submitImpactPublisherEmail2FACode(user: $user, code: $code) {
      verifiedEmail
      accessKey
    }
  }
`;
function useWidgetCodeVerification(props) {
  const host = l();
  const [_, setShowCode] = Pn(SHOW_CODE_NAMESPACE);
  const email = Fn(VERIFICATION_EMAIL_NAMESPACE);
  const [emailSent, setEmailSent] = useState(false);
  const [emailResent, setEmailResent] = useState(false);
  const [codeRef, setCodeRef] = useState(null);
  const [validationError, setValidationError] = useState(false);
  const [emailError, setEmailError] = useState(false);
  const { initialized, verificationEmail, send: [sendEmail, { loading: sendLoading, errors: sendErrors }], verify: [verifyEmail, { loading: verifyLoading, errors: verifyErrors }], } = useVerificationEmail();
  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);
    }
  };
  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) {
    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.";
    h$1(this);
  }
  disconnectedCallback() { }
  getTextProps() {
    return getProps(this);
  }
  render() {
    const props = isDemo()
      ? useDemoWidgetCodeVerification(this)
      : useWidgetCodeVerification(this);
    return h(WidgetCodeVerificationView, Object.assign({}, props));
  }
};
function useDemoWidgetCodeVerification(props) {
  const [emailResent, setEmailResent] = useState(false);
  const setVerifiedContext = En(VERIFICATION_PARENT_NAMESPACE);
  return 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 });
}

export { WidgetCodeVerification as sqm_code_verification };
