'use strict';

var index = require('./index-TwNDE7ev.js');
var tslib_es6 = require('./tslib.es6-DrfCPgT9.js');
var index_esm = require('./index.esm-CKDqUwIC.js');
var aria = require('./aria-BzkqcV7W.js');
var attributes = require('./attributes-Cp0kpySW.js');
var bem = require('./bem-p0PWVN8n.js');
var config_decorator = require('./config.decorator-D_YTqpYj.js');
var date = require('./date-CA-bG6cD.js');
var floatingUi = require('./floating-ui-T_yqQ0TC.js');
var focusVisible = require('./focus-visible-DFZa8IIA.js');
var form = require('./form-BSlIiqcR.js');
var formInput = require('./form-input-DBZuEpuy.js');
var keyboard_helpers = require('./keyboard.helpers-BkZpVT-9.js');
var balDate_i18n = require('./bal-date.i18n-DJlY99as.js');
require('./index-BZ67Dcnb.js');
require('./_commonjsHelpers-BJu3ubxk.js');
require('./index-BobQkZjn.js');
require('./index-C413E-IK.js');
require('./index-ifu9fMyU.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 Date = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.balInput = index.createEvent(this, "balInput");
        this.balChange = index.createEvent(this, "balChange");
        this.balWillAnimate = index.createEvent(this, "balWillAnimate");
        this.balDidAnimate = index.createEvent(this, "balDidAnimate");
        this.balBlur = index.createEvent(this, "balBlur");
        this.balFocus = index.createEvent(this, "balFocus");
        this.balInputClick = index.createEvent(this, "balInputClick");
        this.balIconClick = index.createEvent(this, "balIconClick");
        this.inputId = `bal-da-${dateIds++}`;
        this.inheritedAttributes = {};
        this.isKeyboardMode = false;
        this.hasFocus = false;
        this.isExpanded = false;
        this.language = index.defaultConfig.language;
        this.ariaForm = form.defaultBalAriaForm;
        /**
         * PUBLIC PROPERTY API
         * ------------------------------------------------------
         */
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.inputId;
        /**
         * If `true` the component gets a invalid style.
         */
        this.invalid = false;
        /**
         * If `true` the attribute required is added to the native input.
         */
        this.required = false;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.disabled = false;
        /**
         * If `true` the element can not mutated, meaning the user can not edit the control.
         */
        this.readonly = false;
        /**
         * If `true` there will be no trigger icon visible, so no UX indicator for a picker
         */
        this.freeSolo = false;
        /**
         * If `true` the datepicker only open on click of the icon
         */
        this.triggerIcon = false;
        /**
         * Closes the datepicker popover after selection
         */
        this.closeOnSelect = true;
        /**
         * Indicates whether the value of the control can be automatically completed by the browser.
         */
        this.autocomplete = 'off';
        /**
         * The value of the form field, which accepts ISO 8601 date strings (YYYY-MM-DD).
         */
        this.value = undefined;
        /**
         * Callback to determine which date in the datepicker should be selectable.
         */
        this.allowedDates = undefined;
        /**
         * If `true`, it returns the string `INVALID_VALUE` within the balChange event if the input provided is not valid.
         */
        this.allowInvalidValue = false;
        /**
         * Set the amount of time, in milliseconds, to wait to trigger the `ionChange` event after each keystroke. This also impacts form bindings such as `ngModel` or `v-model`.
         */
        this.debounce = 0;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        /**
         * LIFECYCLE
         * ------------------------------------------------------
         */
        this.hasConnected = false;
        /**
         * PRIVATE METHOD
         * ------------------------------------------------------
         */
        this.handleKeydown = (ev) => {
            this.isKeyboardMode = focusVisible.FOCUS_KEYS.includes(ev.key);
        };
        this.handlePointerDown = () => {
            this.isKeyboardMode = false;
        };
        this.handleOutsideClick = (ev) => {
            if (this.isExpanded) {
                if (!this.el.contains(ev.target)) {
                    this.isExpanded = false;
                    this.hasFocus = false;
                    index.rIC(() => this.balBlur.emit(ev));
                }
            }
        };
        this.handleFocus = (ev) => {
            formInput.stopEventBubbling(ev);
            this.hasFocus = true;
            this.balFocus.emit(ev.detail);
        };
        this.handleBlur = (ev) => {
            formInput.stopEventBubbling(ev);
            if (!this.isExpanded) {
                this.hasFocus = false;
                index.rIC(() => this.balBlur.emit(ev.detail));
            }
        };
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        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) => {
            formInput.stopEventBubbling(ev);
            this.value = ev.detail;
            this.balChange.emit(this.value);
            if (this.closeOnSelect) {
                this.close();
                this.hasFocus = false;
                index.rIC(() => this.balBlur.emit());
            }
        };
        this.onInputInput = (ev) => {
            formInput.stopEventBubbling(ev);
            this.balInput.emit(ev.detail);
            if (ev.detail) {
                const date$1 = date.BalDate.fromAnyFormat(ev.detail);
                if (date$1.isValid) {
                    this.calendarValue = date$1.toISODate();
                }
            }
        };
        this.onInputChange = (ev) => {
            formInput.stopEventBubbling(ev);
            this.value = ev.detail;
            this.balChange.emit(this.value);
        };
        this.onKeyPress = async ({ detail }) => {
            if (detail && detail.key) {
                if (this.isExpanded) {
                    if (detail.key === 'Tab' || index_esm.isEscapeKey(detail) || keyboard_helpers.isSpaceKey(detail)) {
                        await this.close();
                    }
                }
                else {
                    if (keyboard_helpers.isSpaceKey(detail)) {
                        await this.open();
                    }
                }
            }
        };
    }
    createLogger(log) {
        this.log = log;
    }
    valueChanged() {
        this.calendarValue = this.value;
    }
    debounceChanged() {
        this.balChange = index.debounceEvent(this.balChange, this.debounce);
    }
    connectedCallback() {
        if (index.balBrowser.hasDocument) {
            index.addEventListener(document, 'keydown', this.handleKeydown);
            index.addEventListener(document, 'touchstart', this.handlePointerDown);
            index.addEventListener(document, 'mousedown', this.handlePointerDown);
            index.addEventListener(document, 'click', this.handleOutsideClick);
        }
        this.hasConnected = true;
        this.valueChanged();
    }
    disconnectedCallback() {
        if (index.balBrowser.hasDocument) {
            index.removeEventListener(document, 'keydown', this.handleKeydown);
            index.removeEventListener(document, 'touchstart', this.handlePointerDown);
            index.removeEventListener(document, 'mousedown', this.handlePointerDown);
            index.removeEventListener(document, 'click', this.handleOutsideClick);
        }
    }
    componentWillLoad() {
        this.inheritedAttributes = attributes.inheritAttributes(this.el, ['aria-label', 'tabindex', 'title', 'data-hj-allow']);
    }
    /**
     * @internal define config for the component
     */
    async configChanged(state) {
        this.language = state.language;
    }
    /**
     * PUBLIC METHOD
     * ------------------------------------------------------
     */
    /**
     * Opens the accordion
     */
    async open() {
        return this.expand();
    }
    /**
     * Closes the accordion
     */
    async close() {
        return this.collapse();
    }
    /**
     * Triggers the accordion
     */
    async toggle() {
        if (this.isExpanded) {
            return this.collapse();
        }
        else {
            return this.expand();
        }
    }
    /**
     * Selects an option
     */
    async select(dateString) {
        const date$1 = date.BalDate.fromISO(dateString);
        if (date$1.isValid) {
            this.value = date$1.toISODate();
            this.calendarValue = this.value;
        }
    }
    /**
     * Sets focus on the native `input` in `bal-input`. Use this method instead of the global
     * `input.focus()`.
     */
    async setFocus() {
        if (this.inputEl && !this.disabled && !this.readonly) {
            await index.waitAfterIdleCallback();
            this.inputEl.focus();
        }
    }
    /**
     * Sets blur on the native `input` in `bal-input`. Use this method instead of the global
     * `input.blur()`.
     * @internal
     */
    async setBlur() {
        var _a;
        if (this.inputEl && !this.disabled && !this.readonly) {
            await index.waitAfterIdleCallback();
            (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.setBlur();
        }
    }
    /**
     * Returns the native `<input>` element used under the hood.
     */
    async getInputElement() {
        var _a;
        return (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.getInputElement();
    }
    /**
     * @internal
     */
    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) {
            const lib = await floatingUi.balFloatingUi.load();
            this.balWillAnimate.emit();
            this.isExpanded = true;
            this.popupCleanup = lib.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;
    }
    async updatePosition(referenceEl, floatingEl) {
        const lib = await floatingUi.balFloatingUi.load();
        lib
            .computePosition(referenceEl, floatingEl, {
            placement: 'bottom-start',
            middleware: [lib.offset(4), lib.flip({ crossAxis: false })],
        })
            .then(({ x, y }) => {
            Object.assign(floatingEl.style, {
                left: `${x}px`,
                top: `${y}px`,
            });
            this.balDidAnimate.emit();
        });
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = bem.BEM.block('date');
        const blockIcon = block.element('icon');
        const blockPopup = block.element('popup');
        return (index.h(index.Host, { key: 'ab5a0811c70c06da56ad80dda612dc7873cab7a0', id: this.inputId, class: Object.assign({}, block.class()) }, index.h("bal-input-group", { key: '6b56dd808d410d94a9ee6f7e999e26c0ca280b60', invalid: this.invalid, readonly: this.readonly, disabled: this.disabled, ref: el => (this.referenceEl = el) }, index.h("bal-input-date", Object.assign({ key: '37672165bd12ac741e084e74214ac9fab568ed02', 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, allowInvalidValue: this.allowInvalidValue, autocomplete: this.autocomplete, onClick: this.onInputClick, onBalInput: this.onInputInput, onBalChange: this.onInputChange, onBalFocus: ev => this.handleFocus(ev), onBalBlur: ev => this.handleBlur(ev), onBalKeyPress: this.onKeyPress, ref: el => (this.inputEl = el) }, this.inheritedAttributes)), !this.freeSolo ? (index.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": balDate_i18n.i18nBalDate[this.language].toggleDatepicker, "aria-haspopup": "true", "aria-expanded": aria.ariaBooleanToString(this.isExpanded) })) : ('')), index.h("div", { key: 'd72d058ba97876b877a9b7e18ce7ccf89646310d', 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}` }, index.h("bal-date-calendar", { key: 'c4f4f3876ea782d4af605e9f761558ab59864db1', 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 index.getElement(this); }
    static get watchers() { return {
        "value": ["valueChanged"],
        "debounce": ["debounceChanged"]
    }; }
};
tslib_es6.__decorate([
    index.Logger('bal-date'),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Function]),
    tslib_es6.__metadata("design:returntype", void 0)
], Date.prototype, "createLogger", null);
tslib_es6.__decorate([
    config_decorator.ListenToConfig(),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Object]),
    tslib_es6.__metadata("design:returntype", Promise)
], Date.prototype, "configChanged", null);
let dateIds = 0;
Date.style = balDateCss;

exports.bal_date = Date;
