import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { _ as __decorate, a as __metadata } from './tslib.es6.js';
import { B as BEM } from './bem.js';
import { b as balBrowser } from './browser.js';
import { b as balDevice } from './device.js';
import { b as balFloatingUi } from './floating-ui.js';
import { L as Logger } from './log.js';
import { d as defineCustomElement$2 } from './bal-stack2.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 = /*@__PURE__*/ proxyCustomElement(class Tooltip extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.balWillAnimate = createEvent(this, "balWillAnimate", 7);
        this.balDidAnimate = createEvent(this, "balDidAnimate", 7);
        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 (!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 && 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 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 (balBrowser.hasWindow) {
                isInFrame = !!window.frameElement;
            }
            const lib = await 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.block('tooltip');
        const containerBlock = block.element('container');
        const arrowBlock = block.element('arrow');
        const innerBlock = block.element('inner');
        const innerContentBlock = innerBlock.element('content');
        return (h(Host, { key: '44b979f559f36ccc63896081b14dab984057af90', class: Object.assign({}, block.class()), role: "dialog", "aria-hidden": `${this.presented !== true}`, "aria-modal": `${this.presented === true}`, "aria-presented": `${this.presented === true}` }, h("div", { key: '4e96b8f99b20385490151f810f4b336af692f968', class: Object.assign({}, containerBlock.class()), ref: containerEl => (this.containerEl = containerEl) }, h("div", { key: 'f1f7e3f48c22e5c5187ae1c60e5fad5e95077397', class: Object.assign({}, arrowBlock.class()), ref: arrowEl => (this.arrowEl = arrowEl) }), h("bal-stack", { key: '69727e19f5dc28bb04e7e5354ea7824b748c3fe9', layout: "vertical", class: Object.assign({}, innerBlock.class()) }, h("div", { key: 'e9ee7d561604fd046b102ef895f98c385f66cb69', class: Object.assign({}, innerContentBlock.class()), ref: contentEl => (this.contentEl = contentEl), "data-testid": "bal-tooltip-content" }, h("slot", { key: '4a317667331f69961a438d74d9eb07816c444153' }))))));
    }
    get el() { return this; }
    static get watchers() { return {
        "contentWidth": ["contentWidthChanged"]
    }; }
    static get style() { return balTooltipCss; }
}, [257, "bal-tooltip", {
        "reference": [1],
        "placement": [1],
        "offset": [2],
        "demo": [4],
        "contentWidth": [2, "content-width"],
        "presented": [32],
        "present": [64],
        "dismiss": [64],
        "update": [64]
    }, undefined, {
        "contentWidth": ["contentWidthChanged"]
    }]);
__decorate([
    Logger('bal-tooltip'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], Tooltip.prototype, "createLogger", null);
let tooltipIds = 0;
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["bal-tooltip", "bal-stack"];
    components.forEach(tagName => { switch (tagName) {
        case "bal-tooltip":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, Tooltip);
            }
            break;
        case "bal-stack":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}

const BalTooltip = Tooltip;
const defineCustomElement = defineCustomElement$1;

export { BalTooltip, defineCustomElement };
