import { p as proxyCustomElement, H, c as createEvent, h, d as Host } from './p-D16h8pzh.js';
import { getTemplate, getOrganizationContacts, isValidEmail, createEnvelope, formatFullName, getRGBA } from '@verdocs/js-sdk';
import { D as DefaultEndpoint } from './p-C_Xku1v2.js';
import { V as VerdocsToast } from './p-CyvDgtoV.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { S as Store } from './p-DmsV595e.js';
import { d as defineCustomElement$7 } from './p-BNrp2UP2.js';
import { d as defineCustomElement$6 } from './p-wYGYhfrp.js';
import { d as defineCustomElement$5 } from './p-DsCKNQPC.js';
import { d as defineCustomElement$4 } from './p-CeTLcymJ.js';
import { d as defineCustomElement$3 } from './p-Bv-L0hsU.js';
import { d as defineCustomElement$2 } from './p-Boia1Nbz.js';
import { d as defineCustomElement$1 } from './p-BdSDDira.js';

const getRoleNames = (template) => ((template === null || template === void 0 ? void 0 : template.roles) || []).map(role => role.name);
const getRoleIndex = (template, role_name) => Math.max(getRoleNames(template).findIndex(name => name === role_name), 0);

const verdocsSendCss = "@-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-send{padding:10px;position:relative;background:#ffffff;-ms-flex-direction:column;flex-direction:column;font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif}verdocs-send.sendable{display:-ms-flexbox;display:flex}verdocs-send .recipients{position:relative}verdocs-send .left-line{top:32px;left:20px;z-index:1;width:12px;bottom:30px;position:absolute;background:#ffffff;border-left:3px dotted #9b9b9b}verdocs-send .level{display:-ms-flexbox;display:flex;-webkit-column-gap:10px;-moz-column-gap:10px;column-gap:10px;margin-left:50px;position:relative;-ms-flex-direction:row;flex-direction:row;padding:8px 0 4px 0;border-bottom:1px solid rgba(151, 151, 151, 0.2666666667)}verdocs-send .level .level-icon{top:14px;z-index:2;left:-40px;width:24px;height:24px;position:absolute;background:#ffffff}verdocs-send .level .level-icon svg{fill:rgba(0, 0, 0, 0.537254902)}verdocs-send .level .recipient{height:30px;display:-ms-flexbox;display:flex;-ms-flex:0 0 30px;flex:0 0 30px;color:#000000;cursor:pointer;font-size:14px;-ms-flex-align:center;align-items:center;border-radius:30px;-ms-flex-direction:row;flex-direction:row;background:#dddddd;white-space:nowrap;border:2px solid #dddddd;padding:2px 10px 2px 14px}verdocs-send .level .recipient .icon{width:22px;height:22px;-ms-flex:0 0 22px;flex:0 0 22px;margin:0 0 0 10px}verdocs-send .level .recipient .icon svg{width:22px;height:22px;fill:#333333;outline:none}verdocs-send .level .complete{-ms-flex:1;flex:1;height:30px;display:-ms-flexbox;display:flex;color:#000000;font-size:14px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;padding:3px 10px 3px 2px}verdocs-send .buttons{display:-ms-flexbox;display:flex;margin-top:10px;-webkit-column-gap:15px;-moz-column-gap:15px;column-gap:15px;-ms-flex-direction:row;flex-direction:row}verdocs-send verdocs-contact-picker{left:0;top:41px;z-index:10;position:absolute;border:1px solid #dddddd;-webkit-box-shadow:0 0 6px 3px rgba(0, 0, 0, 0.1);box-shadow:0 0 6px 3px rgba(0, 0, 0, 0.1)}";

