'use strict';

var index = require('./index-BUvWX8u2.js');
var floatingUi_dom = require('./floating-ui.dom-BZk7Blsu.js');

const pdsTooltipCss = ".pds-tooltip{--tooltip-border-width-arrow-down:var(--tooltip-sizing-arrow) var(--tooltip-sizing-arrow) 0;--tooltip-border-width-arrow-left:var(--tooltip-sizing-arrow) var(--tooltip-sizing-arrow) var(--tooltip-sizing-arrow) 0;--tooltip-border-width-arrow-right:var(--tooltip-sizing-arrow) 0 var(--tooltip-sizing-arrow) var(--tooltip-sizing-arrow);--tooltip-border-width-arrow-up:0 var(--tooltip-sizing-arrow) var(--tooltip-sizing-arrow);--tooltip-sizing-arrow:6px;--tooltip-sizing-arrow-offset:14px;--tooltip-dimension-max-width:320px}.pds-tooltip__content{background-color:var(--pine-color-primary);border-radius:calc(var(--pine-dimension-xs) * 1.25);-webkit-box-shadow:var(--pine-box-shadow);box-shadow:var(--pine-box-shadow);color:var(--pine-color-text-primary);max-width:var(--tooltip-dimension-max-width);opacity:0;padding:var(--pine-dimension-xs) calc(var(--pine-dimension-md) / 2);position:relative;visibility:hidden;width:-webkit-max-content;width:-moz-max-content;width:max-content}.pds-tooltip--is-open .pds-tooltip__content{opacity:1;visibility:visible;z-index:var(--pine-z-index-raised)}.pds-tooltip.pds-tooltip--has-html-content .pds-tooltip__content{width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.pds-tooltip__content::after{border-color:transparent;border-right-color:transparent;border-style:solid;border-width:var(--tooltip-border-width-arrow-left);content:\"\";height:0;position:absolute;width:0}.pds-tooltip--right .pds-tooltip__content::after{border-inline-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-left);left:calc(var(--tooltip-sizing-arrow) * -1);top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.pds-tooltip--right-end .pds-tooltip__content::after{border-inline-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-left);bottom:var(--tooltip-sizing-arrow-offset);left:calc(var(--tooltip-sizing-arrow) * -1);top:initial}.pds-tooltip--right-start .pds-tooltip__content::after{border-inline-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-left);left:calc(var(--tooltip-sizing-arrow) * -1);top:var(--tooltip-sizing-arrow-offset)}.pds-tooltip--top .pds-tooltip__content::after{border-block-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-down);bottom:calc(var(--tooltip-sizing-arrow) * -1);left:50%;top:initial;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.pds-tooltip--top-start .pds-tooltip__content::after{border-block-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-down);bottom:calc(var(--tooltip-sizing-arrow) * -1);left:var(--tooltip-sizing-arrow-offset);top:initial}.pds-tooltip--top-end .pds-tooltip__content::after{border-block-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-down);bottom:calc(var(--tooltip-sizing-arrow) * -1);left:initial;right:var(--tooltip-sizing-arrow-offset);top:initial}.pds-tooltip--left .pds-tooltip__content::after{border-inline-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-right);left:initial;right:calc(var(--tooltip-sizing-arrow) * -1);top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.pds-tooltip--left-end .pds-tooltip__content::after{border-inline-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-right);bottom:var(--tooltip-sizing-arrow-offset);left:initial;right:calc(var(--tooltip-sizing-arrow) * -1);top:initial}.pds-tooltip--left-start .pds-tooltip__content::after{border-inline-start-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-right);left:initial;right:calc(var(--tooltip-sizing-arrow) * -1);top:var(--tooltip-sizing-arrow-offset)}.pds-tooltip--bottom .pds-tooltip__content::after{border-block-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-up);left:50%;top:calc(var(--tooltip-sizing-arrow) * -1);-webkit-transform:translateX(-50%);transform:translateX(-50%)}.pds-tooltip--bottom-end .pds-tooltip__content::after{border-block-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-up);left:initial;right:var(--tooltip-sizing-arrow-offset);top:calc(var(--tooltip-sizing-arrow) * -1)}.pds-tooltip--bottom-start .pds-tooltip__content::after{border-block-end-color:var(--pine-color-primary);border-width:var(--tooltip-border-width-arrow-up);left:var(--tooltip-sizing-arrow-offset);top:calc(var(--tooltip-sizing-arrow) * -1)}.pds-tooltip--no-arrow .pds-tooltip__content::after{border-width:0}";

