import { p as proxyCustomElement, H, c as createEvent, h, d as Host, F as Fragment } from './p-D16h8pzh.js';
import { VerdocsEndpoint, getEnvelope, getDocumentDownloadLink, cancelEnvelope, userCanCancelEnvelope, integerSequence } from '@verdocs/js-sdk';
import { s as saveEnvelopesAsZip } from './p-y2dhcER7.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { S as Store } from './p-DmsV595e.js';
import { d as defineCustomElement$6 } from './p-CZTe2XIO.js';
import { d as defineCustomElement$5 } from './p-QqWvYNbV.js';
import { d as defineCustomElement$4 } from './p-WvXI4EBm.js';
import { d as defineCustomElement$3 } from './p-Bv-L0hsU.js';
import { d as defineCustomElement$2 } from './p-CQ-UXlBO.js';
import { d as defineCustomElement$1 } from './p-Boia1Nbz.js';

const verdocsViewCss = "@-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-view{display:-ms-flexbox;display:flex;overflow:hidden;min-height:600px;position:relative;-ms-flex-align:center;align-items:center;-ms-flex-direction:column;flex-direction:column;-webkit-box-sizing:border-box;box-sizing:border-box;font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif}verdocs-view div,verdocs-view canvas{-webkit-box-sizing:border-box;box-sizing:border-box}verdocs-view .document{-ms-flex:1;flex:1;width:100%;height:100%;display:-ms-flexbox;display:flex;padding:15px;row-gap:15px;min-height:200px;max-width:1200px;position:relative;overflow-y:scroll;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-flex-direction:column;flex-direction:column}verdocs-view .document .inner{width:100%;max-width:1028px}verdocs-view .loading-indicator{top:0;left:0;right:0;bottom:0;display:-ms-flexbox;display:flex;z-index:10000;position:fixed;background-color:rgba(0, 0, 0, 0.7)}#verdocs-view-header{width:100%;color:#fff;display:-ms-flexbox;display:flex;z-index:1000;-ms-flex:0 0 56px;flex:0 0 56px;padding:0 20px;font-size:12px;-webkit-column-gap:15px;-moz-column-gap:15px;column-gap:15px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;-webkit-transition:all 0.25s;transition:all 0.25s;background-color:#33354c;-webkit-box-shadow:0 4px 4px 0 rgba(0, 0, 0, 0.24), 0 0 4px 0 rgba(0, 0, 0, 0.12);box-shadow:0 4px 4px 0 rgba(0, 0, 0, 0.24), 0 0 4px 0 rgba(0, 0, 0, 0.12)}@media all and (max-width: 500px){#verdocs-view-header{padding:0 10px}}#verdocs-view-header .inner{width:100%;display:-ms-flexbox;display:flex;margin:0 auto;padding:0 20px;max-width:1200px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row}@media all and (max-width: 500px){#verdocs-view-header .inner{padding:0 10px}}#verdocs-view-header .logo{width:80px;display:none;margin:-6px 0 0 0}#verdocs-view-header .title{font-size:18px;font-weight:500;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}";

