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.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 || '';
            this.delegator = this.templateRole.delegator || 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,
            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: '5b4d4de3ad06d4cb458b92ca6159fadcbb38a89e', onSubmit: e => e.preventDefault(),
            // onClick={e => e.stopPropagation()}
            autocomplete: "off" }, h("div", { key: '065bd43ea84a5431f4cb370491147377d0b4ed87', class: "row" }, h("label", { key: '48e3ab3a13607b42018e400703910d08f053d7c0', htmlFor: this.firstNameFieldId }, "Name:"), h("div", { key: 'c1acb5b9cfd0cdbd17edce151e66035826ae3e15', class: "names-row" }, h("input", { key: 'bfd3f91624725b717df1b27d000924503e0cb0b8', 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: '30ae8e6b5c52c45bad07572a9357c575fd248df1', 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: '6a03422c1dbe45c1e8a389af0f884f2f4b525aca', anchor: this.firstNameFieldId, onClickAway: () => {
                this.showSuggestions = false;
                document.querySelectorAll(`.verdocs-portal-wrapper`).forEach(el => el.remove());
            }, id: "verdocs-contact-picker-suggestions" }, h("div", { key: 'a9907d3c7b291fde2e86a3a0dd2bfb0f2c1d06b3', 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: '220b7dc0f04eb27279e003aaa196aee58b51ec64', class: "row" }, h("label", { key: '7120d789f96a375a3f6237b93a3699866dae5e0e', htmlFor: this.emailFieldId }, "Email:"), h("input", { key: '33aa0973927dedcc1d3005411dcdb87c969a65c2', 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: '8b888dd8490d99235bd1d1b2e6acce6d64fbf5a4', class: "row" }, h("label", { key: '702e60156cfbe39cc56c20ca5f9e5b112eb8fbb5', htmlFor: this.phoneFieldId }, "Phone:"), h("input", { key: '1f6b416d622b821e63e89bdf75626bc9f97422df', 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: '60d3ccc50417d1fbe6a815d6edf37619f945b63e' }, verificationOptions.length > 0 && (h("div", { key: 'f1248b2c40c1cfb22cfa577bc1f5c5895362ded2', class: "row pin-code" }, h("label", { key: 'd782f794fa6a8d2ca18835db9e8d6e510038f212' }, "Verification Methods:"), h("div", { key: '51370acfa10be18fa7783ee28849caaf9ad11fcb' }, 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: '37cc47ae07fcee96a90ca0684307b2fa12436fbd', class: "row pin-code" }, h("label", { key: '57b9975fcdf609ebcfd709f2cc646f74163eda15', htmlFor: this.phoneFieldId }, "Passcode:"), h("input", { key: '5c9f4d7f4757512fa7c87e91adf731fe256050da', 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: '7bed0f7befff14122e821680fce895d64889212c', class: "row pin-code" }, h("label", { key: '295f03231ca15e2a25895d8f6dca7b7507fc58fa' }, "Delegation:"), h("div", { key: '21d03961df0853b3f1e4a4b3e9445e8a3ecf80ee' }, h("div", { key: '1e70e144d4e678e9697039468549ef38606dc3b7', class: "option" }, h("verdocs-checkbox", { key: '8f94ea2d0b3f1bc8831c8666d379ebc2a22fbb95', size: "small", id: "verdocs-delegator", checked: this.delegator, onInput: (e) => {
                this.delegator = e.target.checked;
            } }), h("label", { key: '9ea3f9f359f7045aebd80367af0a7431d1e850e4', htmlFor: "verdocs-delegator" }, "May delegate signing")))), h("div", { key: '90e07660115c7f41ade3aad5fe4eb93d7d8cb4fd', class: "row message" }, h("label", { key: '0268f3ecd123de3c8d0e27b345253385157bfce6', htmlFor: "verdocs-contact-picker-message" }, "Message:"), h("textarea", { key: '526671a3e768cc6280e82d04fe4f86d0fd5678bd', 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: '9bfb44085c94a08a9d2957d031e263d398ab170b', class: "buttons" }, h("div", { key: '2b21510d850071094dd7005c26de4e8cd14c992d', class: "flex-fill" }), h("verdocs-button", { key: '881527d8167c31490622f3e9f0252cfdd3139d58', variant: "outline", label: "Cancel", size: "small", onClick: e => this.handleCancel(e) }), h("verdocs-button", { key: '3dbc5efa49eb696eedb2d50c06837b70abea5e80', 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",
                "attribute": "endpoint",
                "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",
                "attribute": "template-role",
                "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; 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",
                "attribute": "contact-suggestions",
                "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": {},
            "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
