import { p as proxyCustomElement, H, c as createEvent, h, d as Host } from './p-D16h8pzh.js';
import { i as interact } from './p-CGNX5HqF.js';
import { VerdocsEndpoint, getTemplate, updateField, createField, integerSequence } from '@verdocs/js-sdk';
import { g as getFieldId, e as updateCssTransform, f as removeCssTransform, h as setControlStyles, i as defaultHeight, j as defaultWidth } from './p-y2dhcER7.js';
import { V as VerdocsToast } from './p-CyvDgtoV.js';
import { S as SDKError } from './p-C1sRVZWv.js';
import { S as Store } from './p-DmsV595e.js';
import { d as defineCustomElement$q } from './p-BNrp2UP2.js';
import { d as defineCustomElement$p } from './p-wYGYhfrp.js';
import { d as defineCustomElement$o } from './p-DsCKNQPC.js';
import { d as defineCustomElement$n } from './p-CZTe2XIO.js';
import { d as defineCustomElement$m } from './p-CTzrE2_W.js';
import { d as defineCustomElement$l } from './p-MX0H_yx6.js';
import { d as defineCustomElement$k } from './p-CRR4fTl9.js';
import { d as defineCustomElement$j } from './p-Clt27_Qj.js';
import { d as defineCustomElement$i } from './p-CsyhCKk4.js';
import { d as defineCustomElement$h } from './p-xIC5Vhhx.js';
import { d as defineCustomElement$g } from './p-Sk_71M_-.js';
import { d as defineCustomElement$f } from './p-BeSHNILk.js';
import { d as defineCustomElement$e } from './p-D-GZw56Q.js';
import { d as defineCustomElement$d } from './p-DF8La-N2.js';
import { d as defineCustomElement$c } from './p-BGZ_owBm.js';
import { d as defineCustomElement$b } from './p-kCaWRqn0.js';
import { d as defineCustomElement$a } from './p-Bv-L0hsU.js';
import { d as defineCustomElement$9 } from './p-CQ-UXlBO.js';
import { d as defineCustomElement$8 } from './p-Boia1Nbz.js';
import { d as defineCustomElement$7 } from './p-Cy-AXBKH.js';
import { d as defineCustomElement$6 } from './p-DoO2XAMG.js';
import { d as defineCustomElement$5 } from './p-CNvRd0Kp.js';
import { d as defineCustomElement$4 } from './p-vCuIwe1D.js';
import { d as defineCustomElement$3 } from './p-C_SISdpZ.js';
import { d as defineCustomElement$2 } from './p-B0-ZXlBg.js';
import { d as defineCustomElement$1 } from './p-CcglHGeY.js';

