import { r as registerInstance, c as createEvent, h, H as Host, F as Fragment, g as getElement } from './index-CjTHbolG.js';
import { VerdocsEndpoint, DEFAULT_DISCLOSURES, startSigningSession, envelopeRecipientAgree, getEnvelope, updateEnvelopeField, createSignature, createInitials, sortFields, envelopeRecipientSubmit, isFieldValid, isFieldFilled, uploadEnvelopeFieldAttachment, deleteEnvelopeFieldAttachment, formatFullName, fullNameToInitials, verifySigner, getEnvelopesZip, getEnvelopeDocumentDownloadLink, getCombinedEnvelopeDocumentDownloadLink, delegateRecipient, envelopeRecipientDecline, integerSequence, askQuestion } from '@verdocs/js-sdk';
import { u as updateDocumentFieldValue, g as getFieldId, r as renderDocumentFlag, a as renderDocumentField, d as defaultHeight } from './utils-D9l-GFdv.js';
import { D as DownloadAction } from './Types-CIxfEdV7.js';
import { D as DocumentPageIcon, C as CheckCircleIcon } from './Icons-BU5rnXp2.js';
import { V as VerdocsToast } from './Toast-D97GxsI-.js';
import { S as SDKError } from './errors-C1sRVZWv.js';
import { S as Store } from './Datastore-C7hFgM52.js';
import './index-BglCURB-.js';

const verdocsSignCss = () => `verdocs-sign{display:-ms-flexbox;display:flex;overflow:hidden;min-height:700px;position:relative;-ms-flex-direction:column;flex-direction:column;-webkit-box-sizing:border-box;box-sizing:border-box;background-color:#f5f5f5;font-family:var(--verdocs-primary-font, "Inter", "Barlow", sans-serif)}verdocs-sign div{display:block;-webkit-box-sizing:border-box;box-sizing:border-box}verdocs-sign input{vertical-align:top}verdocs-sign>.document{-ms-flex:1;flex:1;width:100%;height:100%;-ms-flex-item-align:center;align-self:center;display:-ms-flexbox;display:flex;padding:15px;padding-right:140px;row-gap:15px;max-width:1200px;min-height:200px;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-sign>.document .inner{width:100%;max-width:1028px}verdocs-sign>.document .document-separator{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;gap:10px;padding:12px 20px;width:100%;max-width:1028px;-webkit-box-sizing:border-box;box-sizing:border-box;background-color:#33364b;color:white;border-radius:6px;font-size:16px;font-weight:500;margin-top:20px;-webkit-box-shadow:0 2px 4px rgba(0, 0, 0, 0.1);box-shadow:0 2px 4px rgba(0, 0, 0, 0.1)}verdocs-sign>.document .document-separator svg{-ms-flex-negative:0;flex-shrink:0}verdocs-sign>.document .document-separator:first-child{margin-top:0}verdocs-sign .signed-document-container{width:64%;margin-left:260px;-webkit-transition:all 0.3s ease;transition:all 0.3s ease}verdocs-sign .signed-document-container.zoom-normal{width:64%;margin-left:260px}verdocs-sign .signed-document-container.zoom-zoom1{width:80%;margin-left:200px}verdocs-sign .signed-document-container.zoom-zoom2{width:100%;margin-left:150px}verdocs-sign .signed-document-container.zoom-zoom2 .verdocs-flag-instance{opacity:0;pointer-events:none}@media (max-width: 768px){verdocs-sign verdocs-sign-footer{padding:0 10px}verdocs-sign verdocs-sign-footer .buttons{gap:8px}verdocs-sign verdocs-sign-footer .buttons button{font-size:10px}verdocs-sign .signed-document-container{width:100%;margin-left:0}verdocs-sign .signed-document-container.zoom-normal,verdocs-sign .signed-document-container.zoom-zoom1,verdocs-sign .signed-document-container.zoom-zoom2{width:100%;margin-left:0}verdocs-sign>.document{padding-right:15px}verdocs-sign .verdocs-flag-instance{display:none !important}verdocs-sign .controls-toolbar .center-controls{display:none}verdocs-sign .controls-toolbar .right-controls .mobile-next-button{display:block;margin-right:10px}verdocs-sign .controls-toolbar .right-controls .minus,verdocs-sign .controls-toolbar .right-controls .plus{display:none}}verdocs-sign .cover{top:0;left:0;right:0;bottom:0;display:-ms-flexbox;display:flex;z-index:5000;position:absolute;padding-top:100px;-ms-flex-align:center;align-items:center;-ms-flex-direction:column;flex-direction:column;background:rgba(0, 0, 0, 0.5)}verdocs-sign verdocs-ok-dialog .background-overlay{-ms-flex-align:start;align-items:flex-start;padding-top:100px}verdocs-sign .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-sign .fatal-error{position:absolute;z-index:100;top:0;left:0;right:0;bottom:0;background-color:#4a4a4a;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}verdocs-sign .fatal-error .placeholder{position:absolute;opacity:0.1;z-index:-1;top:0;left:0;right:0;bottom:0;width:612px;height:792px;-webkit-box-shadow:0 0 10px 5px rgba(0, 0, 0, 0.0588235294);box-shadow:0 0 10px 5px rgba(0, 0, 0, 0.0588235294);margin-top:15px}verdocs-sign .fatal-error .message{max-width:360px;width:50%;font-size:16px;background:white;-webkit-box-shadow:3px 3px 9px -1px rgba(0, 0, 0, 0.2470588235);box-shadow:3px 3px 9px -1px rgba(0, 0, 0, 0.2470588235)}verdocs-sign .fatal-error .header{color:white;font-size:18px;font-weight:500;padding:5px 10px;margin:0 0 10px 0;background:#4c56cb}verdocs-sign .fatal-error p{margin:1rem;font-size:14px;font-weight:400;padding:0 10px}@media print{verdocs-sign .header,.controls-toolbar,.verdocs-flag-instance,verdocs-signing-progress{display:none !important}verdocs-sign{min-height:auto;background-color:white}verdocs-sign>.document{overflow:visible;height:auto;display:block;padding:0;margin:0}verdocs-sign>.document .document-separator{display:none}verdocs-sign .signed-document-container{width:100%;margin:0}}#verdocs-sign-header{color:#fff;width:100%;display:-ms-flexbox;display:flex;z-index:1000;-ms-flex:0 0 46px;flex:0 0 46px;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)}#verdocs-sign-header .inner{width:100%;display:-ms-flexbox;display:flex;margin:0 auto;padding:0 12px;max-width:1200px;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;-webkit-column-gap:10px;-moz-column-gap:10px;column-gap:10px}#verdocs-sign-header .logo{width:80px;display:none;margin:-6px 0 0 0}#verdocs-sign-header .title{font-size:18px;font-weight:500;overflow:hidden;white-space:nowrap;padding:0 10px 0 0;text-overflow:ellipsis}@media (max-width: 670px){#verdocs-sign-header .title{font-size:14px}}#verdocs-sign-header .remaining-count{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;gap:8px;color:#ffffff;font-size:13px;font-weight:400;white-space:nowrap}#verdocs-sign-header .remaining-count .check-icon{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center}#verdocs-sign-header .remaining-count .check-icon svg{width:16px;height:16px;fill:#55bc81}#verdocs-sign-header .remaining-count .separator{opacity:0.5;margin:0 2px}#verdocs-sign-header .remaining-count .review-optional{cursor:pointer;text-decoration:underline}#verdocs-sign-header .remaining-count .review-optional:hover{color:#54d68c}@media (max-width: 670px){#verdocs-sign-header .remaining-count .review-optional{display:none}}@media (max-width: 670px){#verdocs-sign-header .remaining-count{font-size:12px}}#verdocs-sign-header .icon-button{width:20px;height:32px;display:-ms-flexbox;display:flex;cursor:pointer;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;border-radius:4px;-webkit-transition:background-color 0.2s;transition:background-color 0.2s}#verdocs-sign-header .icon-button svg path{fill:#ffffff}#verdocs-sign-header .icon-button:hover{background-color:rgba(255, 255, 255, 0.1)}#verdocs-sign-header .icon-button.disabled{opacity:0.35;pointer-events:none}#verdocs-sign-header .icon-button+.icon-button{margin-left:-6px}@media (max-width: 670px){#verdocs-sign-header .icon-button.magnify{display:none}}.spinner-overlay{position:fixed;top:0;left:0;right:0;bottom:0;z-index:1000;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;background:rgba(0, 0, 0, 0.4980392157);-ms-flex-pack:center;justify-content:center}.controls-toolbar{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;height:54px;padding:0 12px 0 24px;background-color:#ffffff;border-bottom:1px solid #e0e0e0;-webkit-box-shadow:none;box-shadow:none;font-family:"Inter", sans-serif;color:#424242;z-index:1000}.controls-toolbar .left-controls{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.controls-toolbar .left-controls .title{font-weight:500;font-size:16px;color:#242424;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.controls-toolbar .center-controls{-ms-flex:1;flex:1;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;gap:10px;font-size:14px;display:none}.controls-toolbar .center-controls .label{color:#000000;font-weight:300}.controls-toolbar .center-controls .select-wrapper{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.controls-toolbar .center-controls .select-wrapper verdocs-select-input{margin:0}.controls-toolbar .center-controls .select-wrapper verdocs-select-input .input-label{display:none}.controls-toolbar .center-controls .select-wrapper verdocs-select-input .input-element{background:transparent;border:1px solid #e0e0e0;height:32px;padding:2px 8px;min-width:60px;text-align:center;font-family:inherit;color:#424242}.controls-toolbar .center-controls .select-wrapper verdocs-select-input .input-element:focus{border-color:var(--verdocs-primary-color, #55bc81)}.controls-toolbar .center-controls .count{color:#000000;font-weight:300}.controls-toolbar .right-controls{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;justify-content:flex-end}.controls-toolbar .right-controls .mobile-next-button{display:none}.controls-toolbar .right-controls .icon-button{width:32px;height:32px;display:-ms-flexbox;display:flex;color:#424242;cursor:pointer;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;-webkit-transition:background-color 0.2s;transition:background-color 0.2s}.controls-toolbar .right-controls .icon-button:hover{background-color:#f5f5f5}.controls-toolbar .right-controls .icon-button.disabled{opacity:0.3;pointer-events:none}.controls-toolbar .right-controls .icon-button svg{display:block;width:20px;height:20px}`;

