import { p as proxyCustomElement, H, c as createEvent, h, d as Host, F as Fragment } from './p-CUAGH_8P.js';
import { i as interact } from './p-CGNX5HqF.js';
import { VerdocsEndpoint, updateField } from '@verdocs/js-sdk';
import { S as SettingsIcon, P as PencilIcon, E as EraserIcon } from './p-Du758Jse.js';
import { S as Store } from './p-bS8INhRF.js';
import { d as defineCustomElement$9 } from './p-C_yyK5xE.js';
import { d as defineCustomElement$8 } from './p-BvV9rOTP.js';
import { d as defineCustomElement$7 } from './p-CdmWI0-q.js';
import { d as defineCustomElement$6 } from './p-CnPaJH5T.js';
import { d as defineCustomElement$5 } from './p-CNKACBaL.js';
import { d as defineCustomElement$4 } from './p-DUYRis3A.js';
import { d as defineCustomElement$3 } from './p-C1AtapGD.js';
import { d as defineCustomElement$2 } from './p-ClKxADje.js';
import { d as defineCustomElement$1 } from './p-BhfPQRmb.js';

const verdocsFieldInitialCss = "verdocs-field-initial{font-family:var(--verdocs-primary-font, \"Inter\", \"Barlow\", sans-serif);width:83px;height:36px;display:block;font-size:11px;position:relative;letter-spacing:0.3px;scroll-margin:20px 0;-webkit-transform-origin:bottom left;transform-origin:bottom left;border-radius:var(--verdocs-field-radius);background-color:var(--verdocs-field-background, transparent);border:var(--verdocs-field-border, 1px solid rgba(0, 0, 0, 0.2))}verdocs-field-initial label{top:-14px;left:-1px;height:14px;color:var(--verdocs-field-text-color, white);padding:0 4px;font-size:9px;line-height:13px;position:absolute;background:#4a4a99;border-top-left-radius:2px;border-top-right-radius:2px}verdocs-field-initial.done{border:none;opacity:1}verdocs-field-initial .initial-container{width:100%;height:100%;position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}verdocs-field-initial .initial-container img{display:block;max-width:100%;max-height:100%;-o-object-fit:contain;object-fit:contain}verdocs-field-initial .initial-container .overlay{position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(220, 220, 220, 0.85);display:none;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;gap:8px;border-radius:var(--verdocs-field-radius);-webkit-backdrop-filter:blur(1px);backdrop-filter:blur(1px)}verdocs-field-initial .initial-container .overlay .icon-button{background:white;border:1px solid rgba(0, 0, 0, 0.1);cursor:pointer;padding:4px;border-radius:6px;color:#444;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;-webkit-transition:all 0.2s ease;transition:all 0.2s ease;-webkit-box-shadow:0 2px 4px rgba(0, 0, 0, 0.05);box-shadow:0 2px 4px rgba(0, 0, 0, 0.05);width:auto;height:auto}verdocs-field-initial .initial-container .overlay .icon-button:hover{background-color:#fafafa;-webkit-transform:translateY(-1px);transform:translateY(-1px);-webkit-box-shadow:0 4px 6px rgba(0, 0, 0, 0.1);box-shadow:0 4px 6px rgba(0, 0, 0, 0.1);color:#000}verdocs-field-initial .initial-container .overlay .icon-button svg{width:14px;height:14px}verdocs-field-initial .initial-container:hover .overlay{display:-ms-flexbox;display:flex}verdocs-field-initial .initial-container.suppress-overlay:hover .overlay{display:none}verdocs-field-initial.disabled .initial-container{opacity:0.5;pointer-events:none}verdocs-field-initial button{cursor:inherit;-webkit-box-sizing:border-box;box-sizing:border-box;border:none;color:var(--verdocs-field-text-color, rgba(0, 0, 0, 0.87));font-weight:500;-webkit-transform-origin:0 0;transform-origin:0 0;height:100%;width:100%;background:none;font-size:11px}verdocs-field-initial button.hide{display:none}verdocs-field-initial.required{border:1px solid var(--verdocs-required-field-border)}verdocs-field-initial.filled{border:none !important;background-color:transparent !important}verdocs-field-initial verdocs-button-panel{top:-3px;left:-2px;opacity:0.5;z-index:1000;cursor:pointer;position:absolute;-webkit-transform:scale(0.6);transform:scale(0.6)}verdocs-field-initial verdocs-button-panel[data-active],verdocs-field-initial verdocs-button-panel:hover{opacity:1}verdocs-field-initial verdocs-button-panel .icon svg{fill:#333333}verdocs-field-initial verdocs-button-panel .icon:hover svg{fill:#000000}verdocs-field-initial .settings-icon{position:absolute;top:-3px;left:-20px;display:inline-block;cursor:pointer;opacity:0.3}verdocs-field-initial .settings-icon svg{fill:#707ae5}verdocs-field-initial .settings-icon:hover{opacity:1}verdocs-field-initial .edge-top,verdocs-field-initial .edge-right,verdocs-field-initial .edge-left,verdocs-field-initial .edge-bottom{position:absolute;z-index:10}verdocs-field-initial .edge-top{top:-2px;left:0;right:0;height:5px}verdocs-field-initial .edge-right{top:0;bottom:0;right:-2px;width:5px}verdocs-field-initial .edge-left{top:0;left:-2px;bottom:0;width:5px}verdocs-field-initial .edge-bottom{bottom:-2px;left:0;right:0;height:5px}";