const PdsTooltip = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        /**
         * Internal state: true if the tooltip was opened by user interaction (hover/focus),
         * false if opened via the `opened` prop or currently closed.
         */
        this._isInteractiveOpen = false;
        this.portalEl = null;
        this.resolvedPlacement = 'right';
        this.triggerEl = null;
        this.contentDiv = null;
        this.slotMutationObserver = null;
        this.currentPathname = '';
        this.pathnameCheckInterval = null;
        this.stopAutoUpdate = null;
        /**
         * Determines whether or not the tooltip has an arrow
         * @defaultValue true
         */
        this.hasArrow = true;
        /**
         * Enable this option when using the content slot
         * @defaultValue false
         */
        this.htmlContent = false;
        /**
         * Determines the preferred position of the tooltip
         * @defaultValue "right"
         */
        this.placement = 'right';
        /**
         * Sets the maximum width of the tooltip content
         * @defaultValue "352px"
         */
        this.maxWidth = '352px';
        /**
         * Determines whether or not the tooltip is visible
         * @defaultValue false
         */
        this.opened = false;
        this.handleHide = () => {
            if (this.opened && !this._isInteractiveOpen) {
                return;
            }
            this.hideTooltip();
            this._isInteractiveOpen = false;
        };
        this.handleShow = () => {
            if (this.opened && !this._isInteractiveOpen) {
                return;
            }
            this._isInteractiveOpen = true;
            this.showTooltip();
        };
        this.handlePageShow = () => {
            if (this.opened && !this._isInteractiveOpen) {
                return;
            }
            this.opened = false;
            this._isInteractiveOpen = false;
        };
        this.handleSpaNavigation = () => {
            if (this.opened && !this._isInteractiveOpen) {
                return;
            }
            this.hideTooltip();
            this._isInteractiveOpen = false;
        };
        this.checkPathnameChange = () => {
            if (window.location.pathname !== this.currentPathname) {
                this.currentPathname = window.location.pathname;
                this.handleSpaNavigation();
            }
        };
    }
    handleOpenToggle(newValue, oldValue) {
        if (newValue === false && oldValue === true) {
            this._isInteractiveOpen = false;
        }
    }
    componentWillLoad() {
        this._isInteractiveOpen = false;
        this.resolvedPlacement = this.placement;
    }
    componentDidLoad() {
        window.addEventListener('pageshow', this.handlePageShow);
        this.currentPathname = window.location.pathname;
        this.triggerEl = this.el.querySelector('.pds-tooltip__trigger');
        const contentSlotWrapper = this.el.querySelector('.pds-tooltip__content-slot-wrapper');
        if (contentSlotWrapper !== null) {
            this.slotMutationObserver = new MutationObserver(() => {
                if (this.opened && this.portalEl !== null) {
                    this.removePortal();
                    this.createPortal();
                }
            });
            this.slotMutationObserver.observe(contentSlotWrapper, { childList: true, subtree: false });
        }
        // no return; Stencil ignores teardown functions here
    }
    disconnectedCallback() {
        window.removeEventListener('pageshow', this.handlePageShow);
        if (this.slotMutationObserver !== null) {
            this.slotMutationObserver.disconnect();
            this.slotMutationObserver = null;
        }
        // Ensure global listeners/intervals are removed if still present
        if (this.portalEl !== null) {
            this.removePortal();
        }
        if (this.pathnameCheckInterval !== null) {
            clearInterval(this.pathnameCheckInterval);
            this.pathnameCheckInterval = null;
        }
        // Ensure autoUpdate is stopped if still present
        if (this.stopAutoUpdate !== null) {
            this.stopAutoUpdate();
            this.stopAutoUpdate = null;
        }
    }
    componentDidRender() {
        if (this.opened && this.portalEl === null) {
            this.createPortal();
        }
        else if (!this.opened && this.portalEl !== null) {
            this.removePortal();
        }
        // Update portal class when opened state changes
        if (this.portalEl !== null) {
            this.portalEl.className = `pds-tooltip pds-tooltip--${this.resolvedPlacement} ${this.htmlContent ? 'pds-tooltip--has-html-content' : ''} ${this.opened ? 'pds-tooltip--is-open' : ''} ${this.hasArrow ? '' : 'pds-tooltip--no-arrow'}`;
            // Update ARIA attributes to stay in sync with visual open state
            this.portalEl.setAttribute('aria-hidden', this.opened ? 'false' : 'true');
            this.portalEl.setAttribute('aria-live', this.opened ? 'polite' : 'off');
        }
    }
    /**
     * Shows the tooltip by enabling the opened property
     */
    async showTooltip() {
        this.opened = true;
    }
    /**
     * Hides the tooltip by disabling the opened property
     */
    async hideTooltip() {
        this.opened = false;
    }
    /**
     * Determines the most accurate HTML element to use as the anchor for positioning the tooltip.
     * If `htmlContent` is false, it attempts to find the actual element slotted as the trigger.
     * Otherwise, or if no specific element is found, it defaults to the span wrapper around the trigger slot.
     * This helps with precise alignment.
     */
    determinePositioningAnchor() {
        let positioningAnchor = this.triggerEl;
        if (this.triggerEl !== null) {
            const children = this.triggerEl.childNodes;
            for (let i = 0; i < children.length; i++) {
                const childNode = children[i];
                if (childNode.nodeType === Node.ELEMENT_NODE) {
                    positioningAnchor = childNode;
                    break; // Found the first element, use it as the anchor
                }
            }
        }
        // If no ELEMENT_NODE is found within this.triggerEl (e.g., if trigger is just text),
        // positioningAnchor will correctly remain this.triggerEl (the span).
        return positioningAnchor;
    }
    /**
     * Centralized method to calculate and apply the tooltip's position using floating UI.
     * Uses the determined anchor element and applies computePosition with flip, offset, and shift.
     */
    async repositionPortal() {
        const anchor = this.determinePositioningAnchor();
        if (anchor !== null && this.portalEl !== null) {
            try {
                const { x, y, placement: computedPlacement } = await floatingUi_dom.computePosition(anchor, this.portalEl, {
                    placement: this.placement,
                    strategy: 'fixed',
                    middleware: [floatingUi_dom.offset(8), floatingUi_dom.flip(), floatingUi_dom.shift({ padding: 5 })],
                });
                this.resolvedPlacement = computedPlacement;
                Object.assign(this.portalEl.style, {
                    left: `${x}px`,
                    top: `${y}px`,
                    position: 'fixed',
                });
                // Update CSS classes to match the resolved placement
                this.portalEl.className = `pds-tooltip pds-tooltip--${this.resolvedPlacement} ${this.htmlContent ? 'pds-tooltip--has-html-content' : ''} ${this.opened ? 'pds-tooltip--is-open' : ''} ${this.hasArrow ? '' : 'pds-tooltip--no-arrow'}`;
            }
            catch (error) {
                console.warn('Failed to position tooltip:', error);
                this.resolvedPlacement = this.placement; // Fallback to requested placement
                // Fallback to basic positioning if floating UI fails
                const anchorRect = anchor.getBoundingClientRect();
                this.portalEl.style.left = `${anchorRect.right + 8}px`;
                this.portalEl.style.top = `${anchorRect.top}px`;
                this.portalEl.style.position = 'fixed';
            }
        }
    }
    createPortal() {
        if (this.portalEl !== null)
            return;
        this.portalEl = document.createElement('div');
        this.portalEl.className = `pds-tooltip pds-tooltip--${this.resolvedPlacement} ${this.htmlContent ? 'pds-tooltip--has-html-content' : ''} ${this.opened ? 'pds-tooltip--is-open' : ''} ${this.hasArrow ? '' : 'pds-tooltip--no-arrow'}`;
        this.portalEl.style.position = 'fixed';
        this.portalEl.style.zIndex = 'var(--pine-z-index-nuclear)';
        if (this.portalEl.id === '') {
            const suffix = PdsTooltip.instanceCounter++;
            const baseId = this.componentId || this.el.id || 'pds-tooltip';
            this.portalEl.id = `${baseId}-portal-${suffix}`;
        }
        if (this.portalEl.getAttribute('id') !== this.portalEl.id) {
            this.portalEl.setAttribute('id', this.portalEl.id);
        }
        this.portalEl.setAttribute('role', 'tooltip');
        this.portalEl.setAttribute('aria-hidden', this.opened ? 'false' : 'true');
        this.portalEl.setAttribute('aria-live', this.opened ? 'polite' : 'off');
        this.portalEl.style.maxWidth = this.maxWidth;
        this.contentDiv = document.createElement('div');
        this.contentDiv.className = 'pds-tooltip__content';
        this.contentDiv.setAttribute('aria-hidden', this.opened ? 'false' : 'true');
        this.contentDiv.setAttribute('aria-live', this.opened ? 'polite' : 'off');
        const contentSlotWrapper = this.el.querySelector('.pds-tooltip__content-slot-wrapper');
        const slottedContentContainer = contentSlotWrapper === null || contentSlotWrapper === void 0 ? void 0 : contentSlotWrapper.querySelector('[slot="content"]');
        let hasSlottedContent = false;
        if (slottedContentContainer !== null) {
            const childrenToClone = Array.from(slottedContentContainer.childNodes);
            if (childrenToClone.length > 0) {
                const hasMeaningfulNode = childrenToClone.some(node => {
                    var _a;
                    return node.nodeType === Node.ELEMENT_NODE ||
                        (node.nodeType === Node.TEXT_NODE && ((_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim()) !== '');
                });
                if (hasMeaningfulNode) {
                    hasSlottedContent = true;
                    childrenToClone.forEach((node /*, index*/) => {
                        var _a;
                        if (node.nodeType === Node.ELEMENT_NODE || (node.nodeType === Node.TEXT_NODE && ((_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim()) !== '')) {
                            this.contentDiv.appendChild(node.cloneNode(true));
                        }
                    });
                }
            }
        }
        if (!hasSlottedContent && typeof this.content === 'string' && this.content.trim() !== '') {
            this.contentDiv.textContent = this.content;
        }
        this.portalEl.appendChild(this.contentDiv);
        document.body.appendChild(this.portalEl);
        this.repositionPortal().catch(error => {
            console.warn('Failed to position tooltip on creation:', error);
        });
        // Use Floating UI's autoUpdate to handle scroll/resize automatically
        if (this.triggerEl && this.portalEl) {
            this.stopAutoUpdate = floatingUi_dom.autoUpdate(this.triggerEl, this.portalEl, () => {
                this.repositionPortal().catch(error => {
                    console.warn('Failed to reposition tooltip on auto update:', error);
                });
            });
        }
        // Keep only SPA navigation listeners (not handled by autoUpdate)
        window.addEventListener('popstate', this.handleSpaNavigation, true);
        window.addEventListener('hashchange', this.handleSpaNavigation, true);
        // Start pathname change detection
        this.pathnameCheckInterval = setInterval(this.checkPathnameChange, 100);
        // Add ARIA attribute to trigger, now that portalEl and its ID are confirmed
        if (this.triggerEl !== null && this.portalEl.id !== '') {
            this.triggerEl.setAttribute('aria-describedby', this.portalEl.id);
        }
    }
    removePortal() {
        // Stop Floating UI's autoUpdate
        if (this.stopAutoUpdate !== null) {
            this.stopAutoUpdate();
            this.stopAutoUpdate = null;
        }
        // Stop pathname change detection
        if (this.pathnameCheckInterval !== null) {
            clearInterval(this.pathnameCheckInterval);
            this.pathnameCheckInterval = null;
        }
        if (this.portalEl !== null) {
            // Remove only SPA navigation listeners (scroll/resize handled by autoUpdate)
            window.removeEventListener('popstate', this.handleSpaNavigation, true);
            window.removeEventListener('hashchange', this.handleSpaNavigation, true);
            // Safely remove portal from DOM
            try {
                if (this.portalEl.parentNode) {
                    this.portalEl.parentNode.removeChild(this.portalEl);
                }
            }
            catch (error) {
                // Portal might have already been removed by test cleanup
                console.warn('Portal element could not be removed from DOM:', error);
            }
            this.portalEl = null;
        }
        // Remove ARIA attribute from trigger
        if (this.triggerEl !== null) {
            this.triggerEl.removeAttribute('aria-describedby');
        }
        this.contentDiv = null;
    }
    render() {
        const hostId = this.componentId || undefined;
        return (index.h(index.Host, { key: '4e6188e03c2f1d33e571b96a3006a585840716bd', id: hostId, class: { 'pds-tooltip--is-open': this.opened } }, index.h("span", { key: '0b82d180295421c32548577fb2038422b8ebd3be', class: "pds-tooltip__trigger", onMouseEnter: this.handleShow, onMouseLeave: this.handleHide,
            /* focusin/out bubble; ensure keyboard users see tooltips */
            onFocusin: this.handleShow, onFocusout: this.handleHide, ref: el => this.triggerEl = el }, index.h("slot", { key: '661014ee46b11bcc906e7b64ef8c8a5739d459f0' })), index.h("div", { key: '1861ce9b260f5f7d2eb0a1f337dadd63a0dfee97', class: "pds-tooltip__content-slot-wrapper", hidden: true }, index.h("slot", { key: '963fb263c72fba432c2b672a2c3e85ca524f2b67', name: "content" }))));
    }
    get el() { return index.getElement(this); }
    static get watchers() { return {
        "opened": ["handleOpenToggle"]
    }; }
};
PdsTooltip.instanceCounter = 0;
PdsTooltip.style = pdsTooltipCss;

exports.pds_tooltip = PdsTooltip;
//# sourceMappingURL=pds-tooltip.entry.cjs.js.map
