import { p as proxyCustomElement, H, c as createEvent, h } from './p-AiOs8RvA.js';
import { VerdocsEndpoint, createProfile, verifyEmail, authenticate, getMyUser, resendVerification, resetPassword } from '@verdocs/js-sdk';
import { V as VerdocsToast } from './p-CyvDgtoV.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { d as defineCustomElement$4 } from './p-DMVmShTi.js';
import { d as defineCustomElement$3 } from './p-Bbomvxyl.js';
import { d as defineCustomElement$2 } from './p-xz67XcVg.js';

const verdocsAuthCss = "@-webkit-keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}@keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}verdocs-auth{font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center}verdocs-auth .form{width:320px;display:-ms-flexbox;display:flex;padding:20px;max-width:90%;-ms-flex-align:center;align-items:center;-ms-flex-direction:column;flex-direction:column;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-flex-pack:center;justify-content:center;background:#ffffff}verdocs-auth .logo{width:128px;max-width:100%;margin:20px 0 30px}verdocs-auth h3{color:#092c4c;text-align:center;font-weight:400;font-size:18px;line-height:1.75;margin:0}verdocs-auth em{font-size:14px;margin:15px 0}verdocs-auth .buttons{gap:20px;margin:20px 0 0 0;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:center;justify-content:center}verdocs-auth .status-result{display:none}verdocs-auth .status-result.debug{white-space:pre-wrap;font-size:14px;background:#fff;padding:10px;display:block;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:center;justify-content:center}verdocs-auth form{width:100%}verdocs-auth verdocs-text-input{margin-bottom:10px}verdocs-auth .account-option{gap:8px;margin:20px 0 8px 0;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row}verdocs-auth p{color:#092c4c;margin:1em 0;font-size:14px}verdocs-auth p+p{margin-top:0}verdocs-auth verdocs-help-icon{margin-top:18px;display:-ms-flexbox;display:flex;width:32px;height:32px;-ms-flex:0 0 32px;flex:0 0 32px}verdocs-auth .already-have{color:#092c4c;margin:0.5em 0;font-size:14px}";