const VerdocsFieldInitial = /*@__PURE__*/ proxyCustomElement(class VerdocsFieldInitial extends H {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.adopt = createEvent(this, "adopt");
        this.exit = createEvent(this, "exit");
        this.fieldChange = createEvent(this, "fieldChange");
        this.settingsChanged = createEvent(this, "settingsChanged");
        this.settingsPress = createEvent(this, "settingsPress");
        this.deleted = createEvent(this, "deleted");
        /**
         * Fields may be attached to templates or envelopes, but only template fields may be edited.
         */
        this.source = 'template';
        /**
         * The source template or envelope ID the field is found in.
         */
        this.sourceid = '';
        /**
         * The name of the field to display.
         */
        this.fieldname = '';
        /**
         * Override the field's settings. This is intended to be used during signing when fields are being
         * mutated.
         */
        this.field = null;
        /**
         * If set, overrides the field's settings object. Primarily used to support "preview" modes where all fields are disabled.
         */
        this.disabled = false;
        /**
         * The document or template field to display.
         */
        this.initials = '';
        /**
         * If set, a settings icon will be displayed on hover. The settings shown allow the field's recipient and other settings to be
         * changed, so it should typically only be enabled in the Builder.
         */
        this.editable = false;
        /**
         * If set, the field may be dragged to a new location. This should only be enabled in the Builder, or for self-placed fields.
         */
        this.moveable = false;
        /**
         * If set, the field is considered "done" and is drawn in a display-final-value state.
         */
        this.done = false;
        /**
         * If set, the field will be be scaled horizontally by this factor.
         */
        this.xscale = 1;
        /**
         * If set, the field will be be scaled vertically by this factor.
         */
        this.yscale = 1;
        /**
         * The page the field is on
         */
        this.pagenumber = 1;
        this.showingProperties = false;
        this.focused = false;
        this.suppressOverlay = false;
        this.tempInitials = '';
    }
    async focusField() {
        this.el.focus();
        this.focused = true;
    }
    componentDidRender() {
        interact.dynamicDrop(true);
        if (this.editable) {
            interact(this.el).resizable({
                edges: {
                    top: '.edge-top',
                    left: '.edge-left',
                    bottom: '.edge-bottom',
                    right: '.edge-right',
                },
                modifiers: [
                    interact.modifiers.restrictSize({
                        min: { width: 71, height: 36 },
                    }),
                ],
                listeners: {
                    start: this.handleResizeStart.bind(this),
                    move: this.handleResize.bind(this),
                    end: this.handleResizeEnd.bind(this),
                },
            });
        }
    }
    handleBlur() {
        this.focused = false;
    }
    handleResizeStart(e) {
        e.preventDefault();
        e.stopPropagation();
        e.target.dataset.originalBottom = e.target.style.bottom;
    }
    handleResize(e) {
        let { width, height } = e.rect;
        const dX = e.deltaRect.left;
        const dY = e.deltaRect.bottom;
        const currentLeft = parseFloat(e.target.style.left);
        const currentBottom = parseFloat(e.target.style.bottom);
        width /= this.xscale;
        height /= this.yscale;
        Object.assign(e.target.style, {
            width: `${width}px`,
            height: `${height}px`,
            left: `${currentLeft + dX}px`,
            bottom: `${currentBottom - dY}px`,
        });
    }
    async handleResizeEnd(e) {
        const { sourceid, fieldname } = this;
        const width = Math.round(parseFloat(e.target.style.width));
        let height = Math.round(parseFloat(e.target.style.height));
        if (height < 20) {
            height = 15;
        }
        const newBottom = parseFloat(e.target.style.bottom);
        const originalBottom = parseFloat(e.target.dataset.originalBottom);
        const template = await Store.getTemplate(VerdocsEndpoint.getDefault(), this.sourceid);
        const oldField = template.fields.find(f => f.name === fieldname);
        const y = newBottom !== originalBottom ? newBottom / this.yscale : oldField === null || oldField === void 0 ? void 0 : oldField.y;
        updateField(VerdocsEndpoint.getDefault(), sourceid, fieldname, { width, height, y })
            .then(async (updatedField) => {
            var _a;
            const template = await Store.getTemplate(VerdocsEndpoint.getDefault(), this.sourceid);
            const newTemplate = JSON.parse(JSON.stringify(template));
            const fieldIndex = newTemplate.fields.findIndex(field => field.name === fieldname);
            if (fieldIndex > -1) {
                newTemplate.fields[fieldIndex] = updatedField;
            }
            Store.updateTemplate(this.sourceid, newTemplate);
            (_a = this.settingsChanged) === null || _a === void 0 ? void 0 : _a.emit({ fieldName: fieldname, field: updatedField });
            Object.assign(e.target.dataset, { x: 0, y: 0, h: 0 });
        })
            .catch(e => console.log('Field update failed', e));
    }
    async showSettingsPanel() {
        const settingsPanel = document.getElementById(`verdocs-settings-panel-${this.fieldname}`);
        if (settingsPanel && settingsPanel.showPanel) {
            settingsPanel.showPanel();
        }
    }
    async hideSettingsPanel() {
        const settingsPanel = document.getElementById(`verdocs-settings-panel-${this.fieldname}`);
        if (settingsPanel && settingsPanel.hidePanel) {
            settingsPanel.hidePanel();
        }
    }
    render() {
        const { source, sourceid, fieldname, editable = false, done = false, disabled = false, focused, xscale = 1, yscale = 1 } = this;
        const { index, field } = Store.getField(source, sourceid, fieldname, this.field);
        const { required = false, value = '', label = '', settings = {} } = field || {};
        const signerClass = `signer-${(index % 10) + 1}`;
        const { base64 } = settings;
        if (done) {
            return h(Host, { class: { done } }, value && h("img", { src: value, alt: "Initial" }));
        }
        return (h(Host, { class: { required, disabled, done, focused, filled: !!base64, [signerClass]: true } }, editable && h("div", { class: "edge-right" }), editable && h("div", { class: "edge-left" }), editable && h("div", { class: "edge-top" }), editable && h("div", { class: "edge-bottom" }), label && h("label", null, label), base64 ? (h("div", { class: { 'initial-container': true, 'suppress-overlay': this.suppressOverlay }, onMouseLeave: () => (this.suppressOverlay = false) }, h("img", { src: base64, alt: "Initial" }), h("div", { class: "overlay" }, h("button", { class: "icon-button", innerHTML: PencilIcon, onClick: e => {
                e.stopPropagation();
                if (disabled)
                    return;
                // EDIT action: always open dialog
                console.log('[INITIAL] Editing initials');
                this.adopt.emit();
            } }), h("button", { class: "icon-button", innerHTML: EraserIcon, onClick: e => {
                var _a;
                e.stopPropagation();
                if (disabled)
                    return;
                // CLEAR action
                console.log('[INITIAL] Clearing initials');
                (_a = this.fieldChange) === null || _a === void 0 ? void 0 : _a.emit(null);
            } })))) : (h("button", { onClick: () => {
                var _a;
                if (disabled)
                    return;
                // If we already have an initial ID, use it immediately
                if (this.initialid) {
                    console.log('[INITIAL] Reusing existing initials', this.initialid);
                    this.suppressOverlay = true;
                    (_a = this.fieldChange) === null || _a === void 0 ? void 0 : _a.emit(this.initialid);
                }
                else {
                    this.adopt.emit();
                }
            } }, "Initial")), editable && (h(Fragment, null, h("div", { id: `verdocs-settings-panel-trigger-${fieldname}`, style: { transform: `scale(${Math.floor((1 / xscale) * 1000) / 1000}, ${Math.floor((1 / yscale) * 1000) / 1000})` }, class: "settings-icon", innerHTML: SettingsIcon, onClick: (e) => {
                e.stopPropagation();
                this.showingProperties = !this.showingProperties;
            } }), this.showingProperties && (h("verdocs-portal", { anchor: `verdocs-settings-panel-trigger-${fieldname}`, onClickAway: () => (this.showingProperties = false) }, h("verdocs-template-field-properties", { templateId: sourceid, fieldName: fieldname, onClose: () => (this.showingProperties = false), onDelete: () => {
                var _a;
                (_a = this.deleted) === null || _a === void 0 ? void 0 : _a.emit({ fieldName: field.name });
                return this.hideSettingsPanel();
            }, onSettingsChanged: e => {
                var _a;
                (_a = this.settingsChanged) === null || _a === void 0 ? void 0 : _a.emit(e.detail);
                return this.hideSettingsPanel();
            }, helpText: "initial fields capture the recipient's initials on a clause or page." })))))));
    }
    get el() { return this; }
    static get style() { return verdocsFieldInitialCss; }
}, [256, "verdocs-field-initial", {
        "source": [513],
        "sourceid": [513],
        "fieldname": [513],
        "field": [16],
        "disabled": [516],
        "initials": [513],
        "editable": [516],
        "moveable": [516],
        "done": [516],
        "xscale": [514],
        "yscale": [514],
        "pagenumber": [514],
        "initialid": [513],
        "showingProperties": [32],
        "focused": [32],
        "suppressOverlay": [32],
        "tempInitials": [32],
        "focusField": [64],
        "showSettingsPanel": [64],
        "hideSettingsPanel": [64]
    }, [[0, "blur", "handleBlur"]]]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-field-initial", "verdocs-button", "verdocs-checkbox", "verdocs-component-error", "verdocs-help-icon", "verdocs-loader", "verdocs-portal", "verdocs-select-input", "verdocs-template-field-properties", "verdocs-text-input"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-field-initial":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsFieldInitial);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "verdocs-checkbox":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "verdocs-component-error":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-help-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-portal":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-select-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-template-field-properties":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-text-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { VerdocsFieldInitial as V, defineCustomElement as d };
//# sourceMappingURL=p-1yLYyKxs.js.map

//# sourceMappingURL=p-1yLYyKxs.js.map