const verdocsTemplateFieldsCss = "@-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-template-fields{font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif;position:relative;display:block;min-height:600px}verdocs-template-fields .page-0{padding:65px 15px 0 15px;-webkit-box-sizing:border-box;box-sizing:border-box}verdocs-template-fields .page-0 .user-placed-fields{height:100px;position:relative;background:#ffffff;-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)}verdocs-template-fields .page-0 .user-placed-fields .title{top:0;left:0;color:#ffffff;font-size:12px;padding:3px 6px;font-weight:bold;position:absolute;background:#46497d}verdocs-template-fields .pages{display:-ms-flexbox;display:flex;padding:15px;row-gap:15px;min-height:200px;position:relative;-ms-flex-align:center;align-items:center;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-flex-direction:column;flex-direction:column}verdocs-template-fields .pages div,verdocs-template-fields .pages canvas{-webkit-box-sizing:border-box;box-sizing:border-box}verdocs-template-fields #verdocs-template-fields-toolbar{width:100%;height:50px;display:-ms-flexbox;display:flex;-webkit-column-gap:15px;-moz-column-gap:15px;column-gap:15px;font-weight:700;padding:0 20px 0 0;-ms-flex-align:center;align-items:center;-ms-flex-direction:row;flex-direction:row;color:#f5f5fa;-ms-flex-pack:center;justify-content:center;background:#46497d}verdocs-template-fields #verdocs-template-fields-toolbar>verdocs-select-input{margin:0}verdocs-template-fields #verdocs-template-fields-toolbar svg{width:24px;height:24px}verdocs-template-fields #verdocs-template-fields-toolbar .add-for{margin:0;font-weight:500;color:#f5f5fa}verdocs-template-fields #verdocs-template-fields-toolbar verdocs-select-input{margin:0 20px 0 0}@media all and (max-width: 1000px){verdocs-template-fields #verdocs-template-fields-toolbar{-webkit-column-gap:8px;-moz-column-gap:8px;column-gap:8px;padding:0 10px 0 0}verdocs-template-fields #verdocs-template-fields-toolbar svg{-webkit-transform:scale(0.8);transform:scale(0.8)}verdocs-template-fields #verdocs-template-fields-toolbar .add-for,verdocs-template-fields #verdocs-template-fields-toolbar verdocs-select-input{display:none}}@media all and (max-width: 600px){verdocs-template-fields #verdocs-template-fields-toolbar{-webkit-column-gap:6px;-moz-column-gap:6px;column-gap:6px}verdocs-template-fields #verdocs-template-fields-toolbar svg{-webkit-transform:scale(0.6);transform:scale(0.6)}verdocs-template-fields #verdocs-template-fields-toolbar .separator,verdocs-template-fields #verdocs-template-fields-toolbar .add-for,verdocs-template-fields #verdocs-template-fields-toolbar verdocs-select-input{display:none}}verdocs-template-fields.placing-attachment{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='m10.55 16.55 7.275-7.275L16.05 7.5l-5.5 5.45-2.675-2.65L6.1 12.075Zm-5.375 4.925q-1.125 0-1.887-.763-.763-.762-.763-1.887V5.175q0-1.125.763-1.888.762-.762 1.887-.762h13.65q1.125 0 1.888.762.762.763.762 1.888v13.65q0 1.125-.762 1.887-.763.763-1.888.763Zm0-2.65h13.65V5.175H5.175v13.65Zm0-13.65v13.65-13.65Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-checkbox{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='m10.55 16.55 7.275-7.275L16.05 7.5l-5.5 5.45-2.675-2.65L6.1 12.075Zm-5.375 4.925q-1.125 0-1.887-.763-.763-.762-.763-1.887V5.175q0-1.125.763-1.888.762-.762 1.887-.762h13.65q1.125 0 1.888.762.762.763.762 1.888v13.65q0 1.125-.762 1.887-.763.763-1.888.763Zm0-2.65h13.65V5.175H5.175v13.65Zm0-13.65v13.65-13.65Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-date{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath fill='%23000000' d='M7.6 13.925q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375Zm4.4 0q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375Zm4.4 0q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375ZM5.3 22.85q-1.325 0-2.238-.912-.912-.913-.912-2.238V6.3q0-1.325.912-2.238.913-.912 2.238-.912H6v-2h2.575v2h6.85v-2H18v2h.7q1.325 0 2.238.912.912.913.912 2.238v13.4q0 1.325-.912 2.238-.913.912-2.238.912Zm0-3.15h13.4V10H5.3v9.7ZM5.3 8h13.4V6.3H5.3Zm0 0V6.3 8Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-dropdown{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' stroke-width='1.5' stroke='currentColor'%3E%3Cpath stroke='%23000000' stroke-linecap='round' stroke-linejoin='round' d='M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25' /%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-initial{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='M6.225 20.775V7h-5V3.225H15V7h-5v13.775Zm9.775 0v-8h-3V9h9.775v3.775h-3v8Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-payment{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='m10.55 16.55 7.275-7.275L16.05 7.5l-5.5 5.45-2.675-2.65L6.1 12.075Zm-5.375 4.925q-1.125 0-1.887-.763-.763-.762-.763-1.887V5.175q0-1.125.763-1.888.762-.762 1.887-.762h13.65q1.125 0 1.888.762.762.763.762 1.888v13.65q0 1.125-.762 1.887-.763.763-1.888.763Zm0-2.65h13.65V5.175H5.175v13.65Zm0-13.65v13.65-13.65Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-radio{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='M12 17q2.075 0 3.538-1.463Q17 14.075 17 12t-1.462-3.538Q14.075 7 12 7 9.925 7 8.463 8.462 7 9.925 7 12q0 2.075 1.463 3.537Q9.925 17 12 17Zm0 5.85q-2.275 0-4.25-.85t-3.438-2.312Q2.85 18.225 2 16.25q-.85-1.975-.85-4.25T2 7.75q.85-1.975 2.312-3.438Q5.775 2.85 7.75 2q1.975-.85 4.25-.85t4.25.85q1.975.85 3.438 2.312Q21.15 5.775 22 7.75q.85 1.975.85 4.25T22 16.25q-.85 1.975-2.312 3.438Q18.225 21.15 16.25 22q-1.975.85-4.25.85Zm0-3.15q3.25 0 5.475-2.225Q19.7 15.25 19.7 12q0-3.25-2.225-5.475Q15.25 4.3 12 4.3q-3.25 0-5.475 2.225Q4.3 8.75 4.3 12q0 3.25 2.225 5.475Q8.75 19.7 12 19.7Zm0-7.7Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-signature{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='m9.225 21.225 4.65-4.65h8.45v4.65Zm-5.35-2.2H5.05l8.5-8.5-1.175-1.175-8.5 8.5Zm14.25-9.95L13.8 4.8l1.325-1.325q.625-.65 1.525-.663.9-.012 1.6.663l1.225 1.175q.675.675.663 1.562-.013.888-.663 1.513ZM16.7 10.55 6 21.225H1.675V16.9L12.35 6.225Zm-3.725-.625-.6-.575 1.175 1.175Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-textarea{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath d='M3.225 20.725v-3.15h11.55v3.15Zm0-4.775V12.8h17.55v3.15Zm0-4.75V8.05h17.55v3.15Zm0-4.775v-3.15h17.55v3.15Z'/%3E%3C/svg%3E\") 16 16, pointer}verdocs-template-fields.placing-textbox{cursor:url(\"data:image/svg+xml,%3Csvg width='32' height='15' viewBox='0 0 32 15' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cmask id='path-1-inside-1_1401_24' fill='white'%3E%3Cpath d='M0 0H32V15H0V0Z'/%3E%3C/mask%3E%3Cpath d='M0 0H32V15H0V0Z' fill='%234C56CB' fill-opacity='0.1'/%3E%3Cpath d='M0 0V-1H-1V0H0ZM0 15H-1V16H0V15ZM0 1H32V-1H0V1ZM32 14H0V16H32V14ZM1 15V0H-1V15H1Z' fill='%234C56CB' mask='url(%23path-1-inside-1_1401_24)'/%3E%3Cpath d='M3 11.8V8.65H14.15V11.8H3ZM3 6.65V3.5H20.15V6.65H3Z' fill='%234C56CB'/%3E%3Cline x1='31.5' y1='1' x2='31.5' y2='14' stroke='%234C56CB' stroke-opacity='0.32' stroke-dasharray='1 1'/%3E%3C/svg%3E%0A\") 0 14, pointer}verdocs-template-fields.placing-timestamp{cursor:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24'%3E%3Cpath fill='%23000000' d='M9 1h6v2H9zm10.03 6.39 1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM13 14h-2V8h2v6z'%3E%3C/path%3E%3C/svg%3E\") 16 16, pointer}";

