import { h, Fragment } from "@stencil/core";
import { formatFullName, getActiveEntitlements, isValidEmail, VerdocsEndpoint } from "@verdocs/js-sdk";
import { getFeatureFlags } from "../../../utils/Unleash";
import { convertToE164 } from "../../../utils/utils";
const addrBookIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-book-user"><path d="M15 13a3 3 0 1 0-6 0"/><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/><circle cx="12" cy="8" r="2"/></svg>`;
/**
 * Display a contact picker suitable for filling out Recipient objects when sending Envelopes.
 *
 * This picker can also be integrated with a backend to provide contact list / suggestion / address-book style behavior. As the
 * user interacts with the component, the text entered in the name fields is sent back to the parent via the `searchContacts` event.
 * The parent can use that text as a query string to call a backend to obtain appropriate contacts to show. This list may also be
 * hard-coded ahead of time to provide the user with smart suggestions on initial display, such as "Recently Used" contacts, or
 * to always display the user's own contact record.
 *
 * ```ts
 * <verdocs-contact-picker
 *   templateRole={role}
 *   contactSuggestions={[]}
 *   onNext={e => console.log('Contact completed', e.detail)}
 *   />
 * ```
 */
export class VerdocsContactPicker {
    constructor() {
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The role that this contact will be assigned to.
         */
        this.templateRole = null;
        /**
         * If set, suggestions will be displayed in a drop-down list to the user. It is recommended that the number
         * of suggestions be limited to the 5 best matching records.
         */
        this.contactSuggestions = [];
        this.showSuggestions = false;
        this.showMessage = false;
        this.delegator = false;
        this.name_locked = false;
        this.auth_methods = [];
        this.passcode = '';
        this.firstNameFieldId = `verdocs-contact-picker-firstname-${Math.random().toString(36).substring(2, 11)}`;
        this.lastNameFieldId = `verdocs-contact-picker-lastname-${Math.random().toString(36).substring(2, 11)}`;
        this.emailFieldId = `verdocs-contact-picker-email-${Math.random().toString(36).substring(2, 11)}`;
        this.phoneFieldId = `verdocs-contact-picker-phone-${Math.random().toString(36).substring(2, 11)}`;
        this.featureFlags = null;
        this.activeEntitlements = {};
    }
    componentWillLoad() {
        this.endpoint.loadSession();
        if (this.templateRole) {
            const fullName = formatFullName(this.templateRole);
            const nameComponents = fullName.split(' ');
            const firstName = this.templateRole.first_name || nameComponents.shift() || '';
            const lastName = this.templateRole.last_name || nameComponents.join(' ') || '';
            this.first_name = firstName;
            this.last_name = lastName;
            this.email = this.templateRole.email || '';
            this.phone = this.templateRole.phone || '';
            // delegator and name_locked are mutually exclusive; delegator takes precedence if both are somehow set
            this.delegator = this.templateRole.delegator || false;
            this.name_locked = this.delegator ? false : (this.templateRole.name_locked || false);
            this.message = this.templateRole.message || '';
            this.showMessage = this.message !== '';
            this.auth_methods = this.templateRole.auth_methods || [];
            this.passcode = this.templateRole.passcode || '';
        }
        getActiveEntitlements(this.endpoint)
            .then(r => {
            this.activeEntitlements = r;
            console.log('[CONTACT PICKER] Loaded entitlements', r);
        })
            .catch(e => console.log('[CONTACT PICKER] Error loading entitlements, some features may be disabled.', e));
        getFeatureFlags()
            .then(flags => {
            this.featureFlags = flags;
            console.log('[CONTACT PICKER] Loaded feature flags', flags);
        })
            .catch(e => {
            console.log('[CONTACT PICKER] Unable to fetch feature flags, some features may be disabled.', e);
        });
    }
    handleFirstNameChange(e) {
        var _a;
        this.first_name = e.target.value;
        (_a = this.searchContacts) === null || _a === void 0 ? void 0 : _a.emit({ query: this.first_name });
    }
    handleLastNameChange(e) {
        var _a;
        this.last_name = e.target.value;
        (_a = this.searchContacts) === null || _a === void 0 ? void 0 : _a.emit({ query: this.last_name });
    }
    handleCancel(e) {
        var _a;
        e.stopPropagation();
        this.showSuggestions = false;
        (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit();
    }
    handleSubmit(e) {
        var _a;
        e.stopPropagation();
        this.showSuggestions = false;
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit({
            first_name: this.first_name,
            last_name: this.last_name,
            email: this.email,
            phone: this.phone,
            message: this.message,
            delegator: this.delegator,
            name_locked: this.name_locked,
            auth_methods: this.auth_methods,
            passcode: this.passcode,
            address: this.address,
            zip: this.zip,
        });
    }
    handleSelectSuggestion(e, suggestion) {
        e.stopPropagation();
        this.first_name = suggestion.first_name;
        this.last_name = suggestion.last_name;
        this.email = suggestion.email;
        this.phone = suggestion.phone;
        this.showSuggestions = false;
    }
    // The reason for the random names/IDs is to disable browser autocomplete. We set the autocomplete tags but many browsers ignore them
    // and show a duplicate autocomplete picker on top of our own.
    render() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
        // const hasBasics = this.first_name && this.last_name && (isValidEmail(this.email) || isValidPhone(this.phone));
        const hasBasics = this.first_name && this.last_name && isValidEmail(this.email);
        const hasAuthRequirements = !this.auth_methods.length ||
            (this.auth_methods.includes('passcode') && !!this.passcode) ||
            (this.auth_methods.includes('kba') && !!this.first_name && !!this.last_name) ||
            (this.auth_methods.includes('email') && !!this.email) ||
            (this.auth_methods.includes('sms') && !!this.phone);
        const canSubmit = hasBasics && hasAuthRequirements;
        const globalSMS = ((_c = (_b = (_a = this.featureFlags) === null || _a === void 0 ? void 0 : _a.toggles) === null || _b === void 0 ? void 0 : _b.find(t => t.name === 'sms')) === null || _c === void 0 ? void 0 : _c.enabled) === true;
        const verificationOptions = [];
        if (((_f = (_e = (_d = this.featureFlags) === null || _d === void 0 ? void 0 : _d.toggles) === null || _e === void 0 ? void 0 : _e.find(t => t.name === 'passcode-verification')) === null || _f === void 0 ? void 0 : _f.enabled) === true) {
            verificationOptions.push({ label: 'Passcode', value: 'passcode' });
        }
        if (((_j = (_h = (_g = this.featureFlags) === null || _g === void 0 ? void 0 : _g.toggles) === null || _h === void 0 ? void 0 : _h.find(t => t.name === 'email-verification')) === null || _j === void 0 ? void 0 : _j.enabled) === true) {
            verificationOptions.push({ label: 'Email', value: 'email' });
        }
        if (globalSMS && ((_m = (_l = (_k = this.featureFlags) === null || _k === void 0 ? void 0 : _k.toggles) === null || _l === void 0 ? void 0 : _l.find(t => t.name === 'sms-verification')) === null || _m === void 0 ? void 0 : _m.enabled) === true && !!this.activeEntitlements.sms_auth) {
            verificationOptions.push({ label: 'SMS (One-Time Code)', value: 'sms' });
        }
        if (((_q = (_p = (_o = this.featureFlags) === null || _o === void 0 ? void 0 : _o.toggles) === null || _p === void 0 ? void 0 : _p.find(t => t.name === 'kba-verification')) === null || _q === void 0 ? void 0 : _q.enabled) === true && !!this.activeEntitlements.kba_auth) {
            verificationOptions.push({ label: 'Knowledge-Based (KBA)', value: 'kba' });
        }
        if (((_t = (_s = (_r = this.featureFlags) === null || _r === void 0 ? void 0 : _r.toggles) === null || _s === void 0 ? void 0 : _s.find(t => t.name === 'id-verification')) === null || _t === void 0 ? void 0 : _t.enabled) === true && !!this.activeEntitlements.id_auth) {
            verificationOptions.push({ label: 'ID Check', value: 'id' });
        }
        return (h("form", { key: '374d6f0907e09a4c312bcd666eaabf578f8671b5', onSubmit: e => e.preventDefault(),
            // onClick={e => e.stopPropagation()}
            autocomplete: "off" }, h("div", { key: 'bbdb01e7229992ff75b3b124fde6a8606769d53c', class: "row" }, h("label", { key: '546da7ec599b17cc2e514dcaf47fe41d7107ec11', htmlFor: this.firstNameFieldId }, "Name:"), h("div", { key: 'e5819a8cb2c261c302a4923561578c5928063e64', class: "names-row" }, h("input", { key: '05a471f19b8018993d50f4ba9776864392c13c9d', id: this.firstNameFieldId, name: this.firstNameFieldId, type: "text", "data-lpignore": "true", autocomplete: "blocked", "aria-autocomplete": "none", value: this.first_name, placeholder: "First...", onFocus: () => {
                // Give the blur event a chance to hide it first if going between first/last
                setTimeout(() => {
                    var _a;
                    this.showSuggestions = ((_a = this.contactSuggestions) === null || _a === void 0 ? void 0 : _a.length) > 0;
                }, 100);
            }, onInput: e => this.handleFirstNameChange(e) }), h("input", { key: '4e56ab4161e6bd7894c636619282915243c8aeec', id: this.lastNameFieldId, name: this.lastNameFieldId, type: "text", "data-lpignore": "true", autocomplete: "blocked", "aria-autocomplete": "none", value: this.last_name, placeholder: "Last...", onFocus: () => {
                // Give the blur event a chance to hide it first if going between first/last
                setTimeout(() => {
                    var _a;
                    this.showSuggestions = ((_a = this.contactSuggestions) === null || _a === void 0 ? void 0 : _a.length) > 0;
                }, 100);
            }, onInput: e => this.handleLastNameChange(e) })), this.showSuggestions && (h("verdocs-portal", { key: '0a856517832b4dc417627675a0327e5a5e9e4710', anchor: this.firstNameFieldId, onClickAway: () => {
                this.showSuggestions = false;
                document.querySelectorAll(`.verdocs-portal-wrapper`).forEach(el => el.remove());
            }, id: "verdocs-contact-picker-suggestions" }, h("div", { key: '6c0c1747e5ed512ad463c26f220b34db395e8f2c', class: "dropdown" }, this.contactSuggestions
            .filter(suggestion => !this.first_name || suggestion.first_name.toLowerCase().includes(this.first_name.toLowerCase()))
            .map(suggestion => {
            var _a;
            return (h("div", { key: (_a = suggestion.id) !== null && _a !== void 0 ? _a : suggestion.email, class: "suggestion", onClick: e => this.handleSelectSuggestion(e, suggestion) }, suggestion.picture ? h("img", { alt: "Avatar", class: "avatar", src: suggestion.picture }) : h("div", { class: "avatar", innerHTML: addrBookIcon }), h("div", { class: "details" }, h("div", { class: "name" }, formatFullName(suggestion)), suggestion.email && h("div", { class: "destination" }, suggestion.email), suggestion.phone && h("div", { class: "destination" }, suggestion.phone))));
        }))))), h("div", { key: '85552b20424fb4884fa88d22c78375fe5c6513e0', class: "row" }, h("label", { key: '2b438ee30f3c0115d0445e3f5bfe4ae8b7635073', htmlFor: this.emailFieldId }, "Email:"), h("input", { key: 'a349fb9e534ed7786268d9aac9184fc38a8a102e', id: this.emailFieldId, name: this.emailFieldId, type: "text", "data-lpignore": "true", autoComplete: "blocked", "aria-autocomplete": "none", value: this.email, placeholder: "Invite/verify via email...", onFocus: () => (this.showSuggestions = false), onInput: (e) => (this.email = e.target.value) })), globalSMS && (h("div", { key: 'f015a535d0a37d94eb73b145342d00dde7b63a50', class: "row" }, h("label", { key: 'eff877e183e38de65ca11e535b81e11b5ee1bd92', htmlFor: this.phoneFieldId }, "Phone:"), h("input", { key: '41db6e4607189c0b0da0ef658b1fbafcfeab92ba', id: this.phoneFieldId, name: this.phoneFieldId, type: "text", "data-lpignore": "true", autoComplete: "blocked", "aria-autocomplete": "none", value: this.phone, placeholder: "Invite/verify via SMS...", onFocus: () => (this.showSuggestions = false), onInput: (e) => {
                this.phone = convertToE164(e.target.value);
            } }))), h(Fragment, { key: 'c037e234e206b1cd45bf91649f211ebe42f885fe' }, verificationOptions.length > 0 && (h("div", { key: '23fa9db672498199d7c053b258669e0676852322', class: "row pin-code" }, h("label", { key: 'd5208d3cd083716589aa6c18dbd85ba88ca208b3' }, "Verification Methods:"), h("div", { key: 'f239551b28d2ca51b8f9ab5ec64bfdfdce4bf823' }, verificationOptions.map((option, i) => (h("div", { class: "option" }, h("verdocs-checkbox", { size: "small", id: `verdocs-multi-select-opt-${i}`, value: option.value, checked: this.auth_methods.includes(option.value), onInput: (e) => {
                if (e.target.checked) {
                    this.auth_methods = [...this.auth_methods, option.value];
                }
                else {
                    this.auth_methods = this.auth_methods.filter(selected => selected !== option.value);
                }
            } }), h("label", { htmlFor: `verdocs-multi-select-option-${i}` }, option.label))))))), this.auth_methods.includes('passcode') && (h("div", { key: 'd57e7078dfefb1c816a15c52a8aa44eae62a5557', class: "row pin-code" }, h("label", { key: 'df97978ae0e4c176c7d6ca38850537d3d6db5ce3', htmlFor: this.phoneFieldId }, "Passcode:"), h("input", { key: '7791e5a2d856bdd9dbbfcf8c339531e3e5c5e52b', id: "verdocs-passcode", name: "verdocs-passcode", type: "text", "data-lpignore": "true", autocomplete: "blocked", "aria-autocomplete": "none", value: this.passcode, placeholder: "4-8 digits recommended...", onFocus: () => (this.showSuggestions = false), onInput: (e) => (this.passcode = e.target.value) })))), h("div", { key: '7de2d50963399db273bd1d38941ea967a2d92827', class: "row pin-code" }, h("label", { key: 'd0202a6e0969b405d303cdc291dee95048460b43', style: { marginTop: '6px' } }, "Options:"), h("div", { key: '52f68972a5fee697972fa9baa284ca6a37830ab9' }, h("div", { key: '8e15a3caa1e4ce0cbb943fb7bfaaf274d4410de3', class: "option" }, h("verdocs-checkbox", { key: '7d21cafec340458f1c6a06b577fad30bbd5680eb', size: "small", id: "verdocs-delegator", checked: this.delegator, disabled: this.name_locked, onInput: (e) => {
                this.delegator = e.target.checked;
                if (this.delegator)
                    this.name_locked = false;
            } }), h("label", { key: '2b96fb477ce41038cf9d115e9fabf102d670d801', htmlFor: "verdocs-delegator" }, "May delegate signing")), h("div", { key: '7f616562ee03e6026bf09b355ae20720b45655b0', class: "option" }, h("verdocs-checkbox", { key: '47bfa40e403ddf6da8cba33fda8ebff05625d353', size: "small", id: "verdocs-name-locked", checked: this.name_locked, disabled: this.delegator, onInput: (e) => {
                this.name_locked = e.target.checked;
                if (this.name_locked)
                    this.delegator = false;
            } }), h("label", { key: '382d0b92f8999dc1a0adaa91d00c6c0f95a17552', htmlFor: "verdocs-name-locked" }, "Name locked")))), h("div", { key: '6797886d95d1e08dc0c018e89cf6040aa60b02ff', class: "row message" }, h("label", { key: 'cb6f04c40e1b6601d0292e248b26cb4f2519e7d9', htmlFor: "verdocs-contact-picker-message" }, "Message:"), h("textarea", { key: '018a9162f52e73650283a7f2271a99352008085c', id: "verdocs-contact-picker-message", name: "verdocs-contact-picker-message", "data-lpignore": "true", autocomplete: "blocked", placeholder: "Optional message to include in invitation...", onFocus: () => (this.showSuggestions = false), onInput: (e) => (this.message = e.target.value) }, this.message)), h("div", { key: 'd2f04563ad450f4c6c0c19735a064d01182cf458', class: "buttons" }, h("div", { key: '43f240077f3c5b3e252c60a277668c94c9163b24', class: "flex-fill" }), h("verdocs-button", { key: 'f758cb6d10b3deb58d13aaf54c212e6455933104', variant: "outline", label: "Cancel", size: "small", onClick: e => this.handleCancel(e) }), h("verdocs-button", { key: '3aa451a2d6d23ada4a7a5ddb5843b22954b69161', label: "OK", size: "small", disabled: !canSubmit, onClick: !canSubmit ? () => { } : e => this.handleSubmit(e) }))));
    }
    static get is() { return "verdocs-contact-picker"; }
    static get originalStyleUrls() {
        return {
            "$": ["verdocs-contact-picker.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["verdocs-contact-picker.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "VerdocsEndpoint",
                    "resolved": "VerdocsEndpoint",
                    "references": {
                        "VerdocsEndpoint": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::VerdocsEndpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "VerdocsEndpoint.getDefault()"
            },
            "templateRole": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Partial<IRecipient> | null",
                    "resolved": "{ id?: string; envelope_id?: string; role_name?: string; profile_id?: string; status?: TRecipientStatus; first_name?: string; last_name?: string; full_name?: string; email?: string; phone?: string; address?: string; city?: string; state?: string; zip?: string; ssn_last_4?: string; disclosures?: string; disclosures_accepted_at?: string; dob?: string; sequence?: number; order?: number; type?: TRecipientType; delegator?: boolean; delegated_to?: string; message?: string; claimed?: boolean; agreed?: boolean; name_locked?: boolean; key_used_to_conclude?: string; environment?: string; created_at?: string; updated_at?: string; last_attempt_at?: string; in_app_key?: string; auth_step?: TRecipientAuthStep; auth_methods?: TRecipientAuthMethod[]; auth_method_states?: Record<TRecipientAuthMethod, \"complete\" | \"failed\" | \"challenge\" | \"questions\" | \"differentiator\">; passcode?: string; kba_questions?: IKBAQuestion[]; envelope?: IEnvelope; profile?: IProfile; }",
                    "references": {
                        "Partial": {
                            "location": "global",
                            "id": "global::Partial"
                        },
                        "IRecipient": {
                            "location": "import",
                            "path": "@verdocs/js-sdk",
                            "id": "node_modules::IRecipient"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The role that this contact will be assigned to."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "null"
            },
            "contactSuggestions": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "TPickerContact[]",
                    "resolved": "Partial<IProfile>[]",
                    "references": {
                        "TPickerContact": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx",
                            "id": "src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx::TPickerContact"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If set, suggestions will be displayed in a drop-down list to the user. It is recommended that the number\nof suggestions be limited to the 5 best matching records."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "first_name": {},
            "last_name": {},
            "email": {},
            "phone": {},
            "zip": {},
            "address": {},
            "message": {},
            "showSuggestions": {},
            "showMessage": {},
            "delegator": {},
            "name_locked": {},
            "auth_methods": {},
            "passcode": {},
            "firstNameFieldId": {},
            "lastNameFieldId": {},
            "emailFieldId": {},
            "phoneFieldId": {},
            "featureFlags": {},
            "activeEntitlements": {}
        };
    }
    static get events() {
        return [{
                "method": "searchContacts",
                "name": "searchContacts",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user enters text in the search field. The calling application may use this to update\nthe `contactSuggestions` property."
                },
                "complexType": {
                    "original": "IContactSearchEvent",
                    "resolved": "IContactSearchEvent",
                    "references": {
                        "IContactSearchEvent": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx",
                            "id": "src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx::IContactSearchEvent"
                        }
                    }
                }
            }, {
                "method": "exit",
                "name": "exit",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the step is cancelled. This is called exit to avoid conflicts with the JS-reserved \"cancel\" event name."
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "next",
                "name": "next",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event fired when the user changes the type."
                },
                "complexType": {
                    "original": "IContactSelectEvent",
                    "resolved": "IContactSelectEvent",
                    "references": {
                        "IContactSelectEvent": {
                            "location": "local",
                            "path": "/Users/chad/projects/verdocs/web-sdk/verdocs-web-sdk/src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx",
                            "id": "src/components/envelopes/verdocs-contact-picker/verdocs-contact-picker.tsx::IContactSelectEvent"
                        }
                    }
                }
            }];
    }
}
//# sourceMappingURL=verdocs-contact-picker.js.map
