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: 'cba230aed78c493105a007d965938ef36c0676c5', onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("div", { key: '436c7454a56df0f535f3aefdfff577a88dafa22c', class: "row" }, h("label", { key: 'b281d4c25f7b940d50700f808cdc9e7c3e235c63', htmlFor: this.firstNameFieldId }, "Name:"), h("div", { key: 'ef6316233086a5b6f7d5230e64134d3d4d370401', class: "names-row" }, h("input", { key: 'bb1114f98ee766c4da332c635e9aabfddb0ea0c5', 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: '8165b6a10ccec8cc699965a0e457c4984ba7e6d9', 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: '50bb3ba19b9ebedaf5dc6b42ab9ee56b49baf316', anchor: this.firstNameFieldId, onClickAway: () => (this.showSuggestions = false), id: "verdocs-contact-picker-suggestions" }, h("div", { key: '06d909db8340e219f56520cba088f39d024e23c9', 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: '0fd66b40717c81b65a301ced6b6bf4b6ff7b6626', class: "row" }, h("label", { key: '70956784b72087d8c1868595ec40dfbdee34ca87', htmlFor: this.emailFieldId }, "Email:"), h("input", { key: '35582c90e48b6f532fc75cc51525ca06162ebcc8', 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: '626950e0213dbc8fab07af0ac7682db19638c73c', class: "row" }, h("label", { key: '12cfdd054564af5cc3573785d884c87b7b50bae4', htmlFor: this.phoneFieldId }, "Phone:"), h("input", { key: '8ecb757d6ee8acf6041c75f4fc0621ece470fcdf', 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: '2023b0c925497df85590f0294597c38bde90b1da' }, verificationOptions.length > 0 && (h("div", { key: 'eb16a51636c12027f228714283bc3a045b04f364', class: "row" }, h("label", { key: 'c53d976fa49aa4ff32d6e176aed1a425a19befca' }, "Recipient Verification:"), h("verdocs-multiselect", { key: '6b84fd7b99c4b4f9e21242d444ead7238d3b12ec', label: "", placeholder: "None", options: verificationOptions, selectedOptions: this.auth_methods, onSelectionChanged: (e) => {
                this.auth_methods = e.detail.selectedOptions;
            } }))), this.auth_methods.includes('passcode') && (h("div", { key: '6e5059ea257eef3f44090348d5b264a0d4fca331', class: "row pin-code" }, h("label", { key: '3c38728d9833d750e097c96b1df655d2c624cbaf', htmlFor: this.phoneFieldId }, "Passcode:"), h("input", { key: 'c067ad0b5e64554869d382b30034ad06f3f2287c', 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: 'aea4f4504c415602990370c74b8cbc4888cdb9c4', class: "row message" }, h("label", { key: '293b04061121e45a161299a7c67742b35450f73e', htmlFor: "verdocs-contact-picker-message" }, "Message:"), h("textarea", { key: '27b597556563377a843865cfa1205d28c5a35440', 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: 'cd57ffae6c1fdb990b5cee5d2f93315b1e431ae2', class: "buttons" }, h("div", { key: '229c636cd7d61eaeece868f1d64a787465913223', class: "flex-fill" }), h("verdocs-button", { key: '0014bda0bcef66e26df9cfad2e4ca09bad08419a', variant: "outline", label: "Cancel", size: "small", onClick: e => this.handleCancel(e) }), h("verdocs-button", { key: 'cc2456cc0e493b0449750e3950e28c6c3aa69fa2', 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; 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
