'use strict';

var index = require('./index-TwNDE7ev.js');
var tslib_es6 = require('./tslib.es6-DrfCPgT9.js');
var bem = require('./bem-p0PWVN8n.js');
var device = require('./device-CrnZOym8.js');
var floatingUi = require('./floating-ui-T_yqQ0TC.js');

const showContainerElement = (containerEl) => {
    if (containerEl) {
        showElement(containerEl);
    }
};
const hideContainerElement = (containerEl) => {
    if (containerEl) {
        hideElement(containerEl);
    }
};
const showArrowElement = (arrowEl) => {
    if (arrowEl) {
        showElement(arrowEl);
    }
};
const hideArrowElement = (arrowEl) => {
    if (arrowEl) {
        Object.assign(arrowEl.style, {
            left: '',
            top: '',
            display: 'none',
            visibility: 'hidden',
        });
    }
};
const showElement = (element) => {
    if (element) {
        element.style.setProperty('display', 'block');
        element.style.setProperty('visibility', 'visible');
    }
};
const hideElement = (element) => {
    if (element) {
        element.style.removeProperty('display');
        element.style.removeProperty('visibility');
    }
};

const balTooltipCss = ":host{--bal-tooltip-container-background:var(--bal-color-primary-6);--bal-tooltip-max-width:auto;--bal-tooltip-radius:var(--bal-radius-normal);--bal-tooltip-shadow:var(--bal-shadow-normal);--bal-tooltip-arrow-background:var(--bal-color-primary-6);--bal-tooltip-font-family:var(--bal-font-family-text);--bal-tooltip-font-size:var(--bal-text-size-small)}:host{position:static;display:inline;z-index:var(--bal-z-index-tooltip)}.bal-tooltip__container{background-color:var(--bal-tooltip-container-background);display:none;visibility:hidden;color:#fff;padding:var(--bal-space-x-small);border-radius:var(--bal-tooltip-radius);-webkit-box-shadow:var(--bal-tooltip-shadow);box-shadow:var(--bal-tooltip-shadow);width:var(--bal-tooltip-max-width);position:absolute;top:0;left:0}.bal-tooltip__inner{overflow-y:auto;max-height:calc(var(--bal-app-height, 100%) - 8rem)}.bal-tooltip__inner__content{width:100%;font-family:var(--bal-tooltip-font-family);font-size:var(--bal-tooltip-font-size)}.bal-tooltip__arrow{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;position:absolute;width:.5rem;height:.5rem;background:var(--bal-tooltip-arrow-background);-webkit-transform:rotate(45deg);transform:rotate(45deg);display:none;visibility:hidden}.bal-tooltip-variant-popover-trigger,.bal-tooltip-permanent-trigger{z-index:calc(var(--bal-z-index-tooltip) + 1) !important;position:relative !important}";

