import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { i as isSpaceKey } from './index.esm.js';
import { a as autoUpdate, c as computePosition, o as offset, f as flip } from './floating-ui.dom.esm.js';
import { i as i18nBalDate } from './bal-date.i18n.js';
import { B as BEM } from './bem.js';
import { L as Logger } from './log.js';
import { i as inheritAttributes } from './attributes.js';
import { s as stopEventBubbling } from './form-input.js';
import { m as debounceEvent } from './helpers.js';
import { d as defaultBalAriaForm } from './form.js';
import { d as defineCustomElement$6 } from './bal-date-calendar2.js';
import { d as defineCustomElement$5 } from './bal-date-calendar-cell2.js';
import { d as defineCustomElement$4 } from './bal-icon2.js';
import { d as defineCustomElement$3 } from './bal-input-date2.js';
import { d as defineCustomElement$2 } from './bal-input-group2.js';
import { B as BalDate$1 } from './date.js';
import { d as defaultConfig } from './config.default.js';
import { L as ListenToConfig } from './config.decorator.js';

const balDateCss = ":root{--bal-date-popup-z-index:var(--bal-z-index-tooltip);--bal-date-popup-shadow:var(--bal-shadow-normal);--bal-date-popup-radius:var(--bal-radius-normal)}:root{--bal-z-index-tooltip:1300}.bal-date{display:block;font-family:var(--bal-font-family-text);width:100%}.bal-date__icon--clickable{cursor:pointer}.bal-date__popup{display:none;width:-webkit-max-content;width:-moz-max-content;width:max-content;position:absolute;top:0;left:0;z-index:var(--bal-date-popup-z-index);-webkit-box-shadow:var(--bal-date-popup-shadow);box-shadow:var(--bal-date-popup-shadow);border-radius:var(--bal-date-popup-radius)}.bal-date__popup--visible{display:block}";
const BalDateStyle0 = balDateCss;

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
        r = Reflect.decorate(decorators, target, key, desc);
    else
        for (var i = decorators.length - 1; i >= 0; i--)
            if (d = decorators[i])
                r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const Date = proxyCustomElement(class Date extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.balInput = createEvent(this, "balInput", 7);
        this.balChange = createEvent(this, "balChange", 7);
        this.balWillAnimate = createEvent(this, "balWillAnimate", 7);
        this.balDidAnimate = createEvent(this, "balDidAnimate", 7);
        this.balBlur = createEvent(this, "balBlur", 7);
        this.balFocus = createEvent(this, "balFocus", 7);
        this.balInputClick = createEvent(this, "balInputClick", 7);
        this.balIconClick = createEvent(this, "balIconClick", 7);
        this.balPopoverPrepare = createEvent(this, "balPopoverPrepare", 7);
        this.inputId = `bal-da-${dateIds++}`;
        this.inheritedAttributes = {};
        this.onIconClick = async (_ev) => {
            if (this.triggerIcon) {
                await this.toggle();
            }
            else {
                await this.open();
            }
        };
        this.onInputClick = async (_ev) => {
            if (!this.triggerIcon) {
                await this.open();
            }
        };
        this.onCalendarChange = (ev) => {
            stopEventBubbling(ev);
            this.value = ev.detail;
            this.balChange.emit(this.value);
            if (this.closeOnSelect) {
                this.close();
            }
        };
        this.onInputInput = (ev) => {
            stopEventBubbling(ev);
            this.balInput.emit(ev.detail);
            if (ev.detail) {
                const date = BalDate$1.fromAnyFormat(ev.detail);
                if (date.isValid) {
                    this.calendarValue = date.toISODate();
                }
            }
        };
        this.onInputChange = (ev) => {
            stopEventBubbling(ev);
            this.value = ev.detail;
            this.balChange.emit(this.value);
        };
        this.onInputFocus = (ev) => {
            stopEventBubbling(ev);
            this.balFocus.emit(ev.detail);
        };
        this.onInputBlur = (ev) => {
            stopEventBubbling(ev);
            this.balBlur.emit(ev.detail);
        };
        this.onKeyPress = async ({ detail }) => {
            if (isSpaceKey(detail) && !this.triggerIcon) {
                if (this.isExpanded) {
                    await this.close();
                }
                else {
                    await this.open();
                }
            }
        };
        this.isExpanded = false;
        this.language = defaultConfig.language;
        this.calendarValue = undefined;
        this.ariaForm = defaultBalAriaForm;
        this.name = this.inputId;
        this.invalid = false;
        this.required = false;
        this.disabled = false;
        this.readonly = false;
        this.freeSolo = false;
        this.placeholder = undefined;
        this.triggerIcon = false;
        this.closeOnSelect = true;
        this.value = undefined;
        this.min = undefined;
        this.max = undefined;
        this.minYearProp = undefined;
        this.maxYearProp = undefined;
        this.defaultDate = undefined;
        this.allowedDates = undefined;
        this.debounce = 0;
        this.autoInvalidOff = false;
    }
    createLogger(log) {
        this.log = log;
    }
    valueChanged() {
        this.calendarValue = this.value;
    }
    debounceChanged() {
        this.balChange = debounceEvent(this.balChange, this.debounce);
    }
    connectedCallback() {
        this.valueChanged();
    }
    componentWillLoad() {
        this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']);
    }
    async listenToKeydown(ev) {
        if (this.isExpanded && (ev.key === 'Escape' || ev.key === 'Esc')) {
            ev.preventDefault();
            await this.close();
        }
    }
    async listenOnKeyup(ev) {
        if (ev.key === 'Tab' && !this.el.contains(document.activeElement) && this.isExpanded) {
            await this.close();
        }
    }
    async listenOnclick(ev) {
        if (this.isExpanded && !this.el.contains(ev.target)) {
            await this.close();
        }
    }
    async listenOnPopoverPrepare(ev) {
        if (this.inputId !== ev.detail) {
            await this.close();
        }
    }
    async configChanged(state) {
        this.language = state.language;
    }
    async open() {
        return this.expand();
    }
    async close() {
        return this.collapse();
    }
    async toggle() {
        if (this.isExpanded) {
            return this.collapse();
        }
        else {
            return this.expand();
        }
    }
    async select(dateString) {
        const date = BalDate$1.fromISO(dateString);
        if (date.isValid) {
            this.value = date.toISODate();
            this.calendarValue = this.value;
        }
    }
    async setFocus() {
        var _a;
        (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.setFocus();
    }
    async setBlur() {
        var _a;
        (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.setBlur();
    }
    async getInputElement() {
        var _a;
        return (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.getInputElement();
    }
    async setAriaForm(ariaForm) {
        var _a;
        this.ariaForm = Object.assign({}, ariaForm);
        (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.setAriaForm(ariaForm);
    }
    async expand() {
        if (this.referenceEl && this.floatingEl) {
            this.balPopoverPrepare.emit(this.inputId);
            this.balWillAnimate.emit();
            this.isExpanded = true;
            this.popupCleanup = autoUpdate(this.referenceEl, this.floatingEl, () => {
                this.updatePosition(this.referenceEl, this.floatingEl);
            });
        }
        return this.isExpanded;
    }
    async collapse() {
        if (this.floatingEl) {
            this.balWillAnimate.emit();
            this.isExpanded = false;
            if (this.popupCleanup) {
                this.popupCleanup();
            }
            this.balDidAnimate.emit();
        }
        return this.isExpanded;
    }
    updatePosition(referenceEl, floatingEl) {
        computePosition(referenceEl, floatingEl, {
            placement: 'bottom-start',
            middleware: [offset(4), flip({ crossAxis: false })],
        }).then(({ x, y }) => {
            Object.assign(floatingEl.style, {
                left: `${x}px`,
                top: `${y}px`,
            });
            this.balDidAnimate.emit();
        });
    }
    render() {
        const block = BEM.block('date');
        const blockIcon = block.element('icon');
        const blockPopup = block.element('popup');
        return (h(Host, { id: this.inputId, class: Object.assign({}, block.class()) }, h("bal-input-group", { invalid: this.invalid, readonly: this.readonly, disabled: this.disabled, ref: el => (this.referenceEl = el) }, h("bal-input-date", Object.assign({ name: this.name, required: this.required, placeholder: this.placeholder, value: this.value, min: this.min, max: this.max, invalid: this.invalid, readonly: this.readonly, disabled: this.disabled, onClick: this.onInputClick, onBalInput: this.onInputInput, onBalChange: this.onInputChange, onBalFocus: this.onInputFocus, onBalBlur: this.onInputBlur, onBalKeyPress: this.onKeyPress, ref: el => (this.inputEl = el) }, this.inheritedAttributes)), !this.freeSolo ? (h("bal-icon", { name: "date", role: "button", tabindex: -1, class: Object.assign(Object.assign({}, blockIcon.class()), blockIcon.modifier('clickable').class(!this.disabled && !this.readonly)), "is-right": true, color: this.disabled || this.readonly ? 'grey' : this.invalid ? 'danger' : 'primary', onClick: this.onIconClick, "aria-label": i18nBalDate[this.language].toggleDatepicker, "aria-haspopup": "true", "aria-expanded": this.isExpanded ? 'true' : 'false' })) : ('')), h("div", { role: "dialog", class: Object.assign(Object.assign({}, blockPopup.class()), blockPopup.modifier('visible').class(this.isExpanded)), ref: el => (this.floatingEl = el), "aria-hidden": `${this.isExpanded !== true}`, "aria-presented": `${this.isExpanded === true}` }, h("bal-date-calendar", { value: this.calendarValue, min: this.min, max: this.max, minYearProp: this.minYearProp, maxYearProp: this.maxYearProp, defaultDate: this.defaultDate, allowedDates: this.allowedDates, onBalChange: this.onCalendarChange }))));
    }
    get el() { return this; }
    static get watchers() { return {
        "value": ["valueChanged"],
        "debounce": ["debounceChanged"]
    }; }
    static get style() { return BalDateStyle0; }
}, [0, "bal-date", {
        "name": [1],
        "invalid": [4],
        "required": [4],
        "disabled": [4],
        "readonly": [4],
        "freeSolo": [4, "free-solo"],
        "placeholder": [1],
        "triggerIcon": [4, "trigger-icon"],
        "closeOnSelect": [4, "close-on-select"],
        "value": [1025],
        "min": [1025],
        "max": [1025],
        "minYearProp": [2, "min-year"],
        "maxYearProp": [2, "max-year"],
        "defaultDate": [1, "default-date"],
        "allowedDates": [16],
        "debounce": [2],
        "autoInvalidOff": [516, "auto-invalid-off"],
        "isExpanded": [32],
        "language": [32],
        "calendarValue": [32],
        "ariaForm": [32],
        "configChanged": [64],
        "open": [64],
        "close": [64],
        "toggle": [64],
        "select": [64],
        "setFocus": [64],
        "setBlur": [64],
        "getInputElement": [64],
        "setAriaForm": [64]
    }, [[8, "keydown", "listenToKeydown"], [8, "keyup", "listenOnKeyup"], [4, "click", "listenOnclick"], [16, "balPopoverPrepare", "listenOnPopoverPrepare"]], {
        "value": ["valueChanged"],
        "debounce": ["debounceChanged"]
    }]);
__decorate([
    Logger('bal-date')
], Date.prototype, "createLogger", null);
__decorate([
    ListenToConfig()
], Date.prototype, "configChanged", null);
let dateIds = 0;
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["bal-date", "bal-date-calendar", "bal-date-calendar-cell", "bal-icon", "bal-input-date", "bal-input-group"];
    components.forEach(tagName => { switch (tagName) {
        case "bal-date":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, Date);
            }
            break;
        case "bal-date-calendar":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "bal-date-calendar-cell":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "bal-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "bal-input-date":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "bal-input-group":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}

const BalDate = Date;
const defineCustomElement = defineCustomElement$1;

export { BalDate, defineCustomElement };