const iconTextbox = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="M3.425 16.15V13h11.15v3.15Zm0-5.15V7.85h17.15V11Z"/></svg>';
const iconCheck = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="m10.55 16.55 7.275-7.275L16.05 7.5l-5.5 5.45-2.675-2.65L6.1 12.075Zm-5.375 4.925q-1.125 0-1.887-.763-.763-.762-.763-1.887V5.175q0-1.125.763-1.888.762-.762 1.887-.762h13.65q1.125 0 1.888.762.762.763.762 1.888v13.65q0 1.125-.762 1.887-.763.763-1.888.763Zm0-2.65h13.65V5.175H5.175v13.65Zm0-13.65v13.65-13.65Z"/></svg>';
const iconRadio = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="M12 17q2.075 0 3.538-1.463Q17 14.075 17 12t-1.462-3.538Q14.075 7 12 7 9.925 7 8.463 8.462 7 9.925 7 12q0 2.075 1.463 3.537Q9.925 17 12 17Zm0 5.85q-2.275 0-4.25-.85t-3.438-2.312Q2.85 18.225 2 16.25q-.85-1.975-.85-4.25T2 7.75q.85-1.975 2.312-3.438Q5.775 2.85 7.75 2q1.975-.85 4.25-.85t4.25.85q1.975.85 3.438 2.312Q21.15 5.775 22 7.75q.85 1.975.85 4.25T22 16.25q-.85 1.975-2.312 3.438Q18.225 21.15 16.25 22q-1.975.85-4.25.85Zm0-3.15q3.25 0 5.475-2.225Q19.7 15.25 19.7 12q0-3.25-2.225-5.475Q15.25 4.3 12 4.3q-3.25 0-5.475 2.225Q4.3 8.75 4.3 12q0 3.25 2.225 5.475Q8.75 19.7 12 19.7Zm0-7.7Z"/></svg>';
const iconDatepicker = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="M7.6 13.925q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375Zm4.4 0q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375Zm4.4 0q-.55 0-.925-.375t-.375-.925q0-.55.375-.937.375-.388.925-.388t.925.388q.375.387.375.937t-.375.925q-.375.375-.925.375ZM5.3 22.85q-1.325 0-2.238-.912-.912-.913-.912-2.238V6.3q0-1.325.912-2.238.913-.912 2.238-.912H6v-2h2.575v2h6.85v-2H18v2h.7q1.325 0 2.238.912.912.913.912 2.238v13.4q0 1.325-.912 2.238-.913.912-2.238.912Zm0-3.15h13.4V10H5.3v9.7ZM5.3 8h13.4V6.3H5.3Zm0 0V6.3 8Z"/></svg>';
const iconSignature = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="m9.225 21.225 4.65-4.65h8.45v4.65Zm-5.35-2.2H5.05l8.5-8.5-1.175-1.175-8.5 8.5Zm14.25-9.95L13.8 4.8l1.325-1.325q.625-.65 1.525-.663.9-.012 1.6.663l1.225 1.175q.675.675.663 1.562-.013.888-.663 1.513ZM16.7 10.55 6 21.225H1.675V16.9L12.35 6.225Zm-3.725-.625-.6-.575 1.175 1.175Z"/></svg>';
const iconInitial = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="M6.225 20.775V7h-5V3.225H15V7h-5v13.775Zm9.775 0v-8h-3V9h9.775v3.775h-3v8Z"/></svg>';
const iconTimestamp = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill="#ffffff" d="M9 1h6v2H9zm10.03 6.39 1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM13 14h-2V8h2v6z"></path></svg>';
const iconDropdown = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" stroke-width="1.5" stroke="currentColor"><path stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" d="M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25" /></svg>';
const iconAttachment = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="m18.375 12.739-7.693 7.693a4.5 4.5 0 0 1-6.364-6.364l10.94-10.94A3 3 0 1 1 19.5 7.372L8.552 18.32m.009-.01-.01.01m5.699-9.941-7.81 7.81a1.5 1.5 0 0 0 2.112 2.13" /></svg>';
const separator = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 14.707 14.707"><g><rect x="6.275" y="0" fill="#ffffff7f" width="1" height="15"/></g></svg>';
const menuOptions = [
    { id: 'signature', tooltip: 'Signature', icon: iconSignature, class: 'signature' },
    { id: 'initial', tooltip: 'Initials', icon: iconInitial, class: 'initial' },
    { id: 'sep1', tooltip: '', icon: separator, class: 'separator' },
    { id: 'textbox', tooltip: 'Text Box', icon: iconTextbox, class: 'textbox' },
    { id: 'checkbox', tooltip: 'Check Box', icon: iconCheck, class: 'checkbox' },
    { id: 'radio', tooltip: 'Radio Button', icon: iconRadio, class: 'radio' },
    { id: 'dropdown', tooltip: 'Dropdown', icon: iconDropdown, class: 'dropdown' },
    { id: 'sep2', tooltip: '', icon: separator, class: 'separator' },
    { id: 'date', tooltip: 'Date', icon: iconDatepicker, class: 'date' },
    { id: 'timestamp', tooltip: 'Timestamp', icon: iconTimestamp, class: 'timestamp' },
    // {id: 'sep3', tooltip: '', icon: separator},
    { id: 'attachment', tooltip: 'Attachment', icon: iconAttachment, class: 'attachment' },
    // {id: 'payment', tooltip: 'Payment', icon: 'P'},
];
const VerdocsTemplateFields = /*@__PURE__*/ proxyCustomElement(class VerdocsTemplateFields extends H {
    constructor() {
        super();
        this.__registerHost();
        this.sdkError = createEvent(this, "sdkError");
        this.templateUpdated = createEvent(this, "templateUpdated");
        this.fieldsUpdated = createEvent(this, "fieldsUpdated");
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The ID of the template to create the document from.
         */
        this.templateId = null;
        /**
         * If set, (recommended), the host application should create a <DIV> element with a unique ID. When this
         * component renders, the toolbar 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.
         *
         * The movement of the toolbar 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 toolbar's visibility must
         * be externally controlled, use CSS display options to hide/show it instead.
         */
        this.toolbarTargetId = null;
        this.placing = null;
        this.showMustSelectRole = false;
        this.selectedRoleName = '';
        this.loading = true;
        this.template = null;
        this.pageHeights = {};
        this.cachedPageInfo = {};
    }
    onTemplateIdChanged() {
        this.listenToTemplate();
    }
    // Stop field-placement mode if ESC is pressed
    handleKeyDown(ev) {
        if (ev.key === 'Escape') {
            this.placing = null;
        }
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[FIELDS] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[FIELDS] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[FIELDS] Error with fields session', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    componentDidRender() {
        interact.dynamicDrop(true);
        const toolbarTarget = this.toolbarTargetId ? document.getElementById(this.toolbarTargetId) : null;
        const toolbarEl = document.getElementById('verdocs-template-fields-toolbar');
        if (toolbarTarget && toolbarEl) {
            console.log('[FIELDS] Moving toolbar');
            toolbarEl.remove();
            toolbarTarget.append(toolbarEl);
        }
    }
    componentWillUpdate() {
        var _a, _b;
        // If a new role was added and there were none yet so far, or the "selected" role was deleted, reset our selection
        const roles = ((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || [];
        if (!this.selectedRoleName || !roles.find(role => role && role.name === this.selectedRoleName)) {
            this.selectedRoleName = ((_b = roles[0]) === null || _b === void 0 ? void 0 : _b.name) || '';
            console.log('[FIELDS] Selected new role', this.selectedRoleName);
        }
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
    }
    async listenToTemplate() {
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            var _a, _b;
            this.template = template;
            this.loading = false;
            if (!this.selectedRoleName) {
                this.selectedRoleName = ((_b = (_a = template.roles) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.name) || '';
            }
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    attachFieldAttributes(pageInfo, field, el) {
        // el.addEventListener('input', e => this.handleFieldChange(field, e));
        el.addEventListener('settingsChanged', () => {
            var _a;
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template: this.template, event: 'added-field' });
        });
        el.addEventListener('deleted', () => {
            var _a;
            el.remove();
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template: this.template, event: 'updated-field' });
        });
        el.setAttribute('templateid', this.templateId);
        el.setAttribute('fieldname', field.name);
        el.setAttribute('pageNumber', String(pageInfo.pageNumber));
        el.setAttribute('xScale', String(pageInfo.xScale));
        el.setAttribute('yScale', String(pageInfo.yScale));
        el.setAttribute('name', field.name);
    }
    handlePageRendered(e) {
        var _a;
        const pageInfo = e.detail;
        // console.log('[FIELDS] Page rendered', pageInfo.pageNumber, pageInfo.xScale, pageInfo.yScale);
        this.cachedPageInfo[pageInfo.pageNumber] = pageInfo;
        this.pageHeights[pageInfo.pageNumber] = pageInfo.naturalHeight;
        (((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || [])
            .filter(field => field && field.page === pageInfo.pageNumber)
            .forEach(field => {
            const id = getFieldId(field);
            const el = document.getElementById(id);
            if (el) {
                el.setAttribute('fieldname', field.name);
                el.setAttribute('pagenumber', String(field.page));
                this.makeDraggable(el);
            }
        });
    }
    makeDraggable(el) {
        interact(el).draggable({
            listeners: {
                move: this.handleMoveField.bind(this),
                end: this.handleMoveEnd.bind(this),
            },
        });
    }
    async handleMoveField(event) {
        const oldX = +(event.target.getAttribute('posX') || 0);
        const oldY = +(event.target.getAttribute('posY') || 0);
        const xScale = +(event.target.getAttribute('xScale') || 1);
        const yScale = +(event.target.getAttribute('yScale') || 1);
        const newX = event.dx / xScale + oldX;
        const newY = event.dy / yScale + oldY;
        event.target.setAttribute('posX', newX);
        event.target.setAttribute('posy', newY);
        updateCssTransform(event.target, 'translate', `${newX}px, ${newY}px`);
    }
    async handleMoveEnd(event) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const name = event.target.getAttribute('fieldname');
        const field = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || []).find(field => field.name === name);
        if (!field) {
            console.log('[FIELDS] Unable to find field', name, event.target);
            return;
        }
        const pageNumber = event.target.getAttribute('pagenumber');
        let { naturalWidth = 612, naturalHeight = 792, renderedHeight = 792 } = this.cachedPageInfo[pageNumber];
        const clientRect = event.target.getBoundingClientRect();
        const parent = event.target.parentElement;
        const parentRect = parent.getBoundingClientRect();
        const width = field.width || defaultWidth(field.type);
        const height = field.height || defaultHeight(field.type);
        // These two being backwards is not a mistake. Left measures "over" from the left
        // (positive displacement) while bottom measures "up" from the bottom (negative displacement).
        const newX = Math.max(clientRect.left - parentRect.left, 0);
        let newY = Math.max(renderedHeight - (parentRect.bottom - clientRect.bottom), 0);
        let newPageNumber = parseInt(pageNumber);
        if (newY > renderedHeight) {
            newPageNumber = Math.min(newPageNumber + 1, ((_d = (_c = (((_b = this.template) === null || _b === void 0 ? void 0 : _b.documents) || [])) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.pages) || 1);
            newY -= renderedHeight;
            renderedHeight = this.cachedPageInfo[newPageNumber].renderedHeight;
            console.log('Next page', { newPageNumber, newY, renderedHeight });
        }
        else if (newY < 0) {
            newPageNumber = Math.max(newPageNumber - 1, 1);
            renderedHeight = this.cachedPageInfo[newPageNumber].renderedHeight;
            newY += renderedHeight;
            console.log('[FIELDS] Next page', { newPageNumber, newY, renderedHeight });
        }
        const { x, y } = this.viewCoordinatesToPageCoordinates(newX, newY, pageNumber, naturalWidth - width, naturalHeight - height);
        try {
            const params = { x, y, page: newPageNumber };
            const updatedField = await updateField(this.endpoint, this.templateId, name, params);
            console.log('[FIELDS] Updated', updatedField);
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            const fieldIndex = newTemplate.fields.findIndex(field => field.name === name);
            if (fieldIndex > -1) {
                newTemplate.fields[fieldIndex] = updatedField;
            }
            Store.updateTemplate(this.templateId, newTemplate);
            event.target.removeAttribute('posX');
            event.target.removeAttribute('posY');
            removeCssTransform(event.target);
            const { xScale = 1, yScale = 1 } = this.cachedPageInfo[pageNumber];
            setControlStyles(event.target, updatedField, xScale, yScale);
            (_e = this.templateUpdated) === null || _e === void 0 ? void 0 : _e.emit({ endpoint: this.endpoint, template: newTemplate, event: 'updated-field' });
        }
        catch (e) {
            VerdocsToast('Error updating field, please try again later', { style: 'error' });
            console.log('[FIELDS] Error updating field', e);
            (_f = this.sdkError) === null || _f === void 0 ? void 0 : _f.emit(new SDKError(e.message, (_g = e.response) === null || _g === void 0 ? void 0 : _g.status, (_h = e.response) === null || _h === void 0 ? void 0 : _h.data));
            event.target.removeAttribute('posX');
            event.target.removeAttribute('posY');
            removeCssTransform(event.target);
        }
    }
    generateFieldName(type, pageNumber) {
        var _a;
        let i = 1;
        let fieldName;
        do {
            fieldName = `${type}P${pageNumber}-${i}`;
            i++;
        } while ((((_a = this.template) === null || _a === void 0 ? void 0 : _a.fields) || []).some(field => field && field.name === fieldName));
        return fieldName;
    }
    // Scale the X,Y clicks to the virtual page dimensions. Also ensure the field doesn't go off the page.
    viewCoordinatesToPageCoordinates(viewX, viewY, pageNumber, xMax, yMax) {
        const { xScale = 1, yScale = 1, renderedHeight = 792 } = this.cachedPageInfo[pageNumber];
        const x = Math.floor(Math.min(viewX / xScale, xMax));
        const y = Math.floor(Math.min(Math.max(renderedHeight - viewY, 0) / yScale, yMax));
        return { x, y };
    }
    async handleClickPage(e, pageNumber) {
        var _a;
        if (this.placing) {
            const clickedX = e.offsetX;
            const clickedY = e.offsetY;
            const width = defaultWidth(this.placing);
            const height = defaultHeight(this.placing);
            const cachedPage = this.cachedPageInfo[pageNumber];
            const { naturalWidth = 612, naturalHeight = 792 } = cachedPage;
            const coords = this.viewCoordinatesToPageCoordinates(clickedX, clickedY, pageNumber, naturalWidth - width, naturalHeight - height);
            const x = Math.floor(coords.x);
            const y = Math.floor(coords.y);
            const field = {
                name: this.generateFieldName(this.placing, pageNumber), //  'textboxP1-22',
                role_name: this.selectedRoleName,
                template_id: this.templateId,
                document_id: cachedPage.documentId,
                type: this.placing,
                required: this.placing !== 'radio',
                page: pageNumber,
                validator: null,
                label: null,
                default: null,
                placeholder: null,
                group: null,
                settings: {},
                x,
                y,
                width,
                height,
                multiline: false,
                readonly: false,
                options: this.placing === 'radio' ? [{ id: 'option-1', label: 'Option 1' }] : [],
            };
            console.log('[FIELDS] Will save new field', field);
            const newField = await createField(this.endpoint, this.templateId, field);
            console.log('[FIELDS] Saved field', newField);
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            newTemplate.fields.push(newField);
            Store.updateTemplate(this.templateId, newTemplate);
            (_a = this.templateUpdated) === null || _a === void 0 ? void 0 : _a.emit({ endpoint: this.endpoint, template: newTemplate, event: 'added-field' });
            this.placing = null;
        }
    }
    render() {
        var _a, _b, _c;
        if (this.loading) {
            return (h(Host, null, h("verdocs-loader", null)));
        }
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        const selectableRoles = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).map(role => ({ value: role.name, label: role.full_name ? `${role.name}: ${role.full_name}` : role.name }));
        return (h(Host, { class: this.placing ? { [`placing-${this.placing}`]: true } : {}, onSubmit: () => { } }, h("div", { id: "verdocs-template-fields-toolbar" }, h("div", { class: "add-for" }, "Add field:"), h("verdocs-select-input", { value: this.selectedRoleName, options: selectableRoles, onInput: (e) => (this.selectedRoleName = e.target.value) }), menuOptions.map(option => (h("verdocs-toolbar-icon", { text: option.tooltip, icon: option.icon, class: option.class, onClick: () => {
                // We ignore empty-tooltip entries because they're separators
                if (option.tooltip) {
                    // We require a role to be selected first
                    if (this.selectedRoleName) {
                        this.placing = option.id;
                    }
                    else {
                        this.showMustSelectRole = true;
                    }
                }
            } })))), h("div", { class: "pages" }, (((_b = this.template) === null || _b === void 0 ? void 0 : _b.documents) || []).map(document => {
            const pageNumbers = integerSequence(1, document.pages);
            return pageNumbers.map(page => {
                const pageSize = document.page_sizes[page];
                return (h("verdocs-template-document-page", { templateId: this.templateId, documentId: document.id, pageNumber: page, virtualWidth: (pageSize === null || pageSize === void 0 ? void 0 : pageSize.width) || 612, virtualHeight: (pageSize === null || pageSize === void 0 ? void 0 : pageSize.height) || 792, disabled: true, editable: true, done: false, onClick: (e) => this.handleClickPage(e, page), onPageRendered: e => this.handlePageRendered(e), layers: [
                        { name: 'page', type: 'canvas' },
                        { name: 'controls', type: 'div' },
                    ] }));
            });
        })), this.showMustSelectRole && (h("verdocs-ok-dialog", { heading: "Unable to add field", message: (((_c = this.template) === null || _c === void 0 ? void 0 : _c.roles) || []).length > 0 ? 'Please select a role before adding fields.' : 'Please add at least one role before adding fields.', onNext: () => (this.showMustSelectRole = false) }))));
    }
    static get watchers() { return {
        "templateId": ["onTemplateIdChanged"]
    }; }
    static get style() { return verdocsTemplateFieldsCss; }
}, [256, "verdocs-template-fields", {
        "endpoint": [16],
        "templateId": [1537, "template-id"],
        "toolbarTargetId": [1, "toolbar-target-id"],
        "placing": [32],
        "showMustSelectRole": [32],
        "selectedRoleName": [32],
        "loading": [32],
        "template": [32]
    }, [[4, "keydown", "handleKeyDown"]], {
        "templateId": ["onTemplateIdChanged"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-template-fields", "verdocs-button", "verdocs-checkbox", "verdocs-component-error", "verdocs-dialog", "verdocs-field-attachment", "verdocs-field-checkbox", "verdocs-field-date", "verdocs-field-dropdown", "verdocs-field-initial", "verdocs-field-radio", "verdocs-field-signature", "verdocs-field-textarea", "verdocs-field-textbox", "verdocs-field-timestamp", "verdocs-help-icon", "verdocs-initial-dialog", "verdocs-loader", "verdocs-ok-dialog", "verdocs-portal", "verdocs-select-input", "verdocs-signature-dialog", "verdocs-template-document-page", "verdocs-template-field-properties", "verdocs-text-input", "verdocs-toolbar-icon", "verdocs-upload-dialog"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-template-fields":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsTemplateFields);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$q();
            }
            break;
        case "verdocs-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$p();
            }
            break;
        case "verdocs-component-error":
            if (!customElements.get(tagName)) {
                defineCustomElement$o();
            }
            break;
        case "verdocs-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$n();
            }
            break;
        case "verdocs-field-attachment":
            if (!customElements.get(tagName)) {
                defineCustomElement$m();
            }
            break;
        case "verdocs-field-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$l();
            }
            break;
        case "verdocs-field-date":
            if (!customElements.get(tagName)) {
                defineCustomElement$k();
            }
            break;
        case "verdocs-field-dropdown":
            if (!customElements.get(tagName)) {
                defineCustomElement$j();
            }
            break;
        case "verdocs-field-initial":
            if (!customElements.get(tagName)) {
                defineCustomElement$i();
            }
            break;
        case "verdocs-field-radio":
            if (!customElements.get(tagName)) {
                defineCustomElement$h();
            }
            break;
        case "verdocs-field-signature":
            if (!customElements.get(tagName)) {
                defineCustomElement$g();
            }
            break;
        case "verdocs-field-textarea":
            if (!customElements.get(tagName)) {
                defineCustomElement$f();
            }
            break;
        case "verdocs-field-textbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$e();
            }
            break;
        case "verdocs-field-timestamp":
            if (!customElements.get(tagName)) {
                defineCustomElement$d();
            }
            break;
        case "verdocs-help-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$c();
            }
            break;
        case "verdocs-initial-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$b();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "verdocs-ok-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "verdocs-portal":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "verdocs-select-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-signature-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-template-document-page":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-template-field-properties":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-text-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-toolbar-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-upload-dialog":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

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

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