const Tooltip = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.balWillAnimate = index.createEvent(this, "balWillAnimate");
        this.balDidAnimate = index.createEvent(this, "balDidAnimate");
        this.tooltipId = `bal-to-${tooltipIds++}`;
        /**
         * PUBLIC PROPERTY API
         * ------------------------------------------------------
         */
        /**
         * Id of the reference element default is the trigger element.
         */
        this.reference = '';
        /**
         * If set it turns a tooltip into a fullscreen or a drawer on touch devices
         */
        this.placement = 'bottom';
        /**
         * Offset form trigger to tooltip.
         */
        this.offset = 0;
        /**
         * @internal
         */
        this.demo = false;
        /**
         * Internal active state
         */
        this.presented = false;
    }
    createLogger(log) {
        this.log = log;
    }
    contentWidthChanged(newValue, oldValue) {
        if (newValue !== oldValue) {
            if (newValue === undefined) {
                this.el.style.removeProperty('--bal-tooltip-max-width');
            }
            else {
                this.el.style.setProperty('--bal-tooltip-max-width', `${this.contentWidth}px`);
            }
        }
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    // componentDidRender() {
    //   if (this.demo) {
    //     this.present()
    //   }
    // }
    componentDidLoad() {
        this.contentWidthChanged(this.contentWidth, 0);
        if (!device.balDevice.hasTouchScreen) {
            let showEvents = [];
            let hideEvents = [];
            showEvents = ['mouseenter', 'focus'];
            hideEvents = ['mouseleave', 'blur'];
            showEvents.forEach(event => {
                if (this.triggerElement) {
                    this.triggerElement.addEventListener(event, () => this.present());
                }
            });
            hideEvents.forEach(event => {
                if (this.triggerElement) {
                    this.triggerElement.addEventListener(event, () => this.dismiss());
                }
            });
        }
        if (this.demo) {
            this.present();
        }
    }
    /**
     * INTERNAL METHODS
     * ------------------------------------------------------
     */
    /**
     * @internal
     */
    async present() {
        //
        // identify trigger element or the the closest trigger available
        if (!this.trigger && index.balBrowser.hasDocument) {
            const firstTrigger = Array.from(document.querySelectorAll(`[id="${this.reference}"]`))[0];
            this.trigger = firstTrigger;
        }
        if (this.trigger && this.containerEl && this.arrowEl) {
            this.balWillAnimate.emit();
            //
            // get placement type of the trigger
            const triggerVariantAttr = this.trigger.attributes.getNamedItem('bal-tooltip-placement');
            if (triggerVariantAttr) {
                this.placement = triggerVariantAttr.value;
            }
            else {
                this.placement = this.placement;
            }
            //
            // show all required elements
            showContainerElement(this.containerEl);
            showArrowElement(this.arrowEl);
            this.trigger.classList.add('bal-tooltip-trigger');
            this.presented = true;
            const lib = await floatingUi.balFloatingUi.load();
            this.cleanup = lib.autoUpdate(this.trigger, this.containerEl, () => {
                this.update();
            }, {
                ancestorScroll: true,
                ancestorResize: true,
                elementResize: false,
                layoutShift: true,
                animationFrame: true,
            });
            this.balDidAnimate.emit();
            return true;
        }
        return false;
    }
    /**
     * @internal
     */
    async dismiss() {
        if (this.containerEl && this.arrowEl && this.trigger) {
            this.balWillAnimate.emit();
            if (this.cleanup) {
                this.cleanup();
            }
            this.trigger.classList.remove('bal-tooltip-trigger');
            hideContainerElement(this.containerEl);
            hideArrowElement(this.arrowEl);
            this.presented = false;
            this.balDidAnimate.emit();
            return true;
        }
        return false;
    }
    /**
     * @internal
     */
    async update() {
        if (this.trigger && this.containerEl && this.arrowEl) {
            this.balWillAnimate.emit();
            let isInFrame = false;
            if (index.balBrowser.hasWindow) {
                isInFrame = !!window.frameElement;
            }
            const lib = await floatingUi.balFloatingUi.load();
            lib
                .computePosition(this.trigger, this.containerEl, {
                placement: this.placement,
                middleware: [
                    isInFrame ? undefined : lib.shift(),
                    lib.flip(),
                    lib.offset(8),
                    lib.arrow({
                        element: this.arrowEl,
                        padding: 4,
                    }),
                ],
            })
                .then(({ x, y, middlewareData, placement }) => {
                const side = placement.split('-')[0];
                const staticSide = {
                    top: 'bottom',
                    right: 'left',
                    bottom: 'top',
                    left: 'right',
                }[side];
                if (this.containerEl) {
                    Object.assign(this.containerEl.style, {
                        left: `${x}px`,
                        top: `${y}px`,
                    });
                }
                if (middlewareData.arrow && this.arrowEl) {
                    const arrowPosition = middlewareData.arrow;
                    Object.assign(this.arrowEl.style, {
                        left: x != null && arrowPosition.x != null ? `${arrowPosition.x}px` : '',
                        top: y != null && arrowPosition.y != null ? `${arrowPosition.y}px` : '',
                        right: '',
                        bottom: '',
                        [staticSide]: `${ -4}px`,
                    });
                }
            });
            this.balDidAnimate.emit();
            return true;
        }
        return false;
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    get triggerElement() {
        return document.querySelector(`[id="${this.reference}"]`);
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = bem.BEM.block('tooltip');
        const containerBlock = block.element('container');
        const arrowBlock = block.element('arrow');
        const innerBlock = block.element('inner');
        const innerContentBlock = innerBlock.element('content');
        return (index.h(index.Host, { key: '8a590dae8eddc3aba2700a72f040af70ac4dd3e6', class: Object.assign({}, block.class()), role: "dialog", "aria-hidden": `${this.presented !== true}`, "aria-modal": `${this.presented === true}`, "aria-presented": `${this.presented === true}` }, index.h("div", { key: 'c27651c603f1dda66783bbf9fc57f9b84f29465e', class: Object.assign({}, containerBlock.class()), ref: containerEl => (this.containerEl = containerEl) }, index.h("div", { key: '9e8bb710979992265e4b3938b03500f332fd76f8', class: Object.assign({}, arrowBlock.class()), ref: arrowEl => (this.arrowEl = arrowEl) }), index.h("bal-stack", { key: '8986da10e482c79939711244189613b601bbac60', layout: "vertical", class: Object.assign({}, innerBlock.class()) }, index.h("div", { key: '0f7ff54deee83d4dc00d95655b0f3d0e0a5ce4ed', class: Object.assign({}, innerContentBlock.class()), ref: contentEl => (this.contentEl = contentEl), "data-test": "bal-tooltip-content" }, index.h("slot", { key: '6abe4c290c6974b1b6b075f7ddee9834949cdba8' }))))));
    }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "contentWidth": ["contentWidthChanged"]
    }; }
};
tslib_es6.__decorate([
    index.Logger('bal-tooltip'),
    tslib_es6.__metadata("design:type", Function),
    tslib_es6.__metadata("design:paramtypes", [Function]),
    tslib_es6.__metadata("design:returntype", void 0)
], Tooltip.prototype, "createLogger", null);
let tooltipIds = 0;
Tooltip.style = balTooltipCss;

exports.bal_tooltip = Tooltip;
