import { p as proxyCustomElement, H, c as createEvent, h, d as Host } from './p-AiOs8RvA.js';
import { VerdocsEndpoint, getEnvelopes, integerSequence, getRecipientsWithActions, userCanCancelEnvelope, userCanAct, formatFullName, cancelEnvelope } from '@verdocs/js-sdk';
import { s as saveEnvelopesAsZip } from './p-rIIybUCF.js';
import { V as VerdocsToast } from './p-CyvDgtoV.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { d as defineCustomElement$b } from './p-DMVmShTi.js';
import { d as defineCustomElement$a } from './p-B4xcxu5g.js';
import { d as defineCustomElement$9 } from './p-BnsUul79.js';
import { d as defineCustomElement$8 } from './p-Bbomvxyl.js';
import { d as defineCustomElement$7 } from './p-h3zv1kyS.js';
import { d as defineCustomElement$6 } from './p-BQtWBtuj.js';
import { d as defineCustomElement$5 } from './p-CHC1i5sP.js';
import { d as defineCustomElement$4 } from './p-FuEnKEp1.js';
import { d as defineCustomElement$3 } from './p-lvLxBhMX.js';
import { d as defineCustomElement$2 } from './p-xz67XcVg.js';

const verdocsEnvelopesListCss = "@-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-envelopes-list{display:-ms-flexbox;display:flex;padding:10px;font-size:18px;-ms-flex-wrap:nowrap;flex-wrap:nowrap;border-radius:6px;color:#33364b;-ms-flex-direction:column;flex-direction:column;font-family:\"Inter\", \"Barlow\", sans-serif}@media screen and (max-width: 800px){verdocs-envelopes-list{font-size:14px}}verdocs-envelopes-list .envelope-placeholder{height:48px;-ms-flex:0 0 48px;flex:0 0 48px;margin:5px 0;border-radius:5px;background:#f5f5fa}verdocs-envelopes-list .header{width:100%;row-gap:4px;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-column-gap:12px;-moz-column-gap:12px;column-gap:12px;margin:0 0 10px 0;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row}verdocs-envelopes-list .header .filter{width:300px}verdocs-envelopes-list .header verdocs-text-input{margin:0}verdocs-envelopes-list .header verdocs-text-input input{height:32px}verdocs-envelopes-list .filter{-ms-flex-align:center;align-items:center}verdocs-envelopes-list .envelope{width:100%;margin:3px 0;background:#ffffff}verdocs-envelopes-list .envelope:hover{cursor:pointer;background:#f5f5fa}verdocs-envelopes-list .envelope .inner{gap:12px;display:-ms-flexbox;display:flex;padding:8px 14px;border-radius:5px;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;container-type:inline-size}verdocs-envelopes-list .envelope .inner svg{width:24px;height:24px}verdocs-envelopes-list .vert-spacer{height:50px;display:-ms-flexbox;display:flex;-ms-flex:0 0 1px;flex:0 0 1px;border-right:1px solid #dad8dd}@media screen and (max-width: 800px){verdocs-envelopes-list .vert-spacer{display:none}}@media screen and (max-width: 800px){verdocs-envelopes-list .envelope-icon{display:none}}@media screen and (max-width: 800px){verdocs-envelopes-list verdocs-checkbox{display:none}}verdocs-envelopes-list .last-modified{color:#444;display:-ms-flexbox;display:flex;-ms-flex:0 0 180px;flex:0 0 180px;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;white-space:nowrap}@media screen and (max-width: 800px){verdocs-envelopes-list .last-modified{display:none}}verdocs-envelopes-list .envelope-name{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;color:#000000;line-height:28px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}verdocs-envelopes-list .envelope-recipients{color:#4b5563;font-weight:700;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}verdocs-envelopes-list .empty-text{text-align:center;margin:16px 0 0 0;padding:80px 80px;border:2px solid #ccc}verdocs-envelopes-list .containing{gap:12px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row}@media screen and (max-width: 800px){verdocs-envelopes-list verdocs-status-indicator{font-size:14px}}";

const DocumentIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="#000000" viewBox="0 0 24 24" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" /></svg>`;
const ViewFilters = [
    { value: 'all', label: 'All' },
    { value: 'inbox', label: 'Inbox' },
    { value: 'sent', label: 'Sent' },
    { value: 'completed', label: 'Completed' },
    { value: 'action', label: 'Action Required' },
    { value: 'waiting', label: 'Waiting on Others' },
];
const StatusFilters = [
    { value: 'all', label: 'All' },
    { value: 'pending', label: 'Pending' },
    { value: 'in progress', label: 'In Progress' },
    { value: 'complete', label: 'Completed' },
    { value: 'declined', label: 'Declined' },
    { value: 'canceled', label: 'Canceled' },
];
const SortFilters = [
    { value: 'created_at', label: 'Created' },
    { value: 'updated_at', label: 'Updated' },
    { value: 'canceled_at', label: 'Canceled' },
    { value: 'envelope_name', label: 'Name' },
    { value: 'envelope_status', label: 'Status' },
];
const VerdocsEnvelopesList$1 = /*@__PURE__*/ proxyCustomElement(class VerdocsEnvelopesList extends H {
    constructor() {
        super();
        this.__registerHost();
        this.changeView = createEvent(this, "changeView");
        this.changeStatus = createEvent(this, "changeStatus");
        this.changeSort = createEvent(this, "changeSort");
        this.changeMatch = createEvent(this, "changeMatch");
        this.sdkError = createEvent(this, "sdkError");
        this.viewEnvelope = createEvent(this, "viewEnvelope");
        this.finishEnvelope = createEvent(this, "finishEnvelope");
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The filtered view to display. "completed" will show envelopes that have been submitted. "action" will
         * show envelopes where the user is a recipient and the envelope is not completed. "waiting" will show
         * only envelopes where the user is the sender and the envelope is not completed.
         */
        this.view = undefined;
        /**
         * The status value to filter by
         */
        this.status = 'all';
        /**
         * The sort field to use
         */
        this.sort = 'created_at';
        /**
         * If set, filter envelopes by the specified string.
         */
        this.match = '';
        /**
         * If set, filter envelopes by the specified "containing" value.
         */
        // @Prop({reflect: true, mutable: true}) containing: string = '';
        /**
         * Whether or not pagination should be enabled.
         */
        this.showPagination = true;
        /**
         * The number of rows to display per page.
         */
        this.rowsPerPage = 10;
        /**
         * The initial page number to select. Pagination is internally controlled but may be overriden by the
         * host applicaiton.
         */
        this.selectedPage = 0;
        this.count = 0;
        this.initiallyLoaded = false;
        this.loading = true;
        this.selectedEnvelopes = [];
        this.envelopes = [];
    }
    handleViewUpdated() {
        return this.queryEnvelopes();
    }
    handleStatusUpdated() {
        return this.queryEnvelopes();
    }
    handleSortUpdated() {
        return this.queryEnvelopes();
    }
    handleMatchUpdated() {
        return this.queryEnvelopes();
    }
    // @Watch('containing')
    // handleContainingUpdated() {
    //   return this.queryEnvelopes();
    // }
    handlePageUpdated() {
        return this.queryEnvelopes();
    }
    componentWillLoad() {
        this.endpoint.onSessionChanged((_, session, profile) => {
            console.log('[ENVELOPES_LIST] onSessionChanged', session, profile);
        });
        this.endpoint.loadSession();
    }
    async componentDidLoad() {
        await this.queryEnvelopes();
        this.initiallyLoaded = true;
    }
    async queryEnvelopes() {
        var _a, _b, _c;
        try {
            this.loading = true;
            let queryParams = {
                page: this.selectedPage,
                // sort: this.sort,
                rows: this.rowsPerPage,
            };
            switch (this.view) {
                case 'all':
                    queryParams = {
                        ...queryParams,
                        // sort: this.sort,
                        // direction: this.sort === 'name' ? 'asc' : 'desc',
                        status: (this.status === 'all' ? ['pending', 'in progress', 'complete', 'declined', 'canceled'] : [this.status]),
                    };
                    break;
                case 'inbox':
                    queryParams = {
                        ...queryParams,
                        // is_recipient: true,
                        // sort: 'updated_at',
                        // recipient_status: ['invited', 'declined', 'opened', 'signed', 'submitted', 'canceled'],
                    };
                    break;
                case 'sent':
                    queryParams = {
                        ...queryParams,
                        // FIXME
                        // is_owner: true,
                        // sort: 'updated_at',
                    };
                    break;
                case 'action':
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // is_recipient: true,
                        status: ['pending', 'in progress'],
                        // recipient_status: ['invited', 'opened', 'signed'],
                    };
                    break;
                case 'waiting':
                    queryParams = {
                        ...queryParams,
                        // FIXME
                        // is_owner: true,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: ['pending', 'in progress'],
                    };
                    break;
                case 'completed':
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: ['complete'],
                    };
                    break;
                default:
                    queryParams = {
                        ...queryParams,
                        // sort: 'updated_at',
                        // direction: 'desc',
                        status: (this.status === 'all' ? ['pending', 'in progress', 'complete', 'declined', 'canceled'] : [this.status]),
                    };
            }
            // These filters should only be applied in "View All" mode. Otherwise the user could have set them to something
            // then changed the view e.g. to Inbox and the filter could break the view (e.g. View:Inbox, Status:Declined
            // would never return anything).
            if (this.view === 'all') {
                if (this.status !== 'all') {
                    queryParams.status = [this.status];
                }
            }
            if (this.match.trim()) ;
            // if (this.containing.trim()) {
            //   queryParams.field_value = this.containing.trim();
            // }
            const response = await getEnvelopes(this.endpoint, queryParams);
            this.envelopes = response.envelopes;
            this.count = response.count;
            this.loading = false;
        }
        catch (e) {
            this.loading = false;
            console.log('[ENVELOPES] Error listing envelopes', 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));
        }
    }
    handleDownload() {
        saveEnvelopesAsZip(this.endpoint, this.selectedEnvelopes)
            .then(() => {
            this.selectedEnvelopes = [];
        })
            .catch(e => {
            console.log('[ENVELOPES] Download error', e);
            VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    downloadEnvelope(envelope) {
        saveEnvelopesAsZip(this.endpoint, [envelope]).catch(e => {
            console.log('[ENVELOPES] Download error', e);
            VerdocsToast('Download error: ' + e.message, { style: 'error' });
        });
    }
    render() {
        return (h(Host, { key: 'c164108740fe2979d49969cff9309faa8c76ab39' }, h("div", { key: '89ea7a2cfba74a5efc723b11b85ce73c42785260', class: "header" }, h("div", { key: '22d68c923c0904c6b5374fa4ddea39428de3cadc', class: "filter" }, h("verdocs-text-input", { key: '82e396b43330b174d708732c22a384cdd5bf710a', id: "verdocs-filter-name", value: this.match, clearable: true, autocomplete: "off", placeholder: "Filter by Name, Recipient, or Field...", onFocusout: (e) => {
                var _a;
                // We don't locally filter envelopes because there are too many fields to match against efficiently.
                this.match = e.target.value.trim();
                (_a = this.changeMatch) === null || _a === void 0 ? void 0 : _a.emit(this.match);
            } })), h("verdocs-quick-filter", { key: '721393026ba97346a14c0622dbc667ad20e612ba', label: "View", value: this.view, options: ViewFilters, onOptionSelected: e => {
                this.view = e.detail.value;
            } }), this.view === 'all' && (h("verdocs-quick-filter", { key: '78c069f98e70644dcbd9a03b1dfe512774d424a2', label: "Status", value: this.status, options: StatusFilters, onOptionSelected: e => {
                this.status = e.detail.value;
            } })), this.view === 'all' && (h("verdocs-quick-filter", { key: '83df69798d32972d3d48951a283aa7893bde24d1', label: "Sort By", value: this.sort, options: SortFilters, onOptionSelected: e => {
                this.sort = e.detail.value;
            } })), this.loading && h("verdocs-spinner", { key: '7a4613ec8b94abdd9679bec26ee131e33ce307b5', mode: "dark", size: 24 }), h("div", { key: '7438d9a6484afae3e64ff9f2b949e0b306a0311b', style: { display: 'flex', flex: '1' } }), this.selectedEnvelopes.length > 0 && h("verdocs-button", { key: '984dd9ff7e43b4d9c2f01c7a5effe096a47aa8e5', label: `Download (${this.selectedEnvelopes.length})`, onClick: () => this.handleDownload() })), this.envelopes.map(envelope => {
            var _a;
            const recipientsWithActions = getRecipientsWithActions(envelope);
            const userCanCancel = userCanCancelEnvelope(this.endpoint.profile, envelope);
            const userRole = recipientsWithActions.find(recipient => { var _a; return recipient.email === ((_a = this.endpoint.session) === null || _a === void 0 ? void 0 : _a.email) || ''; });
            const userCanFinish = userRole && userCanCancel && userCanAct(((_a = this.endpoint.session) === null || _a === void 0 ? void 0 : _a.email) || '', recipientsWithActions);
            const menuOptions = [
                { label: 'View Envelope', id: 'view' },
                { label: 'Finish Envelope', id: 'finish', disabled: !userCanFinish },
                { label: 'Download', id: 'download' },
                { label: 'Cancel', id: 'cancel', disabled: !userCanCancel },
            ];
            return (h("div", { class: "envelope", key: envelope.id, onClick: () => { var _a; return (_a = this.viewEnvelope) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope }); } }, h("div", { class: "inner" }, h("verdocs-checkbox", { checked: this.selectedEnvelopes.findIndex(e => e.id === envelope.id) !== -1, onClick: e => e.stopPropagation(), onInput: (e) => {
                    if (e.target.checked) {
                        this.selectedEnvelopes = [...this.selectedEnvelopes, envelope];
                    }
                    else {
                        this.selectedEnvelopes = this.selectedEnvelopes.filter(e => e.id !== envelope.id);
                    }
                } }), h("div", { class: "vert-spacer" }), h("span", { innerHTML: DocumentIcon, class: "envelope-icon" }), h("div", { class: "envelope-name" }, envelope.name, ":\u00A0 ", h("div", { class: "envelope-recipients" }, envelope.recipients.map(r => formatFullName(r)))), h("div", { class: "vert-spacer" }), h("verdocs-status-indicator", { envelope: envelope, style: { width: '125px' } }), h("div", { class: "vert-spacer" }), h("div", { class: "last-modified" }, new Date(envelope.updated_at).toLocaleString()), h("div", { class: "vert-spacer" }), h("verdocs-dropdown", { options: menuOptions, onOptionSelected: e => {
                    var _a, _b;
                    switch (e.detail.id) {
                        case 'view':
                            (_a = this.viewEnvelope) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope });
                            break;
                        case 'finish':
                            (_b = this.finishEnvelope) === null || _b === void 0 ? void 0 : _b.emit({ endpoint: this.endpoint, envelope });
                            break;
                        case 'download':
                            this.downloadEnvelope(envelope);
                            break;
                        case 'cancel':
                            if (window.confirm('Are you sure you want to cancel this envelope?')) {
                                cancelEnvelope(this.endpoint, envelope.id)
                                    .then(() => VerdocsToast('Envelope canceled'))
                                    .catch(e => VerdocsToast('Unable to cancel envelope: ' + e.messabge, { style: 'error' }));
                                this.queryEnvelopes().catch(() => { });
                            }
                            break;
                    }
                } }))));
        }), !this.initiallyLoaded && (h("div", { key: '6cf4b54bdbbfcf76849de4cd9a42eb05babcdfc8', style: { width: '100%' } }, integerSequence(0, this.rowsPerPage).map(() => (h("div", { class: "envelope-placeholder" }))))), this.initiallyLoaded && !this.envelopes.length && h("div", { key: '19f5866766130424f3eb6944cd61904f509d3f71', class: "empty-text" }, "No matching envelopes found. Please adjust your filters and try again."), this.initiallyLoaded && this.envelopes.length && this.showPagination ? (h("div", { style: { marginTop: '20px' } }, h("verdocs-pagination", { selectedPage: this.selectedPage, perPage: this.rowsPerPage, itemCount: this.count, onSelectPage: e => {
                this.selectedPage = e.detail.selectedPage;
            } }))) : (h("div", null))));
    }
    static get watchers() { return {
        "view": ["handleViewUpdated"],
        "status": ["handleStatusUpdated"],
        "sort": ["handleSortUpdated"],
        "match": ["handleMatchUpdated"],
        "selectedPage": ["handlePageUpdated"]
    }; }
    static get style() { return verdocsEnvelopesListCss; }
}, [0, "verdocs-envelopes-list", {
        "endpoint": [16],
        "view": [1537],
        "status": [1537],
        "sort": [1537],
        "match": [1537],
        "showPagination": [4, "show-pagination"],
        "rowsPerPage": [2, "rows-per-page"],
        "selectedPage": [2, "selected-page"],
        "count": [32],
        "initiallyLoaded": [32],
        "loading": [32],
        "selectedEnvelopes": [32],
        "envelopes": [32]
    }, undefined, {
        "view": ["handleViewUpdated"],
        "status": ["handleStatusUpdated"],
        "sort": ["handleSortUpdated"],
        "match": ["handleMatchUpdated"],
        "selectedPage": ["handlePageUpdated"]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-envelopes-list", "verdocs-button", "verdocs-checkbox", "verdocs-dropdown", "verdocs-help-icon", "verdocs-pagination", "verdocs-portal", "verdocs-quick-filter", "verdocs-spinner", "verdocs-status-indicator", "verdocs-text-input"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-envelopes-list":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsEnvelopesList$1);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "verdocs-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "verdocs-dropdown":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "verdocs-help-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "verdocs-pagination":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-portal":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-quick-filter":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-spinner":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-status-indicator":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-text-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}

const VerdocsEnvelopesList = VerdocsEnvelopesList$1;
const defineCustomElement = defineCustomElement$1;

export { VerdocsEnvelopesList, defineCustomElement };
//# sourceMappingURL=verdocs-envelopes-list.js.map

//# sourceMappingURL=verdocs-envelopes-list.js.map