const ToolbarMinusIcon = `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M11 8C11.2761 8 11.5 8.22386 11.5 8.5C11.5 8.77614 11.2761 9 11 9H6C5.72386 9 5.5 8.77614 5.5 8.5C5.5 8.22386 5.72386 8 6 8H11ZM14 8.5C14 5.46243 11.5376 3 8.5 3C5.46243 3 3 5.46243 3 8.5C3 11.5376 5.46243 14 8.5 14C9.83879 14 11.0659 13.5217 12.0196 12.7266L16.1464 16.8536L16.2157 16.9114C16.4106 17.0464 16.68 17.0271 16.8536 16.8536C17.0488 16.6583 17.0488 16.3417 16.8536 16.1464L12.7266 12.0196C13.5217 11.0659 14 9.83879 14 8.5ZM4 8.5C4 6.01472 6.01472 4 8.5 4C10.9853 4 13 6.01472 13 8.5C13 10.9853 10.9853 13 8.5 13C6.01472 13 4 10.9853 4 8.5Z" fill="#424242" /></svg>`;
const ToolbarPlusIcon = `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M11.5 8.5C11.5 8.22386 11.2761 8 11 8H9V6C9 5.72386 8.77614 5.5 8.5 5.5C8.22386 5.5 8 5.72386 8 6V8H6C5.72386 8 5.5 8.22386 5.5 8.5C5.5 8.77614 5.72386 9 6 9H8V11C8 11.2761 8.22386 11.5 8.5 11.5C8.77614 11.5 9 11.2761 9 11V9H11C11.2761 9 11.5 8.77614 11.5 8.5ZM8.5 3C11.5376 3 14 5.46243 14 8.5C14 9.83879 13.5217 11.0659 12.7266 12.0196L16.8536 16.1464C17.0488 16.3417 17.0488 16.6583 16.8536 16.8536C16.68 17.0271 16.4106 17.0464 16.2157 16.9114L16.1464 16.8536L12.0196 12.7266C11.0659 13.5217 9.83879 14 8.5 14C5.46243 14 3 11.5376 3 8.5C3 5.46243 5.46243 3 8.5 3ZM8.5 4C6.01472 4 4 6.01472 4 8.5C4 10.9853 6.01472 13 8.5 13C10.9853 13 13 10.9853 13 8.5C13 6.01472 10.9853 4 8.5 4Z" fill="#424242" /></svg>`;
const ToolbarDownloadIcon = `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M15.5 16.9988C15.7761 16.9988 16 17.2226 16 17.4988C16 17.7442 15.8231 17.9484 15.5899 17.9907L15.5 17.9988H4.5C4.22386 17.9988 4 17.7749 4 17.4988C4 17.2533 4.17688 17.0492 4.41012 17.0068L4.5 16.9988H15.5ZM10.0001 2.00098C10.2456 2.00098 10.4497 2.17798 10.492 2.41124L10.5 2.50112L10.496 14.295L14.1414 10.6466C14.3148 10.4729 14.5842 10.4534 14.7792 10.5882L14.8485 10.646C15.0222 10.8194 15.0418 11.0888 14.907 11.2838L14.8492 11.3531L10.3574 15.8531C10.285 15.9257 10.1957 15.9714 10.1021 15.9901L9.99608 15.9999C9.83511 15.9999 9.69192 15.9237 9.60051 15.8056L5.14386 11.3537C4.94846 11.1586 4.94823 10.842 5.14336 10.6466C5.3168 10.4729 5.58621 10.4534 5.78117 10.5883L5.85046 10.6461L9.496 14.287L9.5 2.50083C9.50008 2.22469 9.724 2.00098 10.0001 2.00098Z" fill="#424242"/></svg>`;
const ToolbarPrintIcon = `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M5 4.5C5 3.67157 5.67157 3 6.5 3H13.5C14.3284 3 15 3.67157 15 4.5V5H15.5C16.8807 5 18 6.11929 18 7.5V12.5C18 13.3284 17.3284 14 16.5 14H15V15.5C15 16.3284 14.3284 17 13.5 17H6.5C5.67157 17 5 16.3284 5 15.5V14H3.5C2.67157 14 2 13.3284 2 12.5V7.5C2 6.11929 3.11929 5 4.5 5H5V4.5ZM6 5H14V4.5C14 4.22386 13.7761 4 13.5 4H6.5C6.22386 4 6 4.22386 6 4.5V5ZM5 13V11.5C5 10.6716 5.67157 10 6.5 10H13.5C14.3284 10 15 10.6716 15 11.5V13H16.5C16.7761 13 17 12.7761 17 12.5V7.5C17 6.67157 16.3284 6 15.5 6H4.5C3.67157 6 3 6.67157 3 7.5V12.5C3 12.7761 3.22386 13 3.5 13H5ZM6.5 11C6.22386 11 6 11.2239 6 11.5V15.5C6 15.7761 6.22386 16 6.5 16H13.5C13.7761 16 14 15.7761 14 15.5V11.5C14 11.2239 13.7761 11 13.5 11H6.5Z" fill="#424242"/></svg>`;
const VerdocsSign = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.sdkError = createEvent(this, "sdkError");
        this.envelopeLoaded = createEvent(this, "envelopeLoaded");
        this.envelopeUpdated = createEvent(this, "envelopeUpdated");
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = new VerdocsEndpoint({ sessionType: 'signing' });
        /**
         * The ID of the envelope to sign.
         */
        this.envelopeId = null;
        /**
         * The ID of the role that will be signing e.g. 'Recipient 1'
         */
        this.roleId = null;
        /**
         * The invite code for the signer.
         */
        this.inviteCode = null;
        /**
         * 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;
        /**
         * The style of the toolbar to display.
         */
        this.toolbarStyle = 'menu';
        this.recipient = null;
        this.hasSignature = false;
        this.nextButtonLabel = 'Start';
        this.nextSubmits = false;
        this.fatalErrorHeader = '';
        this.fatalErrorMessage = '';
        this.focusedField = '';
        this.disclosures = DEFAULT_DISCLOSURES;
        this.fieldUpdateCounter = 0;
        this.submitting = false;
        this.submitted = false;
        this.isDone = false;
        this.showDone = false;
        this.adoptingSignature = false;
        this.showLoadError = false;
        this.finishLater = false;
        this.showFinishLater = false;
        this.agreed = false;
        this.signatureId = null;
        this.initialId = null;
        this.documentsSingularPlural = 'document';
        this.authStep = null;
        this.authMethodStates = {};
        this.pageNumber = 1;
        this.kbaQuestions = null;
        this.showSpinner = false;
        // @State() fieldUpdateCounter = 0;
        this.declining = false;
        this.delegating = false;
        this.delegated = false;
        this.kbaChoices = [];
        this.showDownloadDialog = false;
        this.loading = true;
        this.envelope = null;
        this.zoomLevel = 'normal';
        this.signingProgressMode = 'start';
        this.polling = true;
        this.renderedPages = {};
        this.pollingInterval = null;
    }
    async componentDidLoad() {
        var _a, _b, _c, _d, _e, _f;
        this.updateZoomFromWindow();
        window.addEventListener('resize', () => this.updateZoomFromWindow());
        if (!this.envelopeId) {
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError('[SIGN] Missing required envelopId', 500, ''));
            return;
        }
        if (!this.roleId) {
            (_b = this.sdkError) === null || _b === void 0 ? void 0 : _b.emit(new SDKError('[SIGN] Missing required roleId', 500, ''));
            return;
        }
        if (!this.inviteCode) {
            (_c = this.sdkError) === null || _c === void 0 ? void 0 : _c.emit(new SDKError('[SIGN] Missing required inviteCode', 500, ''));
            return;
        }
        try {
            console.log(`[SIGN] Processing invite code for ${this.envelopeId} / ${this.roleId}`);
            // NOTE: We don't listen to the store here because we are often an independent
            // session and might have a different "view" of the envelope.
            const response = await startSigningSession(this.endpoint, this.envelopeId, this.roleId, this.inviteCode);
            this.processAuthResponse(response);
        }
        catch (e) {
            console.log('[SIGN] Error with signing session', e);
            (_d = this.sdkError) === null || _d === void 0 ? void 0 : _d.emit(new SDKError(e.message, (_e = e.response) === null || _e === void 0 ? void 0 : _e.status, (_f = e.response) === null || _f === void 0 ? void 0 : _f.data));
            this.showLoadError = true;
        }
    }
    componentDidRender() {
        const headerTarget = this.headerTargetId ? document.getElementById(this.headerTargetId) : null;
        const headerEl = document.getElementById('verdocs-sign-header');
        if (headerTarget && headerEl) {
            console.log('[SIGN] Moving header');
            headerEl.remove();
            headerTarget.append(headerEl);
        }
        this.setupIntersectionObserver();
    }
    disconnectedCallback() {
        var _a, _b, _c;
        this.stopPolling();
        (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
        window.removeEventListener('resize', () => this.updateZoomFromWindow());
        (_b = document.getElementById(this.getOrgStyleOverridesId())) === null || _b === void 0 ? void 0 : _b.remove();
        (_c = document.getElementById(this.getBrandStyleOverridesId())) === null || _c === void 0 ? void 0 : _c.remove();
    }
    updateZoomFromWindow() {
        const width = window.innerWidth;
        if (width < 768) {
            if (this.zoomLevel !== 'zoom2')
                this.zoomLevel = 'zoom2';
        }
        else if (width < 1024) {
            if (this.zoomLevel !== 'zoom1')
                this.zoomLevel = 'zoom1';
        }
        else {
            if (this.zoomLevel !== 'normal')
                this.zoomLevel = 'normal';
        }
    }
    setupIntersectionObserver() {
        // We only want to set this up once the elements exist
        const pages = this.el.querySelectorAll('verdocs-envelope-document-page');
        if (pages.length === 0)
            return;
        if (this.observer) {
            this.observer.disconnect();
        }
        const container = this.el.querySelector('.signed-document-container');
        const options = {
            root: container,
            rootMargin: '-40% 0px -40% 0px', // Helper to trigger when the middle 20% is visible
            threshold: 0,
        };
        this.observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const pageId = entry.target.id; // page-1
                    const pageNum = parseInt(pageId.replace('page-', ''), 10);
                    if (!isNaN(pageNum) && this.pageNumber !== pageNum) {
                        // console.log('[SIGN] Updated page number via scroll', pageNum);
                        this.pageNumber = pageNum;
                    }
                }
            });
        }, options);
        pages.forEach(page => this.observer.observe(page));
    }
    getOrgStyleOverridesId() {
        return `verdocs-org-style-overrides-${this.envelopeId}`;
    }
    getBrandStyleOverridesId() {
        return `verdocs-brand-style-overrides-${this.envelopeId}`;
    }
    // Injects a <style> tag into the document head containing any CSS overrides defined on the
    // envelope's organization. This allows the organization to apply custom styling to the signing
    // UI without rebuilding the SDK.
    // TODO: Clean up once js-sdk is updated (style_overrides is not yet in IEnvelope).
    applyOrgStyleOverrides() {
        var _a, _b;
        const styleId = this.getOrgStyleOverridesId();
        const existing = document.getElementById(styleId);
        const overrides = (_b = (_a = this.envelope) === null || _a === void 0 ? void 0 : _a.organization) === null || _b === void 0 ? void 0 : _b.style_overrides;
        if (typeof overrides === 'string') {
            const styleEl = existing || document.createElement('style');
            styleEl.id = styleId;
            styleEl.textContent = overrides;
            if (!existing) {
                document.head.appendChild(styleEl);
            }
        }
        else if (existing) {
            existing.remove();
        }
    }
    applyBrandStyleOverrides(brand) {
        const styleId = this.getBrandStyleOverridesId();
        const existing = document.getElementById(styleId);
        const overrides = brand === null || brand === void 0 ? void 0 : brand.style_overrides;
        if (typeof overrides === 'string' && overrides.length > 0) {
            const styleEl = existing || document.createElement('style');
            styleEl.id = styleId;
            styleEl.textContent = overrides;
            if (!existing) {
                document.head.appendChild(styleEl);
            }
        }
        else if (existing) {
            existing.remove();
        }
    }
    processAuthResponse(response) {
        var _a, _b, _c, _d;
        const { envelope, recipient, brand } = response;
        (_a = envelope.documents) === null || _a === void 0 ? void 0 : _a.sort((a, b) => (a.order !== b.order ? a.order - b.order : a.created_at.localeCompare(b.created_at)));
        const { auth_step } = recipient;
        this.recipient = recipient;
        this.envelope = envelope;
        this.disclosures = ((_c = (_b = this.envelope) === null || _b === void 0 ? void 0 : _b.organization) === null || _c === void 0 ? void 0 : _c.disclaimer) || DEFAULT_DISCLOSURES;
        this.applyOrgStyleOverrides();
        this.applyBrandStyleOverrides(brand);
        this.authStep = auth_step;
        this.delegated = !!recipient.delegated_to;
        this.agreed = recipient.agreed;
        // Intentionally ignore any pre-existing signatures/initials from the server. We always want to prompt the user
        // to adopt at least once per session so the signing flow is explicit after removing the up-front progress dialog.
        this.signatureId = null;
        this.initialId = null;
        this.submitted = recipient.status === 'submitted';
        this.loading = false;
        this.isDone = this.submitted;
        this.showDone = this.submitted;
        Store.updateEnvelope(this.envelopeId, envelope);
        if (this.envelope.documents.length > 0) {
            this.documentsSingularPlural = 'document(s)';
        }
        this.authMethodStates = recipient.auth_method_states || {};
        this.kbaQuestions = recipient.kba_questions;
        if (Object.values(this.authMethodStates).includes('failed')) {
            this.fatalErrorHeader = 'Recipient Verification Failed';
            this.fatalErrorMessage = 'We were unable to verify your identity. The sender has been notified.';
            this.isDone = true;
        }
        // TODO: Envelope "complete" | "declined" | "canceled"
        // TODO: Recipient "canceled"
        if (this.envelope.status === 'canceled') {
            this.fatalErrorHeader = 'Unable to Start Signing Session';
            this.fatalErrorMessage = 'This envelope has been canceled. The sender has been notified.';
        }
        else if (recipient.status === 'declined') {
            this.fatalErrorHeader = 'Declined';
            this.fatalErrorMessage = 'You have declined to sign this request. The sender has been notified.';
        }
        else if (this.agreed) {
            this.nextButtonLabel = 'Next';
        }
        this.checkRecipientFields();
        (_d = this.envelopeLoaded) === null || _d === void 0 ? void 0 : _d.emit({ endpoint: this.endpoint, envelope: this.envelope });
    }
    handleClickAgree() {
        this.submitting = true;
        console.log('[SIGN] Accepting disclosures', this.disclosures);
        envelopeRecipientAgree(this.endpoint, this.envelopeId, this.roleId, this.disclosures)
            .then(() => {
            var _a;
            this.nextButtonLabel = 'Next';
            this.recipient.agreed = true;
            this.submitting = false;
            this.agreed = true; // The server returns a recipient object but it's not "deep" so we track this locally
            (_a = this.envelopeUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope: this.envelope, event: 'agreed' });
        })
            .catch(e => {
            var _a, _b, _c;
            console.log('[SIGN] Unable to accept disclosures', e);
            VerdocsToast('Unable to accept disclosures, please try again later', { style: 'error' });
            (_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.submitting = false;
        });
    }
    handlePageSelect(e) {
        const pageNumber = parseInt(e.target.value);
        if (!isNaN(pageNumber)) {
            this.pageNumber = pageNumber;
            // We manually scroll the container to the top of the page element.
            // This avoids issues where the page might be nested or scrollIntoView behaves unexpectedly.
            const container = this.el.querySelector('.signed-document-container');
            const pageEl = this.el.querySelector(`#page-${pageNumber}`);
            if (container && pageEl) {
                // 20px buffer for visual spacing
                const top = pageEl.offsetTop - 20;
                container.scrollTo({ top, behavior: 'smooth' });
            }
        }
    }
    async handleOptionSelected(e) {
        var _a, _b;
        switch (e.detail.id) {
            case 'later':
                this.finishLater = true;
                this.showFinishLater = true;
                (_a = this.envelopeUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, envelope: this.envelope, event: 'later' });
                break;
            case 'delegate':
                this.delegating = true;
                break;
            case 'decline':
                this.declining = true;
                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':
                this.showDownloadDialog = true;
                this.startPolling();
                break;
        }
    }
    startPolling() {
        this.stopPolling();
        const checkPollingConditions = () => {
            var _a, _b, _c, _d, _e, _f;
            // NOTE: Polling logic for finalizing envelope
            const isSigned = ((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.status) === 'complete' || !!((_b = this.envelope) === null || _b === void 0 ? void 0 : _b.signed);
            const hasCertificate = (_d = (_c = this.envelope) === null || _c === void 0 ? void 0 : _c.documents) === null || _d === void 0 ? void 0 : _d.some(d => d.type === 'certificate');
            const allRecipientsSubmitted = (_f = (_e = this.envelope) === null || _e === void 0 ? void 0 : _e.recipients) === null || _f === void 0 ? void 0 : _f.every(r => r.status === 'submitted');
            if (isSigned && hasCertificate)
                return false;
            if (!allRecipientsSubmitted)
                return false;
            return true;
        };
        if (!checkPollingConditions()) {
            return;
        }
        this.polling = true;
        this.pollingInterval = setInterval(async () => {
            try {
                const envelope = await getEnvelope(this.endpoint, this.envelopeId);
                this.envelope = envelope;
                Store.updateEnvelope(this.envelopeId, envelope);
                this.checkRecipientFields();
                if (!checkPollingConditions()) {
                    this.stopPolling();
                }
            }
            catch (e) {
                console.error('[SIGN] Polling error', e);
                this.stopPolling();
            }
        }, 5000);
    }
    stopPolling() {
        if (this.pollingInterval) {
            clearInterval(this.pollingInterval);
            this.pollingInterval = null;
        }
        this.polling = false;
    }
    handleZoomIn() {
        if (this.zoomLevel === 'normal') {
            this.zoomLevel = 'zoom1';
        }
        else if (this.zoomLevel === 'zoom1') {
            this.zoomLevel = 'zoom2';
        }
    }
    handleZoomOut() {
        if (this.zoomLevel === 'zoom1') {
            this.zoomLevel = 'normal';
        }
        else if (this.zoomLevel === 'zoom2') {
            this.zoomLevel = 'zoom1';
        }
    }
    updateRecipientFieldValue(fieldName, updateResult) {
        console.log('[SIGN] updateRecipientFieldValue', fieldName, updateResult);
        this.getRecipientFields().forEach(oldField => {
            if (oldField.name === fieldName) {
                oldField.value = updateResult.value;
                // TODO: Keeping this while attachments still rely on it
                oldField.settings = updateResult.settings;
                updateDocumentFieldValue(oldField);
                this.fieldUpdateCounter++;
                this.markEnvelopeStarted();
                this.checkRecipientFields();
            }
        });
    }
    getStartedKey() {
        var _a;
        return `${this.envelopeId}:${((_a = this.recipient) === null || _a === void 0 ? void 0 : _a.role_name) || ''}`;
    }
    markEnvelopeStarted() {
        const startedEnvelopes = JSON.parse(localStorage.getItem('startedEnvelopes') || '[]');
        const key = this.getStartedKey();
        if (!startedEnvelopes.includes(key)) {
            startedEnvelopes.push(key);
            while (startedEnvelopes.length > 10) {
                startedEnvelopes.shift();
            }
            localStorage.setItem('startedEnvelopes', JSON.stringify(startedEnvelopes));
        }
    }
    saveFieldChange(fieldName, value, prepared) {
        // Although the inputs disable themselves, the blur handler can still try to re-save
        // the value already in the field. Bypassing that here is easier than adding yet more
        // logic to the fields.
        const field = this.getRecipientFields().find(field => field.name === fieldName);
        if (field === null || field === void 0 ? void 0 : field.readonly) {
            return;
        }
        console.log('[SIGN] saveFieldChange', fieldName, { value, prepared });
        updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, fieldName, value, prepared)
            .then(updateResult => this.updateRecipientFieldValue(fieldName, updateResult))
            .catch(e => {
            var _a, _b, _c, _d, _e, _f;
            if (((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 401 && ((_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.error) === 'jwt expired') {
                console.log('[SIGN] Signing session expired');
                this.fatalErrorHeader = 'Signing Session Expired';
                this.fatalErrorMessage = 'Please reload your browser to continue.';
            }
            else {
                console.log('[SIGN] Server error', e);
                VerdocsToast('Unable to save change, please try again later', { style: 'error' });
            }
            (_d = this.sdkError) === null || _d === void 0 ? void 0 : _d.emit(new SDKError(e.message, (_e = e.response) === null || _e === void 0 ? void 0 : _e.status, (_f = e.response) === null || _f === void 0 ? void 0 : _f.data));
        });
    }
    async handleFieldChange(field, e) {
        if (!e.target) {
            return;
        }
        const { value, checked } = e.target;
        switch (field.type) {
            // TODO: Remove legacy type when no longer needed
            case 'textarea':
            case 'textbox':
                return this.saveFieldChange(field.name, value, false);
            case 'checkbox': {
                return this.saveFieldChange(field.name, String(e.target.checked), false);
            }
            case 'radio': {
                return this.saveFieldChange(field.name, String(e.target.checked), false);
            }
            case 'dropdown':
                // TODO: Set prepared to false server-side.
                console.log('Saving dropdown', field.name, e.detail);
                return this.saveFieldChange(field.name, e.detail, false);
            case 'initial':
                // This can be caused by a focus-out event if the user clicks the field
                // after it's already filled in, then clicks something else like a textbox.
                // We don't visually indicate the focus, but it's still there.
                // NOTE: We now allow null to clear the field
                if (e.detail === undefined) {
                    return;
                }
                if (e.detail === null) {
                    console.log('[SIGN] Clearing initial');
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, null, false);
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                // If we already have an initials block, apply it
                if (this.initialId) {
                    console.log('[SIGN] Reusing initial', this.initialId);
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, this.initialId, false);
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                // If it's a UUID, it's an existing initial ID we can just reuse
                if (typeof e.detail === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.detail)) {
                    console.log('[SIGN] Reusing initial', e.detail);
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, e.detail, false);
                    this.initialId = e.detail;
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                this.showSpinner = true;
                const initialsBlob = await (await fetch(e.detail)).blob();
                return createInitials(this.endpoint, 'initial', initialsBlob) //
                    .then(async (newInitials) => {
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, newInitials.id, false);
                    this.updateRecipientFieldValue(field.name, updateResult);
                    this.initialId = newInitials.id;
                    this.showSpinner = false;
                })
                    .catch(e => {
                    console.log('Error updating initials', e);
                    VerdocsToast('Unable to save initials, please try again later', { style: 'error' });
                    this.showSpinner = false;
                });
            case 'signature':
                // This can be caused by a focus-out event if the user clicks the field
                // after it's already filled in, then clicks something else like a textbox.
                // We don't visually indicate the focus, but it's still there.
                // NOTE: We now allow null to clear the field
                if (e.detail === undefined) {
                    return;
                }
                if (e.detail === null) {
                    console.log('[SIGN] Clearing signature');
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, null, false);
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                // If we already have a signature block, apply it
                if (this.signatureId) {
                    console.log('[SIGN] Reusing signature', this.signatureId);
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, this.signatureId, false);
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                // If it's a UUID, it's an existing signature ID we can just reuse
                if (typeof e.detail === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.detail)) {
                    console.log('[SIGN] Reusing signature', e.detail);
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, e.detail, false);
                    this.signatureId = e.detail;
                    return this.updateRecipientFieldValue(field.name, updateResult);
                }
                this.showSpinner = true;
                const signatureBlob = await (await fetch(e.detail)).blob();
                console.log('[SIGN] Creating new signature');
                return createSignature(this.endpoint, 'signature', signatureBlob) //
                    .then(async (newSignature) => {
                    console.log('Signature update result', newSignature);
                    const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, field.name, newSignature.id, false);
                    this.updateRecipientFieldValue(field.name, updateResult);
                    this.signatureId = newSignature.id;
                    this.showSpinner = false;
                })
                    .catch(e => {
                    console.warn('[SIGN] Error updating signature', e);
                    VerdocsToast('Unable to save signature, please try again later', { style: 'error' });
                    this.showSpinner = false;
                });
            case 'date':
                const { formattedDate } = e.detail;
                if (formattedDate) {
                    return this.saveFieldChange(field.name, formattedDate, false);
                }
                break;
            case 'timestamp':
                console.log('[SIGN] Updating timestamp', { value, ts: e.target.getAttribute('timestamp') });
                break;
            default:
                console.log('[SIGN] Unhandled field update', { value, checked }, field);
                break;
        }
    }
    getSortedFillableFields() {
        const recipientFields = this.getRecipientFields().filter(field => field.type !== 'timestamp' && !field.readonly);
        sortFields(recipientFields);
        return recipientFields;
    }
    /** Like getSortedFillableFields but includes readonly fields, for rendering purposes only. */
    getSortedDisplayableFields() {
        const recipientFields = this.getRecipientFields().filter(field => field.type !== 'timestamp');
        sortFields(recipientFields);
        return recipientFields;
    }
    async handleNext() {
        var _a;
        if (this.nextSubmits) {
            try {
                // Patches the date picker to be forcibly removed if still showing during submission
                (_a = document.getElementById('air-datepicker-global-container')) === null || _a === void 0 ? void 0 : _a.remove();
                this.submitting = true;
                const result = await envelopeRecipientSubmit(this.endpoint, this.envelopeId, this.roleId);
                console.log('[SIGN] Submitted successfully', result);
                // TODO: The "proper" way is generating an error from Stencil
                //  NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which
                //  the new node is to be inserted is not a child of this node.
                window.location.reload();
            }
            catch (e) {
                console.log('[SIGN] Error submitting', e);
                this.submitting = false;
                VerdocsToast('Unable to submit document, please try again.', { style: 'error' });
            }
            return;
        }
        // Find all unfilled fields and move to the next one in sequence
        const allUnfilled = this.getSortedFillableFields().filter(f => !this.isFieldActuallyFilled(f));
        const nextUnfilled = this.getNextFieldFromList(allUnfilled);
        if (nextUnfilled) {
            const id = getFieldId(nextUnfilled);
            const el = document.getElementById(id);
            el === null || el === void 0 ? void 0 : el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
            el === null || el === void 0 ? void 0 : el.focusField();
            this.focusedField = nextUnfilled.name;
        }
    }
    handleNextOptional() {
        const unfilledOptional = this.getSortedFillableFields().filter(f => !f.required && !this.isFieldActuallyFilled(f));
        const next = this.getNextFieldFromList(unfilledOptional);
        if (next) {
            const id = getFieldId(next);
            const el = document.getElementById(id);
            el === null || el === void 0 ? void 0 : el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
            el === null || el === void 0 ? void 0 : el.focusField();
            this.focusedField = next.name;
        }
    }
    getRecipientFields() {
        var _a;
        return ((_a = this.envelope) === null || _a === void 0 ? void 0 : _a.fields.filter(field => field.role_name === this.recipient.role_name)) || [];
    }
    getRequiredTotalCount() {
        return this.getSortedFillableFields().filter(f => f.required).length;
    }
    getRequiredFilledCount() {
        return this.getSortedFillableFields().filter(f => f.required && this.isFieldActuallyFilled(f)).length;
    }
    getOptionalUnfilledCount() {
        return this.getSortedFillableFields().filter(f => !f.required && !this.isFieldActuallyFilled(f)).length;
    }
    // See if everything that "needs to be" filled in is, and all "fillable fields" are valid
    checkRecipientFields() {
        const invalidFields = this.getRecipientFields().filter(field => !isFieldValid(field, this.getRecipientFields()));
        if (invalidFields.length < 1) {
            this.nextButtonLabel = 'Finish';
            if (!this.nextSubmits) {
                this.nextSubmits = true;
            }
        }
        else {
            this.nextButtonLabel = 'Next';
            this.nextSubmits = false;
        }
        this.updateAllFlags();
        // We need a way to know if the user has started signing. But after trying two
        // obvious ways (has the user adopted a signature? are any fields filled in yet?)
        // they both had flaws (we could be carrying over a sig from a previous session,
        // and things like defaults and auto-filled fields make the filled-field approach
        // tricky to maintain).
        // This is sort of a Hail Mary but it works well for now. We just keep a variable
        // in localStorage that tracks the last 10 envelopes the user has "started".
        // We never get a chance to clean them up but 10 GUIDs is tiny compared to what
        // many apps store in a user's browser.
        const startedEnvelopes = JSON.parse(localStorage.getItem('startedEnvelopes') || '[]');
        const hasStarted = startedEnvelopes.includes(this.getStartedKey());
        if (this.nextSubmits) {
            this.signingProgressMode = 'completed';
        }
        else if (hasStarted) {
            this.signingProgressMode = 'signing';
        }
        else {
            this.signingProgressMode = 'start';
        }
    }
    isFieldActuallyFilled(field) {
        if (field.type === 'radio' && field.group) {
            const groupFilled = this.getRecipientFields().some(f => f.group === field.group && f.value === 'true');
            if (groupFilled) {
                return true;
            }
        }
        return (isFieldFilled(field, this.getRecipientFields()) &&
            (field.type !== 'dropdown' || !!field.value) &&
            (field.type !== 'radio' || field.value === 'true') &&
            (field.type !== 'checkbox' || field.value === 'true'));
    }
    getNextRequiredField() {
        // Find and focus the next incomplete field (that is fillable)
        const emptyFields = this.getSortedFillableFields().filter(field => field.required && !this.isFieldActuallyFilled(field));
        sortFields(emptyFields);
        if (emptyFields.length === 0) {
            const allUnfilled = this.getSortedFillableFields().filter(field => !this.isFieldActuallyFilled(field));
            sortFields(allUnfilled);
            if (allUnfilled.length > 0) {
                // If we are here, there are no required fields left, but there are optional ones.
                return this.getNextFieldFromList(allUnfilled);
            }
            return null;
        }
        return this.getNextFieldFromList(emptyFields);
    }
    getNextFieldFromList(fields) {
        const focusedIndex = fields.findIndex(field => field.name === this.focusedField);
        let nextFocusedIndex = focusedIndex + 1;
        if (nextFocusedIndex >= fields.length) {
            nextFocusedIndex = 0;
        }
        // Note: isFieldFilled check above should handle 'initialed'/'signed'.
        return fields[nextFocusedIndex];
    }
    handlePrev() {
        var _a;
        const allFields = this.getSortedFillableFields();
        const focusedIndex = allFields.findIndex(f => f.name === this.focusedField);
        if (focusedIndex > 0) {
            const prevField = allFields[focusedIndex - 1];
            const id = getFieldId(prevField);
            const el = document.getElementById(id);
            el === null || el === void 0 ? void 0 : el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            (_a = el === null || el === void 0 ? void 0 : el.focusField) === null || _a === void 0 ? void 0 : _a.call(el);
            this.focusedField = prevField.name;
        }
    }
    updateAllFlags() {
        Object.values(this.renderedPages).forEach(pageInfo => {
            this.updateFlagsForPage(pageInfo);
        });
    }
    updateFlagsForPage(pageInfo) {
        if (!pageInfo)
            return;
        const controlsDiv = document.getElementById(pageInfo.containerId + '-controls');
        if (!controlsDiv)
            return;
        // Remove existing flags
        const existingFlags = controlsDiv.querySelectorAll('.verdocs-flag-instance');
        existingFlags.forEach(el => el.remove());
        let nextField = this.getNextRequiredField();
        const focusedFieldObj = this.getRecipientFields().find(f => f.name === this.focusedField);
        // If the currently focused field is unfilled, we should point the flag to IT, not the next one.
        // getNextRequiredField() is designed for the "Next" button (skipping current), but the visual flag
        // should guide the user to the current task if it's incomplete.
        if (focusedFieldObj && !isFieldFilled(focusedFieldObj, this.getRecipientFields())) {
            nextField = focusedFieldObj;
        }
        if (nextField && nextField.page === pageInfo.pageNumber && nextField.document_id === pageInfo.documentId) {
            const variant = 'fill';
            let label = 'FILL';
            let showSkip = false;
            switch (nextField.type) {
                case 'signature':
                    label = 'SIGN';
                    break;
                case 'initial':
                    label = 'INITIAL';
                    break;
                case 'checkbox':
                    label = 'CHECK';
                    break;
                case 'radio':
                    label = 'SELECT';
                    break;
                case 'date':
                case 'dropdown':
                    label = 'SELECT';
                    break;
                case 'attachment':
                    label = 'ATTACH';
                    break;
                case 'payment':
                    label = 'PAY';
                    break;
            }
            if (!nextField.required) {
                showSkip = true;
            }
            renderDocumentFlag(pageInfo, nextField.y, nextField.height || defaultHeight(nextField.type), {
                variant,
                label,
                showSkip,
                onSkip: () => {
                    this.handleNext();
                },
                onClick: () => {
                    var _a;
                    const id = getFieldId(nextField);
                    const el = document.getElementById(id);
                    el === null || el === void 0 ? void 0 : el.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    (_a = el === null || el === void 0 ? void 0 : el.focusField) === null || _a === void 0 ? void 0 : _a.call(el);
                },
            });
        }
    }
    attachFieldAttributes(pageInfo, field, el) {
        // We can get called multiple times as rendering completes and it's hard to avoid that
        // because it's a ton of work for the callers to know it's been done already. But we
        // don't want to attach multiple event listeners or we get dupe event handling, like
        // calling the server twice on every field update. Since JS has no removeAllEventListeners()
        // option, using removeEventListener() isn't reliable the way Stencil binds local function
        // contexts, and cloneNode messes up the rest of the rendering, we just track it with a flag.
        if (el.getAttribute('attached') === '1') {
            return;
        }
        el.setAttribute('attached', '1');
        el.addEventListener('input', (e) => {
            // console.log('[SIGN] onfieldInput', e.detail, e.target.value);
            // These field types don't emit fieldChange. Should we standardize on that? We don't tap "input" for fields like
            // text boxes because we'd be updating the field on every keystroke. We do those on blur which fires fieldChange.
            if (e.target.type === 'radio' || e.target.type === 'checkbox') {
                // if (e.target.type === 'radio' || e.target.name.includes('date') || e.target.name.includes('checkbox')) {
                this.handleFieldChange(field, e).finally(() => this.checkRecipientFields());
            }
            else {
                this.checkRecipientFields();
            }
        });
        el.addEventListener('attached', async (e) => {
            console.log('[SIGN] onAttached', e.detail, e.target.value);
            this.showSpinner = true;
            try {
                const updateResult = await uploadEnvelopeFieldAttachment(this.endpoint, this.envelopeId, this.roleId, field.name, e.detail);
                this.updateRecipientFieldValue(field.name, updateResult);
                this.checkRecipientFields();
                const newEl = renderDocumentField('envelope', field, pageInfo, { disabled: false, editable: false, draggable: false, done: this.isDone });
                this.attachFieldAttributes(pageInfo, field, newEl);
                this.showSpinner = false;
            }
            catch (e) {
                console.log('Error uploading attachment', e);
                VerdocsToast('Unable to upload attachment, please try again later', { style: 'error' });
                this.showSpinner = false;
            }
        });
        el.addEventListener('deleted', async (e) => {
            console.log('[SIGN] onDeleted', e.detail, e.target.value);
            this.showSpinner = true;
            try {
                const updateResult = await deleteEnvelopeFieldAttachment(this.endpoint, this.envelopeId, this.roleId, field.name);
                console.log('[SIGN] Deleted attachment', updateResult);
                this.updateRecipientFieldValue(field.name, updateResult);
                this.checkRecipientFields();
                const newEl = renderDocumentField('envelope', field, pageInfo, { disabled: false, editable: false, draggable: false, done: this.isDone });
                this.attachFieldAttributes(pageInfo, field, newEl);
                this.showSpinner = false;
            }
            catch (e) {
                console.log('Error uploading attachment', e);
                VerdocsToast('Unable to upload attachment, please try again later', { style: 'error' });
                this.showSpinner = false;
            }
        });
        el.addEventListener('focusout', e => {
            // These field types trigger focusout as they're used, even without a value change.
            // Signature/Initial fields handle their own changes via fieldChange/adopt events, so we ignore focusout to prevent double-saves.
            if (field.type !== 'dropdown' &&
                field.type !== 'attachment' &&
                field.type !== 'signature' &&
                field.type !== 'initial' &&
                field.type !== 'checkbox' &&
                field.type !== 'radio') {
                this.handleFieldChange(field, e).finally(() => this.checkRecipientFields());
            }
        });
        el.addEventListener('fieldChange', e => {
            this.handleFieldChange(field, e).finally(() => this.checkRecipientFields());
        });
        el.addEventListener('adopt', () => {
            this.focusedField = field.name;
            this.adoptingSignature = true;
        });
        el.setAttribute('templateid', this.envelope.template_id);
        el.setAttribute('fieldname', field.name);
        el.setAttribute('page', pageInfo.pageNumber);
        el.setAttribute('xScale', pageInfo.xScale);
        el.setAttribute('yScale', pageInfo.yScale);
        const fullName = formatFullName(this.recipient);
        el.setAttribute('initials', fullNameToInitials(fullName));
        el.setAttribute('name', fullName);
        if (this.signatureId) {
            el.setAttribute('signatureid', this.signatureId);
        }
        if (this.initialId) {
            el.setAttribute('initialid', this.initialId);
        }
    }
    handlePageRendered(e) {
        const pageInfo = e.detail;
        this.renderedPages[`${pageInfo.documentId}:${pageInfo.pageNumber}`] = pageInfo;
        // console.log('Page rendered', pageInfo);
        // NOTE: We don't filter on pageNumber here because we need the position in the
        // entire list to set the tabIndex.
        const recipientFields = this.getSortedDisplayableFields();
        // console.log('[SIGN] Rendering fields for page', pageInfo.pageNumber, recipientFields);
        // First render the fields for the signer
        recipientFields
            .filter(field => field && field.document_id === pageInfo.documentId && field.page === pageInfo.pageNumber)
            .forEach((field, tabIndex) => {
            const el = renderDocumentField('envelope', field, pageInfo, { disabled: false, editable: false, draggable: false, done: this.isDone }, tabIndex);
            if (!el) {
                return;
            }
            if (Array.isArray(el)) {
                el.map(e => this.attachFieldAttributes(pageInfo, field, e));
            }
            else {
                this.attachFieldAttributes(pageInfo, field, el);
            }
        });
        // Now render the fields for other signers who have yet to act
        this.envelope.recipients
            .filter(r => r.role_name !== this.recipient.role_name && (r.status === 'invited' || r.status === 'opened' || r.status === 'pending'))
            .forEach(() => {
            this.getRecipientFields()
                .filter(field => field.document_id === pageInfo.documentId && field.page === pageInfo.pageNumber)
                .forEach(field => {
                const el = renderDocumentField('envelope', field, pageInfo, { disabled: true, editable: false, draggable: false, done: this.isDone });
                if (!el) {
                    return;
                }
                if (Array.isArray(el)) {
                    el.map(e => this.attachFieldAttributes(pageInfo, field, e));
                }
                else {
                    this.attachFieldAttributes(pageInfo, field, el);
                }
            });
        });
        this.checkRecipientFields();
        this.updateFlagsForPage(pageInfo);
    }
    handleAuthenticateSigner(params) {
        console.log('[SIGN] Submitting authentication step', params);
        verifySigner(this.endpoint, params)
            .then(r => {
            console.log('[SIGN] Verification successful', r);
            this.processAuthResponse(r);
        })
            .catch(e => {
            var _a, _b, _c, _d, _e, _f;
            console.log('[SIGN] Error submitting authentication step', e);
            console.log((_a = e.response) === null || _a === void 0 ? void 0 : _a.data);
            if ((_d = (_c = (_b = e.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.error) === null || _d === void 0 ? void 0 : _d.includes('failed')) {
                this.fatalErrorHeader = 'Recipient Verification Failed';
                this.fatalErrorMessage = 'We were unable to verify your identity. The sender has been notified.';
                this.isDone = true;
            }
            else {
                VerdocsToast(((_f = (_e = e.response) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.error) || 'Unable to verify your identity. Please try again.', { style: 'error' });
            }
        });
    }
    async handleOnDownload(e) {
        var _a, _b;
        const { action, documentId } = e.detail;
        console.log('[SIGN] Download action selected:', action, documentId);
        try {
            switch (action) {
                case DownloadAction.certificate:
                    const cert = this.envelope.documents.find(d => d.type === 'certificate');
                    if (cert) {
                        const url = await getEnvelopeDocumentDownloadLink(this.endpoint, cert.id);
                        window.open(url, '_blank');
                    }
                    else {
                        VerdocsToast('Certificate not yet available.', { style: 'info' });
                    }
                    break;
                case DownloadAction.combined:
                    // The certificate & combined doc use the same envelopeDocument.id in their filename.
                    const combinedDocumentId = documentId || ((_a = this.envelope.documents.find(doc => doc.type === 'certificate')) === null || _a === void 0 ? void 0 : _a.id);
                    const combinedDocumentUrl = await getCombinedEnvelopeDocumentDownloadLink(this.endpoint, combinedDocumentId);
                    window.open(combinedDocumentUrl, '_blank');
                    break;
                case DownloadAction.document:
                    const targetDocId = documentId || ((_b = this.envelope.documents.find(d => d.type === 'attachment')) === null || _b === void 0 ? void 0 : _b.id);
                    if (targetDocId) {
                        const url = await getEnvelopeDocumentDownloadLink(this.endpoint, targetDocId);
                        window.open(url, '_blank');
                    }
                    break;
                case DownloadAction.zip:
                    // The helper in verdocs-view used getEnvelopesZip with an array
                    const blob = await getEnvelopesZip(this.endpoint, [this.envelopeId]);
                    const url = window.URL.createObjectURL(blob.data);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${this.envelope.name}.zip`;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                    break;
            }
        }
        catch (err) {
            console.error('Download error', err);
            VerdocsToast('Unable to complete download request.', { style: 'error' });
        }
    }
    render() {
        var _a;
        if (this.showLoadError) {
            return (h(Host, null, h("verdocs-ok-dialog", { heading: "Unable to Start Signing", message: `Sorry, your invite code is invalid or has expired. Please check your email for an updated invitation, or contact the sender.`, buttonLabel: "OK", onNext: () => {
                    window.location.reload();
                } })));
        }
        if (!this.envelope) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        if (this.fatalErrorMessage) {
            return (h(Host, { class: { agreed: this.agreed } }, h("div", { class: "fatal-error" }, h("div", { class: "message" }, h("div", { class: "header" }, this.fatalErrorHeader), h("p", null, this.fatalErrorMessage)))));
        }
        if (this.delegated) {
            return (h(Host, { class: { agreed: false } }, h("div", { class: "fatal-error" }, h("div", { class: "message" }, h("div", { class: "header" }, "Delegated Signing Request"), h("p", null, "You have delegated signing to another recipient. You will not be able to sign this request again.")))));
        }
        if (this.isDone) {
            return (h(Host, { class: { agreed: this.agreed } }, h("verdocs-view", { endpoint: this.endpoint, envelopeId: this.envelopeId, onSdkError: e => { var _a; return (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(e.detail); } }), this.showDone && (h("verdocs-ok-dialog", { heading: "You're Done!", message: `You can access the ${this.documentsSingularPlural} at any time by clicking on the link from the invitation email.<br /><br />After all recipients have completed their actions, you will receive an email with the document and envelope certificate attached.`, onNext: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    this.showDone = false;
                    this.isDone = true;
                } })), this.submitting && (h("div", { class: "loading-indicator" }, h("verdocs-loader", null)))));
        }
        if (this.delegating) {
            return (h(Host, { class: "agreed" }, h("div", { class: "document", style: { paddingTop: '15px' } }, 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" })), h("verdocs-delegate-dialog", { endpoint: this.endpoint, envelope: this.envelope, onExit: () => (this.delegating = false), onNext: (e) => {
                    delegateRecipient(this.endpoint, this.envelopeId, this.roleId, e.detail)
                        .then(r => {
                        VerdocsToast('Delegation request submitted.', { style: 'success' });
                        console.log('[SIGN] Delegated successfully', r);
                        this.delegated = true;
                        this.delegating = false;
                    })
                        .catch(e => {
                        console.log('[SIGN] Error delegating request', e);
                        VerdocsToast('Unable to process delegation request. Please try again later.', { style: 'error' });
                    });
                } })));
        }
        if (this.declining) {
            return (h(Host, { class: "agreed" }, h("div", { class: "document", style: { paddingTop: '15px' } }, 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" })), h("verdocs-ok-dialog", { heading: "Decline Signing Request", message: `If you decline to sign this request, you will not be able to sign again in the future. The envelope sender will be notified.`, buttonLabel: "OK", showCancel: true, onExit: () => (this.declining = false), onNext: () => {
                    envelopeRecipientDecline(this.endpoint, this.envelopeId, this.roleId)
                        .then(r => {
                        console.log('[SIGN] Decline result', r);
                        window.location.reload();
                    })
                        .catch(e => {
                        console.warn('[SIGN] Error declining signing session', e);
                        VerdocsToast('Unable to decline, please try again later', { style: 'error' });
                    });
                } })));
        }
        if (!this.agreed) {
            return (h(Host, { class: "agreed" }, h("div", { class: "document", style: { paddingTop: '15px' } }, 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" })), h("verdocs-disclosure-dialog", { disclosures: this.disclosures, delegator: this.recipient.delegator, onDelegate: () => (this.delegating = true), onDecline: () => (this.declining = true), onAccept: () => this.handleClickAgree() })));
        }
        if (this.authStep === 'passcode') {
            return h("verdocs-passcode-dialog", { endpoint: this.endpoint, onNext: e => this.processAuthResponse(e.detail.response) });
        }
        if (this.authStep === 'email') {
            return (h("verdocs-otp-dialog", { endpoint: this.endpoint, method: "email", onNext: async (e) => {
                    this.processAuthResponse(e.detail.response);
                } }));
        }
        if (this.authStep === 'kba' && !this.authMethodStates.kba) {
            return (h(Host, { class: "kba" }, h("div", { id: "verdocs-sign-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", { class: "document", style: { paddingTop: '15px' } }, 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" })), h("div", { class: "cover" }, h("div", { class: "kba" }, h("verdocs-kba-dialog", { mode: "identity", helptitle: "Document requires identity verification", helptext: "Please complete your contact details to proceed.", recipient: this.recipient, onNext: async (e) => {
                    const recipDetails = e.detail;
                    this.handleAuthenticateSigner({
                        auth_method: 'kba',
                        first_name: recipDetails.first_name,
                        last_name: recipDetails.last_name,
                        address: recipDetails.address,
                        city: recipDetails.city,
                        state: recipDetails.state,
                        zip: recipDetails.zip,
                        dob: recipDetails.dob,
                    });
                } })))));
        }
        if (this.authStep === 'kba' && this.authMethodStates.kba === 'questions') {
            const questionNumber = this.kbaChoices.length;
            const kbaQuestion = this.kbaQuestions[questionNumber];
            return (h(Host, { class: "kba" }, h("div", { id: "verdocs-sign-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", { class: "document", style: { paddingTop: '15px' } }, 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" })), h("div", { class: "cover" }, h("div", { class: "kba" }, this.kbaChoices.length >= this.kbaQuestions.length ? (h("verdocs-spinner", null)) : (h("verdocs-kba-dialog", { mode: "choice", helptitle: "Your identity requires additional verification", helptext: (kbaQuestion === null || kbaQuestion === void 0 ? void 0 : kbaQuestion.prompt) || 'Please select one of the options below.', choices: (kbaQuestion === null || kbaQuestion === void 0 ? void 0 : kbaQuestion.answer) || ['Skip Question'], step: questionNumber + 1, steps: this.kbaQuestions.length, onNext: async (e) => {
                    const answer = e.detail;
                    this.kbaChoices = [...this.kbaChoices, answer];
                    if (this.kbaChoices.length >= this.kbaQuestions.length) {
                        const responses = this.kbaQuestions.map((q, i) => ({ type: q.type, answer: this.kbaChoices[i] }));
                        console.log('Submitting KBA responses', this.kbaChoices, responses);
                        this.handleAuthenticateSigner({ auth_method: 'kba', responses });
                    }
                } }))))));
        }
        const inProgressMenuOptions = [
            { id: 'later', label: 'Finish Later' }, //
            // {id: 'claim', label: 'Claim the Document', disabled: true},
            { id: 'decline', label: 'Decline to Sign' },
            { id: 'print', label: 'Print Without Signing' },
            { id: 'download', label: 'Download' },
        ];
        const doneMenuOptions = [
            { id: 'print', label: 'Print' },
            { id: 'download', label: 'Download' },
        ];
        if (this.recipient.delegator) {
            inProgressMenuOptions.unshift({ id: 'delegate', label: 'Delegate' });
        }
        const invalidFields = this.getRecipientFields().filter(field => !isFieldValid(field, this.getRecipientFields()));
        invalidFields.length > 0
            ? console.log('[SIGN] Invalid fields remaining', invalidFields.map(field => field.name))
            : console.log('[SIGN] All field valid');
        const totalPages = this.envelope.documents.reduce((acc, doc) => acc + doc.pages, 0);
        const pageOptions = integerSequence(1, totalPages).map(p => ({ label: p.toString(), value: p.toString() }));
        let globalPageCounter = 0;
        return (h(Host, null, this.toolbarStyle === 'menu' && (h("div", { id: "verdocs-sign-header" }, h("div", { class: "inner" }, h("div", { class: "title" }, this.envelope.name), h("div", { style: { flex: '1' } }), !this.finishLater &&
            (() => {
                const remaining = this.getRequiredTotalCount() - this.getRequiredFilledCount();
                const optionalLeft = this.getOptionalUnfilledCount();
                if (remaining > 0) {
                    return (h("span", { class: "remaining-count" }, remaining, " required field", remaining === 1 ? '' : 's', " left"));
                }
                return (h("span", { class: "remaining-count" }, h("span", { class: "check-icon", innerHTML: CheckCircleIcon }), "All required fields complete", optionalLeft > 0 && (h("div", { class: "review-optional" }, h("span", { class: "separator" }, "| "), h("span", { onClick: () => this.handleNextOptional() }, "Review ", optionalLeft, " optional")))));
            })(), !this.finishLater && (h("verdocs-button", { size: "xsmall", label: this.nextButtonLabel === 'Next' ? 'Next Required' : this.nextButtonLabel, disabled: !this.agreed || this.submitting, onClick: () => this.handleNext() })), h("div", { class: { 'icon-button': true, 'minus': true, 'disabled': this.zoomLevel === 'normal', 'magnify': true }, innerHTML: ToolbarMinusIcon, onClick: () => this.handleZoomOut() }), h("div", { class: { 'icon-button': true, 'plus': true, 'disabled': this.zoomLevel === 'zoom2', 'magnify': true }, innerHTML: ToolbarPlusIcon, onClick: () => this.handleZoomIn() }), h("verdocs-dropdown", { options: !this.isDone && !this.finishLater ? inProgressMenuOptions : doneMenuOptions, onOptionSelected: e => this.handleOptionSelected(e) })))), this.toolbarStyle === 'controls' && (h("div", { class: "controls-toolbar" }, h("div", { class: "left-controls" }, h("div", { class: "title" }, this.envelope.name)), h("div", { class: "center-controls" }, h("span", { class: "label" }, "Page"), h("div", { class: "select-wrapper" }, h("verdocs-select-input", { options: pageOptions, value: this.pageNumber.toString(), onInput: e => this.handlePageSelect(e) })), h("span", { class: "count" }, "of ", totalPages)), h("div", { class: "right-controls" }, h("verdocs-button", { class: "mobile-next-button", label: this.nextButtonLabel, size: "xsmall", disabled: !this.agreed || this.submitting, onClick: () => this.handleNext() }), h("div", { class: { 'icon-button': true, 'minus': true, 'disabled': this.zoomLevel === 'normal' }, innerHTML: ToolbarMinusIcon, onClick: () => this.handleZoomOut() }), h("div", { class: { 'icon-button': true, 'plus': true, 'disabled': this.zoomLevel === 'zoom2' }, innerHTML: ToolbarPlusIcon, onClick: () => this.handleZoomIn() }), h("div", { class: "icon-button download", innerHTML: ToolbarDownloadIcon, onClick: () => this.handleOptionSelected({ detail: { id: 'download' } }) }), h("div", { class: "icon-button print", innerHTML: ToolbarPrintIcon, onClick: () => this.handleOptionSelected({ detail: { id: 'print' } }) })))), h("div", { class: `document signed-document-container zoom-${this.zoomLevel}` }, (this.envelope.documents || []).map(envelopeDocument => {
            const pageNumbers = integerSequence(1, envelopeDocument.pages);
            return (h(Fragment, null, this.envelope.documents.length > 1 && (h("div", { class: "document-separator" }, h("div", { innerHTML: DocumentPageIcon }), h("span", null, envelopeDocument.name))), pageNumbers.map(pageNumber => {
                var _a;
                const pageSize = ((_a = envelopeDocument.page_sizes) === null || _a === void 0 ? void 0 : _a[pageNumber]) || { width: 612, height: 792 };
                globalPageCounter++;
                // In signing mode we show the original template page with all the recipient fields so we can show source formatting and
                // where everything went. This is also a visual indicator when optional fields weren't filled in by previous actors, or
                // future signers still need to act. Once we're "done" we flip to showing the envelope's documents which have the final
                // field vales (so far) stamped into them.
                // TODO: Confirm that a pure page-number match is good enough to find the matching template page. We need to make sure
                //  we either don't reset our page numbers for additional attachments, or add match-on identifiers to work around that.
                // console.log('tp', templatePage, page);
                return (h("verdocs-envelope-document-page", { id: `page-${globalPageCounter}`, envelopeId: this.envelopeId, documentId: envelopeDocument.id, endpoint: this.endpoint, virtualWidth: pageSize.width, virtualHeight: pageSize.height, pageNumber: pageNumber, onPageRendered: e => this.handlePageRendered(e), type: "filled", layers: [
                        { name: 'page', type: 'canvas' },
                        { name: 'controls', type: 'div' },
                    ] }));
            })));
        })), this.showFinishLater && (h("verdocs-ok-dialog", { heading: "You've saved your document to finish later.", message: `To complete the ${this.documentsSingularPlural}, use the link in the original email notification inviting you to review and finish the document.`, onNext: () => {
                this.isDone = true;
                this.showFinishLater = false;
            } })), this.showDone && (h("verdocs-ok-dialog", { heading: "You're Done!", message: `You can access the ${this.documentsSingularPlural} at any time by clicking on the link from the invitation email.<br /><br />After all recipients have completed their actions, you will receive an email with the document and envelope certificate attached.`, onNext: () => {
                this.showDone = false;
                this.isDone = true;
            } })), this.adoptingSignature && (h("verdocs-adopt-signature-dialog", { name: formatFullName(this.recipient), nameLocked: !!((_a = this.recipient) === null || _a === void 0 ? void 0 : _a.name_locked), onNext: async (e) => {
                console.log('[SIGN] Adopting signature/initials block', e.detail);
                this.showSpinner = true;
                // These arrive as base-64 encoded data URLs
                const signatureBlob = await (await fetch(e.detail.signature)).blob();
                const initialsBlob = await (await fetch(e.detail.initials)).blob();
                const sigResult = await createSignature(this.endpoint, 'signature', signatureBlob);
                console.log('[SIGN] Created signature', sigResult);
                this.signatureId = sigResult.id;
                const initResult = await createInitials(this.endpoint, 'initial', initialsBlob);
                console.log('[SIGN] Created initials', initResult);
                this.initialId = initResult.id;
                this.showSpinner = false;
                this.adoptingSignature = false;
                this.markEnvelopeStarted();
                // Apply the new signature/initials to the field that triggered the dialog.
                if (this.focusedField) {
                    const fieldObj = this.getRecipientFields().find(f => f.name === this.focusedField);
                    if (fieldObj) {
                        const id = fieldObj.type === 'signature' ? this.signatureId : fieldObj.type === 'initial' ? this.initialId : null;
                        if (id) {
                            const updateResult = await updateEnvelopeField(this.endpoint, this.envelopeId, this.roleId, fieldObj.name, id, false);
                            this.updateRecipientFieldValue(fieldObj.name, updateResult);
                        }
                    }
                    this.focusedField = '';
                }
                // Update any existing field elements in the DOM with the new IDs. This prevents them from
                // needing to show the adoption dialog again if they are clicked.
                const sigFields = this.el.querySelectorAll('verdocs-field-signature');
                sigFields.forEach(el => el.setAttribute('signatureid', this.signatureId));
                const initFields = this.el.querySelectorAll('verdocs-field-initial');
                initFields.forEach(el => el.setAttribute('initialid', this.initialId));
                this.checkRecipientFields();
            }, onExit: () => (this.adoptingSignature = false) })), (this.submitting || this.showSpinner) && (h("verdocs-portal", null, h("div", { class: "spinner-overlay" }, h("verdocs-spinner", null)))), this.showDownloadDialog && (h("verdocs-download-dialog", { signed: this.envelope.signed, polling: this.polling, documents: this.envelope.documents, onExit: () => {
                this.showDownloadDialog = false;
                this.stopPolling();
            }, onDownload: this.handleOnDownload })), !this.loading && !this.isDone && (h("verdocs-sign-footer", { endpoint: this.endpoint, envelopeId: this.envelopeId, isDone: this.isDone, onAskQuestion: (e) => {
                askQuestion(this.endpoint, this.envelopeId, this.roleId, { question: e.detail.question })
                    .then(() => VerdocsToast('Your question has been sent.', { style: 'success' }))
                    .catch(e => {
                    console.log('Error asking question', e);
                    VerdocsToast('Unable to send question, please try again later.', { style: 'error' });
                });
            }, onDecline: () => (this.declining = true), onFinishLater: () => (this.showFinishLater = true) }))));
    }
    get el() { return getElement(this); }
};
VerdocsSign.style = verdocsSignCss();

export { VerdocsSign as verdocs_sign };
//# sourceMappingURL=verdocs-sign.entry.js.map

//# sourceMappingURL=verdocs-sign.entry.js.map