import { h, r as registerInstance } from './index-38ad4957.js';
import { i as intl } from './global-96c14d63.js';
import { k as useState, f as useEffect, n as h$1 } from './dom-context-hooks.module-50442785.js';
import { d as dist, q as Pn, w as wn, J, $ as $e, 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 { T as TextSpanView } from './sqm-text-span-view-72f43dff.js';
import { S as SHOW_CODE_NAMESPACE, V as VERIFICATION_EMAIL_NAMESPACE } from './keys-406491dc.js';
import { u as useVerificationEmail } from './useVerificationEmail-c13c3b51.js';

const UpsertUserEmailMutation = dist.gql `
  mutation upsertUser($userInput: UserInput!) {
    upsertUser(userInput: $userInput) {
      id
      accountId
      email
    }
  }
`;
const UserLookupQuery = dist.gql `
  query user {
    viewer {
      ... on User {
        id
        accountId
        email
        impactConnection {
          user {
            id
            email
          }
        }
      }
    }
  }
`;
function useUpsertUserEmail() {
  const user = J();
  const [request, { loading: loading, data, errors }] = $e(UpsertUserEmailMutation);
  const upsertUserEmail = async (email) => {
    try {
      const result = await request({
        userInput: {
          id: user.id,
          accountId: user.accountId,
          email,
        },
      });
      if (result instanceof Error || !result)
        throw new Error();
      return result;
    }
    catch (e) {
      console.error("Could not set email on user", e);
      return undefined;
    }
  };
  return [
    upsertUserEmail,
    {
      loading,
      data,
      errors,
    },
  ];
}
function useWidgetEmailVerification(props) {
  const [_, setShowCode] = Pn(SHOW_CODE_NAMESPACE);
  const [email, setEmail] = Pn(VERIFICATION_EMAIL_NAMESPACE);
  const [emailExists, setEmailExists] = useState(false);
  const [error, setError] = useState(false);
  const [mutationError, setMutationError] = useState(false);
  const { initialized, send: [sendEmail, { loading: sendLoading, errors }], } = useVerificationEmail();
  const [upsertUserEmail] = useUpsertUserEmail();
  const [loading, setLoading] = useState(true);
  const { data, loading: initialLoading } = wn(UserLookupQuery, {});
  const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  useEffect(() => {
    if (!(data === null || data === void 0 ? void 0 : data.viewer))
      return;
    setEmailExists(!!data.viewer.email);
  }, [data]);
  useEffect(() => {
    if (initialized)
      setLoading(false);
  }, [initialized]);
  const submitEmail = async (e) => {
    e.preventDefault();
    if (!(data === null || data === void 0 ? void 0 : data.viewer))
      return;
    setLoading(true);
    const toAddress = data.viewer.email;
    if (!toAddress) {
      // If no email on the user, set one
      const formData = e.detail.formData;
      const newEmail = formData.get("email").toString();
      if (!emailRegex.test(newEmail)) {
        setError(true);
        return;
      }
      const result = await upsertUserEmail(newEmail);
      if (!result || !result.user.email)
        setError(true);
    }
    // UI should not allow this call til initialisation is done
    if (!initialized)
      return;
    const result = await sendEmail();
    if (!result || !result.success)
      setMutationError(true);
    else {
      // This is used to let the code verification widget know an email was already sent
      setEmail(toAddress);
      setShowCode(true);
    }
    setLoading(false);
  };
  return {
    callbacks: {
      submitEmail,
    },
    states: {
      loading,
      initialLoading: initialLoading && !initialized,
      error,
      email: data === null || data === void 0 ? void 0 : data.viewer.email,
      sendCodeError: mutationError,
    },
    text: props.getTextProps(),
  };
}

const style = {
  Wrapper: {
    display: "flex",
    flexDirection: "column",
    gap: "var(--sl-spacing-medium)",
    marginTop: "var(--sl-spacing-medium)",
  },
  InputsContainer: {
    display: "flex",
    gap: "var(--sl-spacing-medium)",
    position: "relative",
    flexDirection: "column",
    maxWidth: "320px",
  },
  ContinueButton: {
    width: "100%",
    maxWidth: "100px",
  },
  SkeletonOne: {
    width: "50%",
    height: "16px",
  },
  SkeletonTwo: {
    width: "30%",
    height: "34px",
  },
  SkeletonThree: {
    width: "15%",
    height: "24px",
  },
  ErrorInput: {
    "&::part(base)": {
      border: "var(--sqm-border-thickness) solid var(--sqm-danger-color-border)",
      borderRadius: "var(--sqm-input-border-radius)",
    },
    "&::part(help-text)": {
      color: "var(--sqm-danger-color-text)",
    },
  },
};
const vanillaStyle = `
:host {
  display: block;
}
:host([hidden]): {
  display: none;
}

a {
  color: inherit;
  text-decoration: underline;
  cursor: pointer;
}

*::part(primarybutton-base),
sl-button[type="primary"]::part(base) {
  font-family: var(--sqm-primary-font);
  width: 100%;
  background-color: var(--sqm-primary-button-background);
  color: var(--sqm-primary-button-color);
  border-color: var(--sqm-primary-button-color-border);
  border-radius: var(--sqm-primary-button-radius);
}

*::part(primarybutton-base):hover,
sl-button[type="primary"]::part(base):hover{
  background-color: var(--sqm-primary-button-background-hover);
  border-color: var(--sqm-primary-button-border-color-hover);
  color: var(--sqm-primary-button-color-hover);
}


*::part(primarybutton-base):focus,
sl-button[type="primary"]::part(base):focus {
  box-shadow: none;
}

*::part(secondarybutton-base),
sl-button[type="secondary"]::part(base) {
font-family: var(--sqm-primary-font);
  background-color: var(--sqm-secondary-button-background);
  color: var(--sqm-secondary-button-color);
  border-color: var(--sqm-secondary-button-color-border);
  border-radius: var(--sqm-secondary-button-radius);
}

*::part(secondarybutton-base):hover,
sl-button[type="secondary"]::part(base):hover {
  background-color: var(--sqm-secondary-button-background-hover);
  color: var(--sqm-secondary-button-color-hover);
  border-color: var(--sqm-secondary-button-border-color-hover);
}

*::part(input-label), *::part(select-label), *::part(textarea-label){
  font-family: var(--sqm-primary-font);
  font-size: var(--sqm-input-label-font-size, var(--sl-input-font-size-small));
  font-weight: var(--sl-font-weight-semibold);
  color: var(--sqm-input-label-color, var(--sqm-text), black);
}

*::part(input-base), *::part(select-base), *::part(textarea-base){
  font-family: var(--sqm-primary-font);
  background-color: var(--sqm-input-background, #fff);
  border-radius: var(--sqm-input-border-radius, var(--sl-input-border-radius-large), 0.25rem);
  color: var(--sqm-input-color, white);
  border-width: var(--sqm-border-thickness, 1px);
}

*::part(input-base):hover, *::part(select-base):hover, *::part(textarea-base):hover{
  border-color: var(--sqm-border-color-hover);
}

*::part(input-base):focus, *::part(select-base):focus, *::part(textarea-base):focus{
  border-color: var(--sqm-border-color-focus);
}

sqm-name-fields::part(input-base) {
  font-family: var(--sqm-primary-font);
  background-color: var(--sqm-input-background, #fff);
  border-radius: var(--sqm-input-border-radius, var(--sl-input-border-radius-large), 0.25rem);
  color: var(--sqm-input-color, white);
  border-width: var(--sqm-border-thickness, 1px);
}

sl-input::part(base):focus,
sl-select::part(form-control-wrapper):focus,
sl-textarea::part(textarea-label):focus {
  border-color: var(--sqm-border-color-focus);
}

*::part(input-label):disabled, *::part(select-label):disabled, *::part(textarea-label):disabled{
  background: var(--sqm-input-disabled-background, #f5f5f5);
  color: var(--sqm-input-disabled-color, var(--sl-color-gray-600));
}

*::part(input):-webkit-autofill {
  box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
  -webkit-text-fill-color: var(--sqm-input-color, white) !important;
}

*::part(input):-webkit-autofill:hover {
  box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
  -webkit-text-fill-color: var(--sqm-input-color, white) !important;
}

*::part(input):-webkit-autofill:focus {
  box-shadow: 0 0 0 50px var(--sqm-input-background, #fff) inset !important;
  -webkit-text-fill-color: var(--sqm-input-color, white) !important;
}

*::part(input)::placeholder,
*::part(select)::placeholder, 
*::part(textarea)::placeholder {
  font-family: var(--sqm-primary-font);
  color: var(--sqm-text-subdued);
}

*::part(input)::-webkit-input-placeholder,
*::part(select)::-webkit-input-placeholder,
*::part(textarea)::-webkit-input-placeholder {
  font-family: var(--sqm-primary-font);
  color: var(--sqm-text-subdued);
}

*::part(input)::-moz-placeholder,
*::part(select)::-moz-placeholder,
*::part(textarea)::-moz-placeholder {
  font-family: var(--sqm-primary-font);
  opacity: 1; /* Firefox adds an opacity to placeholders by default */
  color: var(--sqm-text-subdued);
}

*::part(input)::-ms-input-placeholder,
*::part(select)::-ms-input-placeholder,
*::part(textarea)::-ms-input-placeholder {
  font-family: var(--sqm-primary-font);
  color: var(--sqm-text-subdued);
}


`;
const sheet = createStyleSheet(style);
const styleString = sheet.toString();
function WidgetEmailVerificationView(props) {
  const { states, callbacks, text } = props;
  const renderLoadingSkeleton = () => {
    return (h("div", { class: sheet.classes.Wrapper },
      h("sqm-skeleton", { height: "16px", width: "50%" }),
      h("sqm-skeleton", { height: "16px", width: "50%" }),
      h("sqm-skeleton", { height: "16px", width: "50%" }),
      h("sqm-skeleton", { height: "34px", width: "30%" }),
      h("sqm-skeleton", { height: "24px", width: "15%" }),
      h("sl-button", { submit: true, class: sheet.classes.ContinueButton, loading: true, exportparts: "base: primarybutton-base", type: "primary" }, text.sendCodeText)));
  };
  return (h("div", { part: "sqm-base" },
    h("style", { type: "text/css" },
      vanillaStyle,
      styleString),
    states.sendCodeError && (h("sqm-form-message", { type: "error" },
      h("p", { part: "alert-title" }, text.sendCodeErrorHeader),
      intl.formatMessage({
        id: "sendCodeErrorDescription",
        defaultMessage: text.sendCodeErrorDescription,
      }, {
        supportLink: (h("a", { target: "_blank", href: `mailto:advocate-support@impact.com` }, text.supportLink)),
      }))),
    states.initialLoading ? (renderLoadingSkeleton()) : (h("div", { class: sheet.classes.Wrapper },
      h(TextSpanView, { type: "p" }, text.verifyEmailHeaderText),
      h("sl-form", { "onSl-submit": callbacks.submitEmail },
        h("div", { class: sheet.classes.InputsContainer },
          h("sl-input", Object.assign({ exportparts: "label: input-label, base: input-base", label: text.emailLabel, value: states.email || "", type: "email", id: "email", name: "email", disabled: !!states.email || states.loading }, (states.error
            ? {
              class: sheet.classes.ErrorInput,
              helpText: text.emailValidationErrorText,
            }
            : {}))),
          h("sl-button", { submit: true, class: sheet.classes.ContinueButton, loading: states.loading, exportparts: "base: primarybutton-base", type: "primary" }, text.sendCodeText)))))));
}

const WidgetEmailVerification = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /**
     * @uiName Verify email widget header text
     */
    this.verifyEmailHeaderText = "Start by verifying your email. We’ll send you a code through our referral provider, impact.com.";
    /**
     * @uiName Send code to email alert header
     */
    this.sendCodeErrorHeader = "There was an error sending your code";
    /**
     * @uiName Support link text
     */
    this.supportLink = "support team";
    /**
     * @uiName Send code to email alert description
     */
    this.sendCodeErrorDescription = "Please try again. If this problem continues, contact our program {supportLink}.";
    /**
     * @uiName Email input label
     */
    this.emailLabel = "Email";
    /**
     * @uiName Send code button text
     */
    this.sendCodeText = "Send code";
    /**
     * @uiName Send code button text
     */
    this.emailValidationErrorText = "Please enter a valid email";
    h$1(this);
  }
  disconnectedCallback() { }
  getTextProps() {
    return getProps(this);
  }
  render() {
    const props = isDemo()
      ? useDemoWidgetEmailVerification(this)
      : useWidgetEmailVerification(this);
    return h(WidgetEmailVerificationView, Object.assign({}, props));
  }
};
function useDemoWidgetEmailVerification(props) {
  const setShowCode = En(SHOW_CODE_NAMESPACE);
  return cjs({
    states: {
      error: true,
      initialLoading: false,
      loading: false,
      email: "test@example.com",
      sendCodeError: true,
    },
    callbacks: {
      submitEmail: async () => setShowCode(true),
    },
    text: props.getTextProps(),
  }, props.demoData || {}, { arrayMerge: (_, a) => a });
}

export { WidgetEmailVerification as sqm_email_verification };