const VerdocsView = /*@__PURE__*/ proxyCustomElement(class VerdocsView extends H {
    constructor() {
        super();
        this.__registerHost();
        this.sdkError = createEvent(this, "sdkError");
        this.envelopeUpdated = createEvent(this, "envelopeUpdated");
        this.another = createEvent(this, "another");
        this.view = createEvent(this, "view");
        this.next = createEvent(this, "next");
        this.envelopeListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = null;
        /**
         * The envelope ID to render. Set ONE OF templateId or envelopeId. If both are set, envelopeId will be ignored.
         */
        this.envelopeId = '';
        /**
         * If set, (recommended), the host application should create a <DIV> element with a unique ID. When this
         * component renders, the header will be removed from its default location and placed in the target element.
         * This allows the parent application to more easily control its placement and scroll effects (e.g. "fixed").
         *
         * The movement of the header to the target container is not dynamic - it is performed only on the initial
         * render. Host applications should not conditionally render this container. If the header's visibility must
         * be externally controlled, use CSS display options to hide/show it instead.
         */
        this.headerTargetId = null;
        this.canceling = false;
        this.showCancelDone = false;
        this.showLoadError = false;
        this.loading = true;
        this.envelope = null;
    }
    async componentWillLoad() {
        var _a, _b, _c;
        if (!this.endpoint) {
            this.endpoint = VerdocsEndpoint.getDefault();
            this.endpoint.loadSession();
        }
        if (!this.envelopeId) {
            console.error(`[VIEW] Missing required envelopeId`);
            return;
        }
        this.listenToEnvelope();
        if (!this.envelope) {
            try {
                console.log('[VIEW] Loading envelope...');
                this.envelope = await getEnvelope(this.endpoint, this.envelopeId);
                console.log('[VIEW] Loaded envelope', this.envelope);
            }
            catch (e) {
                this.showLoadError = true;
                (_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));
            }
        }
    }
    componentDidRender() {
        const headerTarget = this.headerTargetId ? document.getElementById(this.headerTargetId) : null;
        const headerEl = document.getElementById('verdocs-view-header');
        if (headerTarget && headerEl) {
            console.log('[VIEW] Moving header');
            headerEl.remove();
            headerTarget.append(headerEl);
        }
    }
    disconnectedCallback() {
        this.unlistenToEnvelope();
    }
    async listenToEnvelope() {
        console.log('[SIDEBAR] Loading envelope', this.envelopeId);
        this.unlistenToEnvelope();
        Store.subscribe('envelopes', this.envelopeId, () => getEnvelope(this.endpoint, this.envelopeId), true, (envelope) => {
            this.envelope = envelope;
            this.loading = false;
        });
    }
    unlistenToEnvelope() {
        if (this.envelopeListenerId) {
            Store.store.delListener(this.envelopeListenerId);
            this.envelopeListenerId = null;
        }
    }
    handlePageRendered(_e) {
        // const pageInfo = e.detail as IDocumentPageInfo;
        // console.log('[VIEW] Page rendered', pageInfo);
    }
    async handleOptionSelected(e) {
        var _a, _b;
        switch (e.detail.id) {
            case 'cancel':
                // TODO: Better option for inline-flow confirmation and alert dialogs.
                if (confirm('Are you sure you wish to cancel this envelope? This action cannot be undone.')) {
                    this.canceling = true;
                    cancelEnvelope(this.endpoint, this.envelopeId)
                        .then(r => {
                        this.canceling = false;
                        console.log('[VIEW] Envelope canceled', r);
                        return getEnvelope(this.endpoint, this.envelopeId);
                    })
                        .then(env => {
                        console.log('[VIEW] Loaded new envelope details', env);
                        this.envelope = env;
                    })
                        .catch(e => {
                        var _a, _b, _c;
                        this.canceling = false;
                        console.log('[VIEW] Error canceling envelope', 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));
                    });
                    this.showCancelDone = true;
                    (_a = this.envelopeUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope: this.envelope, event: 'canceled' });
                }
                break;
            case 'print':
                window.print();
                (_b = this.envelopeUpdated) === null || _b === void 0 ? void 0 : _b.emit({ endpoint: this.endpoint, envelope: this.envelope, event: 'printed' });
                break;
            case 'download-attachments':
                // TODO: Multiple document support
                {
                    const firstDoc = this.envelope.documents.find(doc => doc.type === 'attachment');
                    if (firstDoc) {
                        const url = await getDocumentDownloadLink(this.endpoint, this.envelopeId, firstDoc.id);
                        window.open(url, '_blank');
                    }
                }
                break;
            case 'download-certificate':
                // TODO: Multiple certificate support
                {
                    const firstCert = this.envelope.documents.find(doc => doc.type === 'certificate');
                    if (firstCert) {
                        const url = await getDocumentDownloadLink(this.endpoint, this.envelopeId, firstCert.id);
                        window.open(url, '_blank');
                    }
                }
                // saveCertificate(this.endpoint, this.envelope, this.envelope.certificate_document_id)
                //   .then(() => {
                //     this.envelopeUpdated?.emit({endpoint: this.endpoint, envelope: this.envelope, event: 'downloaded'});
                //   })
                //   .catch(e => {
                //     console.log('Error downloading PDF', e);
                //   });
                break;
            case 'download-all':
                saveEnvelopesAsZip(this.endpoint, [this.envelope])
                    .then(() => {
                    var _a;
                    (_a = this.envelopeUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope: this.envelope, event: 'downloaded' });
                })
                    .catch(e => {
                    console.log('Error downloading Zip', e);
                });
                break;
        }
    }
    render() {
        var _a;
        if (this.loading) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        if (this.showLoadError) {
            return (h(Host, null, h("verdocs-ok-dialog", { heading: "Unable to View Envelope", message: `Sorry, that envelope is not valid.`, buttonLabel: "OK", onNext: () => {
                    this.showLoadError = false;
                } })));
        }
        if (!this.envelope) {
            return (h(Host, null, h("img", { src: "https://public-assets.verdocs.com/loading-placeholder.png", style: { width: '612px', height: '792px', boxShadow: '0 0 10px 5px #0000000f', marginTop: '15px' }, alt: "Placeholder page" })));
        }
        const menuOptions = [{ id: 'print', label: 'Print' }];
        if (userCanCancelEnvelope(this.endpoint.profile, this.envelope)) {
            menuOptions.push({ id: 'cancel', label: 'Cancel' });
        }
        // Add download options to the menu
        const hasAttachments = this.envelope.documents.length > 0;
        const normalDocCount = this.envelope.documents.filter(doc => doc.type === 'attachment').length;
        const hasCertificate = this.envelope.documents.find(doc => doc.type === 'certificate') !== undefined;
        if (hasAttachments || hasCertificate) {
            menuOptions.push({ label: '' });
            if (hasAttachments) {
                menuOptions.push({ id: 'download-attachments', label: normalDocCount > 1 ? 'Download Documents' : 'Download Document' });
            }
            if (hasCertificate) {
                menuOptions.push({ id: 'download-certificate', label: 'Download Certificate' });
            }
            if (hasAttachments && hasCertificate) {
                menuOptions.push({ id: 'download-all', label: 'Download All Files' });
            }
        }
        return (h(Host, null, h("div", { id: "verdocs-view-header" }, h("div", { class: "inner" }, h("img", { src: "https://verdocs.com/assets/white-logo.svg", alt: "Verdocs Logo", class: "logo" }), h("div", { class: "title" }, this.envelope.name), h("div", { style: { flex: '1' } }), h("div", { style: { marginLeft: '10px' } }), h("verdocs-dropdown", { options: menuOptions, onOptionSelected: e => this.handleOptionSelected(e) }))), h("div", { class: "document", style: { paddingTop: this.headerTargetId ? '70px' : '15px' } }, (((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.documents) || [])
            .filter(document => document.type !== 'certificate')
            .map(envelopeDocument => {
            const pageNumbers = integerSequence(1, envelopeDocument.pages);
            return (h(Fragment, null, pageNumbers.map(pageNumber => {
                var _a;
                const pageSize = ((_a = envelopeDocument.page_sizes) === null || _a === void 0 ? void 0 : _a[pageNumber]) || { width: 612, height: 792 };
                return (h("verdocs-envelope-document-page", { envelopeId: this.envelopeId, documentId: envelopeDocument.id, endpoint: this.endpoint, type: "filled", virtualWidth: pageSize.width, virtualHeight: pageSize.height, pageNumber: pageNumber, onPageRendered: e => this.handlePageRendered(e), layers: [
                        { name: 'page', type: 'canvas' },
                        { name: 'controls', type: 'div' },
                    ] }));
            })));
        })), this.showCancelDone && (h("verdocs-ok-dialog", { heading: "Cancelled", message: `This envelope has been cancelled successfully.`, onNext: () => {
                this.showCancelDone = false;
            } })), this.canceling && (h("div", { class: "loading-indicator" }, h("verdocs-loader", null)))));
    }
    get component() { return this; }
    static get style() { return verdocsViewCss; }
}, [256, "verdocs-view", {
        "endpoint": [16],
        "envelopeId": [1, "envelope-id"],
        "headerTargetId": [1, "header-target-id"],
        "canceling": [32],
        "showCancelDone": [32],
        "showLoadError": [32],
        "loading": [32],
        "envelope": [32]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-view", "verdocs-dialog", "verdocs-dropdown", "verdocs-envelope-document-page", "verdocs-loader", "verdocs-ok-dialog", "verdocs-portal"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-view":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsView);
            }
            break;
        case "verdocs-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-dropdown":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-envelope-document-page":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-ok-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-portal":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { VerdocsView as V, defineCustomElement as d };
//# sourceMappingURL=p-CEX8yyLu.js.map

//# sourceMappingURL=p-CEX8yyLu.js.map