const editIcon = '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" tabindex="-1"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"></path></svg>';
const startIcon = '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" tabindex="-1"><path d="M2 12C2 6.48 6.48 2 12 2s10 4.48 10 10-4.48 10-10 10S2 17.52 2 12zm10 6c3.31 0 6-2.69 6-6s-2.69-6-6-6-6 2.69-6 6 2.69 6 6 6z"></path></svg>';
const stepIcon = '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" tabindex="-1"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"></path></svg>';
const doneIcon = '<svg focusable="false" aria-hidden="true" viewBox="0 0 24 24" tabindex="-1"><path d="m18 7-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41 6 19l1.41-1.41L1.83 12 .41 13.41z"></path></svg>';
const VerdocsSend = /*@__PURE__*/ proxyCustomElement(class VerdocsSend extends H {
    constructor() {
        super();
        this.__registerHost();
        this.beforeSend = createEvent(this, "beforeSend");
        this.send = createEvent(this, "send");
        this.exit = createEvent(this, "exit");
        this.sdkError = createEvent(this, "sdkError");
        this.searchContacts = createEvent(this, "searchContacts");
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = DefaultEndpoint;
        /**
         * The ID of the template to create the document from.
         */
        this.templateId = null;
        /**
         * The environment the control is being called from, e.g. 'web'. This has an impact on how certain
         * operations such as email communications are handled to ensure users receive the correct URLs for
         * their invitations. Setting this to unknown values may produce unexpected/incorrect behaviors.
         * If environment is not known, do this set this property.
         */
        this.environment = '';
        this.containerId = `verdocs-send-${Math.random().toString(36).substring(2, 11)}`;
        this.showPickerForId = '';
        this.sessionContacts = [];
        this.sending = false;
        this.rolesCompleted = {};
        this.loading = true;
        this.template = null;
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        console.log('[SEND] Loading template', this.templateId);
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), true, (template) => {
            console.log('[SEND] Got new template', template);
            this.template = template;
            this.loading = false;
            this.rolesCompleted = {};
            this.recomputeRolesCompleted();
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    async reset() {
        this.rolesCompleted = {};
    }
    onTemplateIdChanged(newTemplateId) {
        console.log('[SEND] Template ID changed', newTemplateId);
        this.listenToTemplate();
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.onSessionChanged((_endpoint, _session, profile) => {
                if (!profile) {
                    return;
                }
                const me = {
                    id: profile.id,
                    first_name: profile.first_name,
                    last_name: profile.last_name,
                    email: profile.email,
                    phone: profile.phone,
                };
                if (profile) {
                    this.sessionContacts = [me];
                    getOrganizationContacts(this.endpoint)
                        .then(contacts => {
                        console.log('[SEND] Got contacts', contacts);
                        this.sessionContacts = [...contacts, me];
                    })
                        .catch(e => {
                        console.log('[SEND] Error getting contacts', e);
                    });
                }
            });
            this.endpoint.loadSession();
            if (!this.endpoint.session) {
                console.log('[SEND] Unable to start Send operation, must be authenticated');
                return;
            }
            if (!this.templateId) {
                console.log(`[SEND] Missing required template ID ${this.templateId}`);
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[SEND] Error with send session', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    recomputeRolesCompleted() {
        var _a;
        this.rolesCompleted = {};
        const rolesAtLevel = {};
        (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).forEach(role => {
            const level = role.sequence;
            rolesAtLevel[level] || (rolesAtLevel[level] = []);
            const id = `r-${level}-${rolesAtLevel[level].length}`;
            rolesAtLevel[level].push({ ...role, id, role_name: role.name, first_name: role.first_name, last_name: role.last_name });
            // if (role.first_name && (isValidEmail(role.email) || isValidPhone(role.phone))) {
            if (role.first_name && isValidEmail(role.email)) {
                this.rolesCompleted[id] = { ...role, id, role_name: role.name, first_name: role.first_name, last_name: role.last_name };
            }
        });
    }
    getSequenceNumbers() {
        var _a;
        // This is cleaner with a Set but we found a regression in some target environments where
        // this breaks down. Reverting to an older technique while we diagnose it.
        const sequences = {};
        (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).forEach(role => {
            sequences[role.sequence] = true;
        });
        return Object.keys(sequences)
            .map(s => +s)
            .sort((a, b) => a - b);
    }
    getRolesAtLevel(level) {
        var _a;
        const rolesAtLevel = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || [])
            .filter(role => role.sequence === level)
            .map((role, index) => ({
            ...role,
            id: `r-${level}-${index}`,
            role_name: role.name,
            first_name: role.first_name,
            last_name: role.last_name,
        }));
        return rolesAtLevel;
    }
    getLevelIcon(level) {
        if (level === 'start') {
            return h("div", { class: "level-icon", innerHTML: startIcon });
        }
        else if (level === 'end') {
            return h("div", { class: "level-icon", innerHTML: doneIcon });
        }
        else {
            return h("div", { class: "level-icon", innerHTML: stepIcon });
        }
    }
    handleSelectContact(e, role) {
        e.preventDefault();
        this.rolesCompleted[role.id] = { ...role, ...e.detail };
        this.showPickerForId = '';
    }
    handleClickRole(e, role) {
        e.stopPropagation();
        this.showPickerForId = role.id;
    }
    handleSend(e) {
        var _a;
        if (this.sending) {
            console.log('[SEND] Skipping duplicate send', e);
            return;
        }
        console.log('[SEND] Sending', e);
        e.preventDefault();
        e.stopPropagation();
        this.sending = true;
        const details = {
            template_id: this.templateId,
            name: ((_a = this.template) === null || _a === void 0 ? void 0 : _a.name) || 'New Envelope',
            environment: this.environment,
            initial_reminder: 0,
            followup_reminders: 0,
            recipients: Object.values(this.rolesCompleted),
        };
        const beforeSendResult = this.beforeSend.emit({ ...details, name: details.name, template: this.template });
        if (beforeSendResult.defaultPrevented) {
            console.log('[SEND] Send cancelled by parent', details);
            this.sending = false;
            return;
        }
        console.log('[SEND] Creating envelope', details);
        createEnvelope(this.endpoint, details)
            .then(r => {
            var _a;
            console.log('[SEND] Send envelope', r);
            this.reset().catch((e) => console.log('Unknown Error', e));
            this.sending = false;
            (_a = this.send) === null || _a === void 0 ? void 0 : _a.emit({ ...details, name: details.name, envelope_id: r.id, envelope: r });
        })
            .catch(e => {
            var _a, _b, _c;
            console.log('[SEND] Send error', e);
            VerdocsToast(((_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) || 'Error creating envelope, please try again later.');
            this.sending = false;
            (_c = this.sdkError) === null || _c === void 0 ? void 0 : _c.emit(e);
        });
    }
    handleCancel(e) {
        var _a;
        e.stopPropagation();
        (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit();
    }
    render() {
        var _a;
        if (this.loading) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        if (!this.endpoint.session) {
            return (h(Host, { style: { display: 'flex' } }, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        const levels = this.getSequenceNumbers();
        const rolesAssigned = Object.values(this.rolesCompleted).filter(recipient => isValidEmail(recipient.email) && recipient.first_name && recipient.last_name);
        const allRolesAssigned = rolesAssigned.length >= getRoleNames(this.template).length;
        return (h(Host, { class: { sendable: (_a = this.template) === null || _a === void 0 ? void 0 : _a.is_sendable } }, h("div", { class: "recipients" }, h("div", { class: "left-line" }), h("div", { class: `level level-start` }, this.getLevelIcon('start'), h("div", { class: "complete" }, "Send Envelope")), levels.map(level => (h("div", { class: `level level-${level}` }, this.getLevelIcon('sequence'), this.getRolesAtLevel(level).map(role => {
            var _a, _b, _c;
            const unknown = !role.email || !role.first_name || !role.last_name;
            const roleName = ((_a = this.rolesCompleted[role.id]) === null || _a === void 0 ? void 0 : _a.first_name) ? formatFullName(this.rolesCompleted[role.id]) : unknown ? role.role_name : formatFullName(role);
            const elId = `verdocs-send-recipient-${role.role_name}`;
            const roleIndex = getRoleIndex(this.template, role.role_name);
            const rgba = getRGBA(roleIndex);
            const completed = rolesAssigned.findIndex(r => r.role_name === role.role_name) > -1;
            const style = {
                backgroundColor: rgba,
                border: completed ? '2px solid #55bc81' : '2px solid #dddddd',
            };
            return unknown ? (h("div", { class: "recipient", "data-ri": roleIndex, "data-rn": role.role_name, style: style, onClick: e => this.handleClickRole(e, role), id: elId }, roleName, h("div", { class: "icon", innerHTML: editIcon }), this.showPickerForId === role.id && (h("verdocs-portal", { anchor: elId, onClickAway: () => (this.showPickerForId = '') }, h("verdocs-contact-picker", { onExit: () => (this.showPickerForId = ''), onNext: e => this.handleSelectContact(e, role), contactSuggestions: this.sessionContacts, templateRole: (_b = this.rolesCompleted[role.id]) !== null && _b !== void 0 ? _b : role, onSearchContacts: e => { var _a; return (_a = this.searchContacts) === null || _a === void 0 ? void 0 : _a.emit(e.detail); } }))))) : (h("div", { class: "recipient", "data-ri": roleIndex, "data-rn": role.role_name, style: style, onClick: e => this.handleClickRole(e, role), id: elId }, roleName, h("div", { class: "icon", innerHTML: editIcon }), this.showPickerForId === role.id && (h("verdocs-portal", { anchor: elId, onClickAway: () => (this.showPickerForId = '') }, h("verdocs-contact-picker", { onExit: () => (this.showPickerForId = ''), onNext: e => this.handleSelectContact(e, role), contactSuggestions: this.sessionContacts, templateRole: ((_c = this.rolesCompleted[role.id]) !== null && _c !== void 0 ? _c : role), onSearchContacts: e => { var _a; return (_a = this.searchContacts) === null || _a === void 0 ? void 0 : _a.emit(e.detail); } })))));
        })))), h("div", { class: `level level-done` }, this.getLevelIcon('end'), h("div", { class: "complete" }, "Signing Complete"))), h("div", { class: "buttons" }, h("verdocs-button", { label: "Cancel", size: "small", variant: "outline", onClick: e => this.handleCancel(e), disabled: this.sending }), h("verdocs-button", { label: "Send", size: "small", disabled: !allRolesAssigned || this.sending, onClick: e => this.handleSend(e) }), this.sending && h("verdocs-spinner", null))));
    }
    static get watchers() { return {
        "templateId": ["onTemplateIdChanged"]
    }; }
    static get style() { return verdocsSendCss; }
}, [256, "verdocs-send", {
        "endpoint": [16],
        "templateId": [513, "template-id"],
        "environment": [1],
        "containerId": [32],
        "showPickerForId": [32],
        "sessionContacts": [32],
        "sending": [32],
        "rolesCompleted": [32],
        "loading": [32],
        "template": [32],
        "reset": [64]
    }, undefined, {
        "templateId": ["onTemplateIdChanged"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-send", "verdocs-button", "verdocs-checkbox", "verdocs-component-error", "verdocs-contact-picker", "verdocs-loader", "verdocs-portal", "verdocs-spinner"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-send":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsSend);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-component-error":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-contact-picker":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-portal":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-spinner":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { VerdocsSend as V, defineCustomElement as d };
//# sourceMappingURL=p-DeoKKq-r.js.map

//# sourceMappingURL=p-DeoKKq-r.js.map