const VerdocsAuth$1 = /*@__PURE__*/ proxyCustomElement(class VerdocsAuth extends H {
    constructor() {
        super();
        this.__registerHost();
        this.authenticated = createEvent(this, "authenticated");
        this.sdkError = createEvent(this, "sdkError");
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * Normally, if the user has a valid session, this embed will be invisible, otherwise it will display
         * login / signup forms. If this is set to false, this embed will be invisible in both cases. Apps may
         * use this to verify if a user has a valid session without needing a separate call to Verdocs JS SDK.
         */
        this.visible = true;
        /**
         * By default, a Verdocs logo will be displayed above the login/signup forms. This may be used to
         * override its source. (Alternatively, you may simply hide it via CSS overrides.) Logos should be
         * in SVG format for best results.
         */
        this.logo = 'https://app.verdocs.com/assets/blue-logo.svg';
        /**
         * The display mode to start in.
         */
        this.displayMode = 'login';
        this.org_name = '';
        this.first_name = '';
        this.last_name = '';
        this.email = '';
        this.verificationCode = '';
        this.newPassword = '';
        this.password = '';
        this.confirmpass = '';
        this.submitting = false;
        this.resendDisabled = false;
        this.session = null;
        this.profile = null;
        this.resendDisabledTimer = null;
        // We can't instantly log in on the default endpoint because other listeners might see
        // its events and incorrectly trigger before we're done. So we manage our own temp
        // endpoint and pass the final tokens to the default once we're ready.
        this.tempAuthEndpoint = new VerdocsEndpoint({
            baseURL: VerdocsEndpoint.getDefault().getBaseURL(),
            persist: false,
        });
    }
    componentWillLoad() {
        this.endpoint.loadSession();
        VerdocsEndpoint.getDefault().onSessionChanged((_endpoint, session, profile) => {
            var _a, _b;
            this.session = session;
            this.profile = profile;
            if (session) {
                (_a = this.authenticated) === null || _a === void 0 ? void 0 : _a.emit({ authenticated: true, session, profile });
            }
            else {
                (_b = this.authenticated) === null || _b === void 0 ? void 0 : _b.emit({ authenticated: false, session, profile });
            }
        });
    }
    isPasswordComplex(password) {
        const isUppercase = (ch) => /[A-Z]/.test(ch);
        const isLowercase = (ch) => /[a-z]/.test(ch);
        const isSpecialChar = (ch) => /[`!@#$%^&*()_\-+=\[\]{};':"\\|,.<>\/?~ ]/.test(ch);
        let countOfUpperCase = 0, countOfLowerCase = 0, countOfSpecialChar = 0;
        for (let i = 0; i < password.length; i++) {
            let ch = password.charAt(i);
            if (isUppercase(ch))
                countOfUpperCase++;
            else if (isLowercase(ch))
                countOfLowerCase++;
            else if (isSpecialChar(ch))
                countOfSpecialChar++;
        }
        return password.length >= 8 && countOfLowerCase > 0 && countOfUpperCase > 0 && countOfSpecialChar > 0;
    }
    handleSignup() {
        if (!this.isPasswordComplex(this.password)) {
            VerdocsToast('Password must be at least 8 characters long and contain at least one uppercase, one lowercase, and one special character.', { style: 'error' });
            return;
        }
        if (this.password !== this.confirmpass) {
            VerdocsToast('Passwords do not match.', { style: 'error' });
            return;
        }
        this.submitting = true;
        this.tempAuthEndpoint.clearSession();
        createProfile(this.tempAuthEndpoint, {
            email: this.email,
            password: this.password,
            first_name: this.first_name,
            last_name: this.last_name,
            org_name: this.org_name,
        })
            .then(r => {
            if (r.intercom_key) {
                localStorage.setItem('intercom_key', r.intercom_key);
            }
            console.log('[AUTH] Profile creation result', r);
            this.tempAuthEndpoint.setToken(r.access_token);
            // We can't clearForms because we need email to stick around
            this.password = '';
            this.first_name = '';
            this.last_name = '';
            this.org_name = '';
            this.displayMode = 'verify';
            this.submitting = false;
        })
            .catch(e => {
            var _a, _b, _c, _d, _e, _f;
            console.log('[AUTH] Signup error', e.response);
            this.submitting = false;
            (_a = this.authenticated) === null || _a === void 0 ? void 0 : _a.emit({ authenticated: false, profile: null, session: null });
            (_b = this.sdkError) === null || _b === void 0 ? void 0 : _b.emit(new SDKError(e.message, (_c = e.response) === null || _c === void 0 ? void 0 : _c.status, (_d = e.response) === null || _d === void 0 ? void 0 : _d.data));
            VerdocsToast('Signup failed: ' + ((_f = (_e = e.response) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.error) || 'Unknown Error', { style: 'error' });
        });
    }
    async handleVerification() {
        this.submitting = true;
        try {
            this.submitting = false;
            const verificationResult = await verifyEmail(this.tempAuthEndpoint, { email: this.email, token: this.verificationCode });
            VerdocsToast('Thank you for verifying your email address.', { style: 'success' });
            this.completeLogin(verificationResult);
        }
        catch (e) {
            this.submitting = false;
            console.log('Verification error', e);
            VerdocsToast('Verification error, please check the code and try again.');
        }
    }
    completeLogin(result) {
        this.clearForms();
        this.tempAuthEndpoint.clearSession();
        this.endpoint.setToken(result.access_token);
        if (result.intercom_key) {
            localStorage.setItem('intercom_key', result.intercom_key);
        }
    }
    async loginAndCheckVerification() {
        var _a;
        if (this.submitting) {
            return;
        }
        this.submitting = true;
        this.tempAuthEndpoint.clearSession();
        try {
            this.submitting = false;
            const authResult = await authenticate(this.tempAuthEndpoint, { username: this.email.trim(), password: this.password, grant_type: 'password' });
            console.log('[AUTH] Authenticated, checking email verification');
            this.tempAuthEndpoint.setToken(authResult.access_token);
            if (authResult.intercom_key) {
                localStorage.setItem('intercom_key', authResult.intercom_key);
            }
            const user = await getMyUser(this.tempAuthEndpoint);
            console.log('Got user', user);
            if (!user.email_verified) {
                console.log('[AUTH] Logged in, pending email address verification');
                this.displayMode = 'verify';
            }
            else {
                console.log('[AUTH] Email address is verified, completing login');
                this.completeLogin(authResult);
            }
        }
        catch (e) {
            this.submitting = false;
            console.log('[AUTH] Auth failure', ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) || e);
            VerdocsToast('Login failed. Please check your credentials and try again.', { style: 'error' });
        }
    }
    clearForms() {
        this.submitting = false;
        this.resendDisabled = false;
        this.email = '';
        this.password = '';
        this.newPassword = '';
        this.confirmpass = '';
        this.verificationCode = '';
        this.first_name = '';
        this.last_name = '';
        this.org_name = '';
    }
    handleLogout() {
        console.log('logging out');
        this.endpoint.clearSession();
        this.tempAuthEndpoint.clearSession();
        this.clearForms();
        this.displayMode = 'login';
    }
    handleResendVerification() {
        // Avoid the user just click-spamming this pathway. The server rate-limits this anyway so it's not a
        // security issue but it's a poor user experience to allow it.
        this.resendDisabled = true;
        this.resendDisabledTimer = setTimeout(() => {
            this.resendDisabled = false;
            this.resendDisabledTimer = null;
        }, 30000);
        resendVerification(this.tempAuthEndpoint)
            .then(r => {
            console.log('[AUTH] Verification request resent', r);
            VerdocsToast('Please check your email for a verification code.', { style: 'info' });
        })
            .catch((e) => {
            console.log('[AUTH] Unable to resend verification', e);
            VerdocsToast('Unable to resend code. Please try again later.', { style: 'error' });
        });
    }
    handleResendReset() {
        // Avoid the user just click-spamming this pathway. The server rate-limits this anyway so it's not a
        // security issue but it's a poor user experience to allow it.
        this.resendDisabled = true;
        this.resendDisabledTimer = setTimeout(() => {
            this.resendDisabled = false;
            this.resendDisabledTimer = null;
        }, 30000);
        resetPassword(this.tempAuthEndpoint, { email: this.email })
            .then(r => {
            console.log('[AUTH] Resend-code request resent', r);
            VerdocsToast('Please check your email again for a verification code.', { style: 'info' });
        })
            .catch((e) => {
            console.log('[AUTH] Unable to resend reset request', e);
            VerdocsToast('Unable to resend code. Please try again later.', { style: 'error' });
        });
    }
    async handleResetGetCode() {
        this.submitting = true;
        this.confirmpass = '';
        this.newPassword = '';
        try {
            this.submitting = false;
            const result = await resetPassword(this.endpoint, { email: this.email });
            console.log('[AUTH] Reset result', result);
            VerdocsToast('Please check your email inbox for a password reset code.', { style: 'success' });
            this.verificationCode = '';
            this.confirmpass = '';
            this.newPassword = '';
            this.displayMode = 'reset';
        }
        catch (e) {
            this.submitting = false;
            console.log('Reset request error', e);
            VerdocsToast('Request failed. Please check your email address and try again.');
        }
    }
    async handleResetPassword() {
        if (!this.isPasswordComplex(this.newPassword)) {
            VerdocsToast('Password must be at least 8 characters long and contain at least one uppercase, one lowercase, and one special character.', { style: 'error' });
            return;
        }
        if (this.newPassword !== this.confirmpass) {
            VerdocsToast('Passwords do not match.', { style: 'error' });
            return;
        }
        this.submitting = true;
        try {
            this.submitting = false;
            const resetResult = await resetPassword(this.endpoint, { email: this.email, code: this.verificationCode, new_password: this.newPassword });
            console.log('reset result', resetResult);
            VerdocsToast('Your password has been reset. You may now use your new password to login.', { style: 'success' });
            this.verificationCode = '';
            this.confirmpass = '';
            this.newPassword = '';
            this.password = '';
            this.displayMode = 'login';
        }
        catch (e) {
            this.submitting = false;
            console.log('Verification error', e);
            VerdocsToast('Verification error, please check the code and try again.');
        }
    }
    async handleReset() {
        this.submitting = true;
        try {
            const result = await resetPassword(this.endpoint, { email: this.email });
            console.log('[AUTH] Reset sent', result);
            this.submitting = false;
            this.displayMode = 'login';
            VerdocsToast('If your email address is registered, you will receive instructions on resetting your password shortly.', { style: 'info' });
        }
        catch (e) {
            console.log('[AUTH] Unable to reset password', e);
            this.submitting = false;
            VerdocsToast('Unable to reset password. Please check your email address and try again.', { style: 'error' });
        }
    }
    render() {
        if (!this.visible) {
            return h("div", { style: { display: 'none' } }, "Authenticated");
        }
        if (this.session) {
            return (h("verdocs-button", { label: "Sign Out", disabled: this.submitting, onClick: () => this.handleLogout(), style: { display: 'flex', justifyContent: 'center', margin: '30px auto 0' } }));
        }
        if (this.displayMode === 'signup') {
            const invalid = this.submitting || !this.first_name || !this.last_name || !this.email || !this.password || !this.confirmpass || !this.org_name;
            return (h("div", { class: "form" }, h("a", { href: "https://verdocs.com/en/" }, h("img", { src: this.logo, alt: "Verdocs Logo", class: "logo" })), h("h3", null, "Sign up for a free account"), h("div", { class: "already-have" }, "Already have an account?", h("verdocs-button", { label: "Log In", variant: "text", onClick: () => (this.displayMode = 'login'), disabled: this.submitting })), h("form", { onSubmit: () => this.handleSignup() }, h("div", { style: { display: 'flex', flexDirection: 'row', columnGap: '20px' } }, h("verdocs-text-input", { label: "First Name", autocomplete: "first", required: true, value: this.first_name, onInput: (e) => (this.first_name = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Last Name", autocomplete: "last", required: true, value: this.last_name, onInput: (e) => (this.last_name = e.target.value), disabled: this.submitting })), h("verdocs-text-input", { label: "Email Address", autocomplete: "email", required: true, value: this.email, onInput: (e) => (this.email = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Password", type: "password", required: true, autocomplete: "new-password", value: this.password, onInput: (e) => (this.password = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Confirm Password", type: "password", required: true, autocomplete: "off", value: this.confirmpass, onInput: (e) => (this.confirmpass = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Organization Name", autocomplete: "org", required: true, value: this.org_name, onInput: (e) => (this.org_name = e.target.value), disabled: this.submitting, style: { flex: '1' } }), h("div", { style: { marginTop: '30px' } }), h("verdocs-button", { label: "Next", disabled: invalid, onClick: invalid ? () => { } : () => this.handleSignup(), style: { display: 'flex', justifyContent: 'center', margin: '30px auto 0' } }))));
        }
        if (this.displayMode === 'verify') {
            return (h("div", { class: "form" }, h("form", { onSubmit: () => this.handleVerification() }, h("p", null, "Please check your e-mail inbox for a verification code and enter it below."), h("verdocs-text-input", { label: "Verification Code", required: true, value: this.verificationCode, onInput: (e) => (this.verificationCode = e.target.value), disabled: this.submitting }), h("div", { class: "buttons" }, h("verdocs-button", { label: "Sign Out", variant: "outline", disabled: this.submitting, onClick: () => this.handleLogout() }), h("verdocs-button", { label: "Verify", disabled: this.submitting || !this.verificationCode || this.verificationCode.length !== 6, onClick: () => this.handleVerification() })), h("div", { class: "buttons" }, h("verdocs-button", { variant: "text", label: "Resend Code", disabled: this.resendDisabled || this.submitting, onClick: () => this.handleResendVerification() })))));
        }
        if (this.displayMode === 'forgot') {
            return (h("div", { class: "form" }, h("a", { href: "https://verdocs.com/en/" }, h("img", { src: this.logo, alt: "Verdocs Logo", class: "logo" })), h("h3", null, "Forgot your password?"), h("p", null, "Enter your e-mail address below. If the e-mail address is valid, a password reset code will be sent to your inbox. Please allow up to 15 minutes to arrive, and check your spam folder if you do not receive the message."), h("form", { onSubmit: () => this.handleResetGetCode() }, h("verdocs-text-input", { label: "Email Address", autocomplete: "email", required: true, value: this.email, onInput: (e) => (this.email = e.target.value), disabled: this.submitting }), h("div", { style: { marginTop: '30px' } }), h("div", { class: "buttons" }, h("verdocs-button", { size: "small", label: "Cancel", variant: "outline", disabled: this.submitting, onClick: () => (this.displayMode = 'login') }), h("verdocs-button", { size: "small", label: "Request Code", disabled: this.submitting, onClick: () => this.handleResetGetCode() })))));
        }
        if (this.displayMode === 'reset') {
            return (h("div", { class: "form" }, h("a", { href: "https://verdocs.com/en/" }, h("img", { src: this.logo, alt: "Verdocs Logo", class: "logo" })), h("h3", null, "Forgot your password?"), h("p", null, "Enter your e-mail address below, and reset instructions will be sent to your Inbox. Please allow up to 15 minutes to arrive. Check your spam folder if you do not receive the message."), h("form", { onSubmit: () => this.handleResetPassword() }, h("verdocs-text-input", { label: "Verification Code", required: true, value: this.verificationCode, onInput: (e) => (this.verificationCode = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Password", type: "password", required: true, autocomplete: "off", value: this.newPassword, onInput: (e) => (this.newPassword = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Confirm Password", type: "password", required: true, autocomplete: "off", value: this.confirmpass, onInput: (e) => (this.confirmpass = e.target.value), disabled: this.submitting }), h("div", { style: { marginTop: '30px' } }), h("div", { class: "buttons" }, h("verdocs-button", { label: "Cancel", variant: "outline", disabled: this.submitting, onClick: () => (this.displayMode = 'login') }), h("verdocs-button", { label: "Reset", disabled: this.submitting, onClick: () => this.handleResetPassword() })), h("div", { class: "buttons" }, h("verdocs-button", { variant: "text", label: "Resend Code", disabled: this.resendDisabled || this.submitting, onClick: () => this.handleResendReset() })))));
        }
        return (h("div", { class: "form" }, h("a", { href: "https://verdocs.com/en/" }, h("img", { src: this.logo, alt: "Verdocs Logo", class: "logo" })), h("h3", null, "Log in to your account"), h("div", { class: "already-have" }, "Don't have an account?", h("verdocs-button", { label: "Sign Up", variant: "text", onClick: () => (this.displayMode = 'signup'), disabled: this.submitting })), h("form", { onSubmit: () => this.loginAndCheckVerification() }, h("verdocs-text-input", { label: "Email", autocomplete: "username", value: this.email, onInput: (e) => (this.email = e.target.value), disabled: this.submitting }), h("verdocs-text-input", { label: "Password", type: "password", autocomplete: "current-password", value: this.password, onInput: (e) => (this.password = e.target.value), disabled: this.submitting }), h("verdocs-button", { label: "Forgot Your Password?", variant: "text", onClick: () => (this.displayMode = 'forgot'), disabled: this.submitting, style: { display: 'flex', justifyContent: 'center', margin: '10px auto 20px' } }), h("verdocs-button", { label: "Login", disabled: this.submitting, onClick: () => this.loginAndCheckVerification(), style: { display: 'flex', justifyContent: 'center', margin: '10px auto 0' } }))));
    }
    static get style() { return verdocsAuthCss; }
}, [0, "verdocs-auth", {
        "endpoint": [16],
        "visible": [4],
        "logo": [1],
        "displayMode": [1025, "display-mode"],
        "org_name": [32],
        "first_name": [32],
        "last_name": [32],
        "email": [32],
        "verificationCode": [32],
        "newPassword": [32],
        "password": [32],
        "confirmpass": [32],
        "submitting": [32],
        "resendDisabled": [32],
        "session": [32],
        "profile": [32]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-auth", "verdocs-button", "verdocs-help-icon", "verdocs-text-input"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-auth":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsAuth$1);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-help-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-text-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}

const VerdocsAuth = VerdocsAuth$1;
const defineCustomElement = defineCustomElement$1;

export { VerdocsAuth, defineCustomElement };
//# sourceMappingURL=verdocs-auth.js.map

//# sourceMappingURL=verdocs-auth.js.map