import { __decorate } from "tslib";
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-lite-tooltip.css';
import NileElement from '../internal/nile-element';
import tippy, { followCursor, roundArrow, createSingleton, } from 'tippy.js';
import { parseFollowCursor, parseDuration, } from './utils';
import { VisibilityManager } from '../utilities/visibility-manager.js';
/**
 * Nile lite-tooltip component.
 *
 * Supports wrapper, sibling (for), and singleton modes.
 * Aligns with Tippy.js props and Nile design system.
 *
 * @tag nile-lite-tooltip
 */
let NileliteTooltip = class NileliteTooltip extends NileElement {
    static get styles() {
        return [styles];
    }
    createRenderRoot() {
        return this; // lite DOM
    }
    constructor() {
        super();
        // ───────────── Props ─────────────
        /** ID of the target element (for sibling mode) */
        this.for = null;
        /** Tooltip content text or HTML */
        this.content = '';
        /** Tooltip size (applies CSS class) */
        this.size = 'small';
        /** Animation duration for show/hide (ms). Can be a single value or [show, hide]. */
        this.duration = 200;
        /** Interactive mode */
        this.interactive = false;
        /** Placement of the tooltip */
        this.placement = 'top';
        this.disabled = false;
        this.distance = 8;
        this.skidding = 0;
        this.open = false;
        this.trigger = 'mouseenter focus';
        this.allowHTML = false;
        this.followCursor = false;
        this.arrow = 'default';
        this.singleton = false;
        this.enableRecursiveMode = false;
        /** Not added in Doc */
        this.delay = 0;
        this.maxWidth = 'auto';
        this.zIndex = 9999;
        this.hideOnClick = true;
        this.inertia = false;
        this.interactiveBorder = 2;
        this.enableVisibilityEffect = false;
        this.enableTabClose = false;
    }
    firstUpdated() {
        this.attachTooltip();
        const targetEl = (this.for && document.getElementById(this.for)) ||
            this.firstElementChild;
        this.visibilityManager = new VisibilityManager({
            host: this,
            target: targetEl,
            enableVisibilityEffect: this.enableVisibilityEffect,
            enableTabClose: this.enableTabClose,
            isOpen: () => this.open,
            onAnchorOutOfView: () => {
                this.open = false;
                this.hideAllTooltips();
                this.emit('nile-visibility-change', {
                    visible: false,
                    reason: 'anchor-out-of-view',
                });
            },
            onDocumentHidden: () => {
                this.open = false;
                this.hideAllTooltips();
                this.emit('nile-visibility-change', {
                    visible: false,
                    reason: 'document-hidden',
                });
            },
            emit: (event, detail) => this.emit(`nile-${event}`, detail),
        });
    }
    refresh() {
        this.attachTooltip();
    }
    hasValidContent() {
        const content = this.content ??
            this.getAttribute('data-tippy-content') ??
            '';
        return typeof content === 'string' && content.trim().length > 0;
    }
    attachTooltip() {
        this.destroyTooltips();
        if (this.disabled || (!this.enableRecursiveMode && !this.singleton && !this.hasValidContent())) {
            return;
        }
        const options = {
            content: this.content || this.getAttribute('data-tippy-content') || undefined,
            placement: this.placement,
            trigger: this.trigger,
            offset: [this.skidding, this.distance],
            theme: 'lite',
            animation: 'fade',
            interactive: this.interactive,
            arrow: roundArrow,
            duration: parseDuration(this.duration),
            allowHTML: this.allowHTML,
            delay: this.delay,
            maxWidth: this.maxWidth,
            zIndex: this.zIndex,
            hideOnClick: false,
            inertia: this.inertia,
            interactiveBorder: this.interactiveBorder,
            appendTo: document.body,
            followCursor: parseFollowCursor(this.followCursor),
            plugins: parseFollowCursor(this.followCursor) ? [followCursor] : [],
            onShow: instance => {
                this.open = true;
                const content = instance.popper.querySelector('.tippy-content');
                if (content) {
                    if (this.width)
                        content.style.width = this.width;
                    if (this.height) {
                        content.style.height = this.height;
                        content.style.overflow = 'auto';
                    }
                }
                this.dispatchEvent(new CustomEvent('nile-show', {
                    detail: { instance, target: instance.reference },
                }));
                this.dispatchEvent(new CustomEvent('nile-toggle', {
                    detail: { open: true, instance, target: instance.reference },
                }));
                return undefined;
            },
            onHide: instance => {
                this.open = false;
                this.dispatchEvent(new CustomEvent('nile-hide', {
                    detail: { instance, target: instance.reference },
                }));
                this.dispatchEvent(new CustomEvent('nile-toggle', {
                    detail: { open: false, instance, target: instance.reference },
                }));
                return undefined;
            },
        };
        if (this.for) {
            if (this.singleton && !this.for.startsWith('#') && !document.getElementById(this.for)) {
                const targetEls = Array.from(document.querySelectorAll(`.${this.for}`));
                if (targetEls.length > 0) {
                    this.tooltipInstances = targetEls.map(el => {
                        const instance = tippy(el, {
                            ...options,
                            content: el.getAttribute('content') || this.content,
                        });
                        instance.popper.querySelector('.tippy-box')?.classList.add(this.size);
                        return instance;
                    });
                    this.singletonInstance = createSingleton(this.tooltipInstances, {
                        delay: [75, 0],
                        arrow: roundArrow,
                        moveTransition: 'transform 0.15s ease-out',
                    });
                    if (this.open)
                        queueMicrotask(() => this.singletonInstance?.show());
                    return;
                }
            }
            const containerEl = document.getElementById(this.for);
            if (this.singleton && containerEl) {
                const childEls = Array.from(containerEl.querySelectorAll('[content]'));
                if (childEls.length > 0) {
                    this.tooltipInstances = childEls.map(el => {
                        const instance = tippy(el, {
                            ...options,
                            content: el.getAttribute('content') || this.content,
                        });
                        instance.popper.querySelector('.tippy-box')?.classList.add(this.size);
                        return instance;
                    });
                    this.singletonInstance = createSingleton(this.tooltipInstances, {
                        delay: [75, 0],
                        arrow: roundArrow,
                        moveTransition: 'transform 0.15s ease-out',
                    });
                    if (this.open)
                        queueMicrotask(() => this.singletonInstance?.show());
                    return;
                }
            }
            this.targetEl = document.getElementById(this.for);
            if (!this.targetEl)
                return;
            if (!this.id) {
                this.generatedId = `nile-tooltip-${Math.random()
                    .toString(36)
                    .slice(2, 9)}`;
                this.id = this.generatedId;
            }
            this.prevDescribedby = this.targetEl.getAttribute('aria-describedby');
            const describedby = this.prevDescribedby
                ? `${this.prevDescribedby} ${this.id}`
                : this.id;
            this.targetEl.setAttribute('aria-describedby', describedby);
            this.singleInstance = tippy(this.targetEl, options);
            if (this.size)
                this.singleInstance.popper
                    .querySelector('.tippy-box')
                    ?.classList.add(this.size);
            if (this.open) {
                queueMicrotask(() => this.singleInstance?.show());
            }
            return;
        }
        if (this.enableRecursiveMode) {
            const children = Array.from(this.querySelectorAll('[content]')).filter(el => {
                const value = el.getAttribute('content');
                return value !== null && value.trim().length > 0;
            });
            if (children.length > 0) {
                this.tooltipInstances = children.map(child => {
                    const el = child;
                    const localContent = el.getAttribute('content') || this.content;
                    const instance = tippy(el, { ...options, content: localContent });
                    instance.popper.querySelector('.tippy-box')?.classList.add(this.size);
                    return instance;
                });
                if (this.singleton && this.tooltipInstances.length > 1) {
                    this.singletonInstance = createSingleton(this.tooltipInstances, {
                        delay: [75, 0],
                        arrow: roundArrow,
                        moveTransition: 'transform 0.15s ease-out',
                    });
                }
                if (this.open) {
                    if (this.singletonInstance)
                        this.singletonInstance.show();
                    else
                        this.tooltipInstances.forEach(t => t.show());
                }
            }
        }
        else {
            const firstChild = this.firstElementChild;
            if (firstChild) {
                const localContent = firstChild.getAttribute('content') || this.content;
                const instance = tippy(firstChild, { ...options, content: localContent });
                instance.popper.querySelector('.tippy-box')?.classList.add(this.size);
                this.tooltipInstances = [instance];
                if (this.open) {
                    instance.show();
                }
            }
        }
    }
    destroyTooltips() {
        this.tooltipInstances?.forEach(t => t.destroy());
        this.singleInstance?.destroy();
        this.singletonInstance?.destroy();
        this.tooltipInstances = undefined;
        this.singleInstance = undefined;
        this.singletonInstance = undefined;
        if (this.targetEl && this.id) {
            const current = this.targetEl
                .getAttribute('aria-describedby')
                ?.split(' ')
                .filter(id => id !== this.id)
                .join(' ')
                .trim();
            if (current) {
                this.targetEl.setAttribute('aria-describedby', current);
            }
            else {
                this.targetEl.removeAttribute('aria-describedby');
            }
        }
    }
    hideAllTooltips() {
        this.singleInstance?.hide();
        this.singletonInstance?.hide();
        this.tooltipInstances?.forEach(t => t.hide());
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.visibilityManager?.cleanup();
        this.destroyTooltips();
    }
    updated(changed) {
        super.updated(changed);
        if ([
            'for',
            'content',
            'placement',
            'distance',
            'skidding',
            'trigger',
            'disabled',
            'hoist',
            'size',
            'arrow',
            'singleton',
        ].some(p => changed.has(p))) {
            this.attachTooltip();
        }
        if (changed.has('open')) {
            if (this.open) {
                this.visibilityManager?.setup();
                this.singleInstance?.show();
                this.singletonInstance?.show();
                this.tooltipInstances?.forEach(t => t.show());
            }
            else {
                this.visibilityManager?.cleanup();
                this.singleInstance?.hide();
                this.singletonInstance?.hide();
                this.tooltipInstances?.forEach(t => t.hide());
            }
        }
    }
};
__decorate([
    property({ type: String, attribute: 'for' })
], NileliteTooltip.prototype, "for", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "content", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "size", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "duration", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "interactive", void 0);
__decorate([
    property({ type: String })
], NileliteTooltip.prototype, "placement", void 0);
__decorate([
    property({ type: Boolean })
], NileliteTooltip.prototype, "disabled", void 0);
__decorate([
    property({ type: Number })
], NileliteTooltip.prototype, "distance", void 0);
__decorate([
    property({ type: Number })
], NileliteTooltip.prototype, "skidding", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "open", void 0);
__decorate([
    property({ type: String })
], NileliteTooltip.prototype, "trigger", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "allowHTML", void 0);
__decorate([
    property({ type: String, reflect: true, attribute: true })
], NileliteTooltip.prototype, "followCursor", void 0);
__decorate([
    property({ type: String, reflect: true, attribute: true })
], NileliteTooltip.prototype, "arrow", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "singleton", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "enableRecursiveMode", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "delay", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "maxWidth", void 0);
__decorate([
    property({ type: Number })
], NileliteTooltip.prototype, "zIndex", void 0);
__decorate([
    property({ type: [Boolean, String], reflect: true })
], NileliteTooltip.prototype, "hideOnClick", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "inertia", void 0);
__decorate([
    property({ type: Number })
], NileliteTooltip.prototype, "interactiveBorder", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "enableVisibilityEffect", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileliteTooltip.prototype, "enableTabClose", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "width", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileliteTooltip.prototype, "height", void 0);
NileliteTooltip = __decorate([
    customElement('nile-lite-tooltip')
], NileliteTooltip);
export { NileliteTooltip };
export default NileliteTooltip;
//# sourceMappingURL=nile-lite-tooltip.js.map