'use strict';

var index = require('./index-DuCXzb-X.js');

const spwDropdownCss = () => `html{line-height:1.3;-webkit-text-size-adjust:100%;}h1,h2,h3,h4,h5,h6,p,ul,li{padding:0;margin:0}ul{list-style:none}:host{box-sizing:border-box;line-height:1.3;-webkit-text-size-adjust:100%;font-size:100%}:host *,:host *::before,:host *::after{box-sizing:inherit;font-family:var(--spw-ds-font-main)}body{margin:0}hr{box-sizing:content-box;height:0;overflow:visible;}pre{font-family:monospace, monospace;font-size:1em;}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted;}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace, monospace;font-size:1em;}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0;}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal;}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0;}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px;}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit;}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}:root{--spw-ds-container-xl:1232px;--spw-ds-container-lg:1024px;--spw-ds-container-md:768px;--spw-ds-container-sm:640px}.spw-ds-container{width:100%;padding-left:16px;padding-right:16px;margin-left:auto;margin-right:auto}@media (min-width: 460px){.spw-ds-container{max-width:var(--spw-ds-container-sm)}}@media (min-width: 768px){.spw-ds-container{max-width:var(--spw-ds-container-md)}}@media (min-width: 1024px){.spw-ds-container{max-width:var(--spw-ds-container-lg)}}@media (min-width: 1350px){.spw-ds-container{max-width:var(--spw-ds-container-xl)}}:host{display:inline-block;line-height:1}:host([open]){--spw-dropdown-icon-color:var(--spw-color-themes-grey-grey-900)}.spw-dropdown__trigger{cursor:pointer}.spw-dropdown__trigger:hover{--spw-dropdown-icon-color:var(--spw-color-themes-grey-grey-900)}.spw-dropdown__trigger ::slotted(spw-icon){color:var(--spw-dropdown-icon-color, inherit)}`;

const SpwDropdown = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.spwDropdownOpen = index.createEvent(this, "spwDropdownOpen", 7);
        this.spwDropdownClose = index.createEvent(this, "spwDropdownClose", 7);
        /** Position du dropdown */
        this.direction = 'bottom';
        /** Alignement du dropdown par rapport au trigger (start/end = haut-gauche pour top/bottom, haut-bas pour left/right) */
        this.alignment = 'center';
        /** Active un padding interne */
        this.hasPadding = true;
        /** Largeur du dropdown (px) */
        this.contentWidth = 300;
        /** Hauteur max du dropdown (px) */
        this.maxHeight = 'auto';
        /** Contrôle externe du dropdown */
        this.open = false;
        this.isVisible = false;
        this.dropdownEl = null;
        this.movedContentEl = null;
        this.triggerEl = null;
        this.handleKeyDown = null;
        this.showDropdown = () => {
            var _a, _b;
            if (this.isVisible)
                return;
            const slotContent = this.host.querySelector('[slot="dropdownContent"]');
            if (!slotContent)
                return;
            this.isVisible = true;
            this.spwDropdownOpen.emit();
            this.triggerEl = (_b = (_a = this.host.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.spw-dropdown__trigger')) !== null && _b !== void 0 ? _b : null;
            this.dropdownEl = document.createElement('div');
            this.dropdownEl.className = `spw-dropdown-fixed spw-dropdown-fixed--${this.direction} spw-dropdown-fixed--${this.alignment}`;
            if (this.hasPadding)
                this.dropdownEl.classList.add('spw-dropdown-fixed--padded');
            this.dropdownEl.setAttribute('role', 'menu');
            this.dropdownEl.setAttribute('aria-modal', 'false');
            this.dropdownEl.style.width = `${this.contentWidth || 200}px`;
            this.dropdownEl.style.maxHeight = this.maxHeight !== 'auto' ? `${this.maxHeight}px` : 'none';
            this.dropdownEl.style.overflowY = this.maxHeight !== 'auto' ? 'auto' : 'visible';
            this.movedContentEl = slotContent;
            this.dropdownEl.appendChild(this.movedContentEl);
            document.body.appendChild(this.dropdownEl);
            requestAnimationFrame(() => {
                this.positionDropdown();
                this.addListeners();
                const focusable = this.getFocusableElements();
                if (focusable.length > 0) {
                    focusable[0].focus();
                }
            });
        };
        this.hideDropdown = () => {
            var _a;
            if (!this.isVisible)
                return;
            this.isVisible = false;
            this.open = false;
            this.spwDropdownClose.emit();
            if (this.dropdownEl && this.movedContentEl) {
                this.host.appendChild(this.movedContentEl);
            }
            if ((_a = this.dropdownEl) === null || _a === void 0 ? void 0 : _a.parentNode) {
                this.dropdownEl.parentNode.removeChild(this.dropdownEl);
            }
            this.dropdownEl = null;
            this.movedContentEl = null;
            this.removeListeners();
        };
    }
    async close() {
        this.open = false;
        this.hideDropdown();
    }
    onOpenChange(newVal) {
        newVal ? this.showDropdown() : this.hideDropdown();
    }
    connectedCallback() {
        this.handleClickOutside = this.handleClickOutside.bind(this);
        this.handleScrollOrResize = this.handleScrollOrResize.bind(this);
        this.handleTriggerKeyDown = this.handleTriggerKeyDown.bind(this);
        this.host.addEventListener('keydown', this.handleTriggerKeyDown);
    }
    handleTriggerKeyDown(e) {
        if ((e.key === 'Enter' || e.key === ' ') && !this.isVisible) {
            e.preventDefault();
            this.open = true;
        }
    }
    componentDidLoad() {
        if (this.open) {
            this.showDropdown();
        }
    }
    disconnectedCallback() {
        this.removeListeners();
        this.host.removeEventListener('keydown', this.handleTriggerKeyDown);
    }
    addListeners() {
        document.addEventListener('click', this.handleClickOutside, true);
        window.addEventListener('scroll', this.handleScrollOrResize, true);
        window.addEventListener('resize', this.handleScrollOrResize);
        this.handleKeyDown = (e) => {
            var _a;
            if (!this.dropdownEl)
                return;
            if (e.key === 'Escape') {
                e.preventDefault();
                this.close();
                (_a = this.triggerEl) === null || _a === void 0 ? void 0 : _a.focus();
                return;
            }
            if (e.key === 'Tab') {
                const focusable = this.getFocusableElements();
                if (focusable.length === 0)
                    return;
                const first = focusable[0];
                const last = focusable[focusable.length - 1];
                if (e.shiftKey) {
                    if (document.activeElement === first) {
                        e.preventDefault();
                        last.focus();
                    }
                }
                else {
                    if (document.activeElement === last) {
                        e.preventDefault();
                        first.focus();
                    }
                }
                return;
            }
            if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
                e.preventDefault();
                const focusable = this.getFocusableElements();
                if (focusable.length === 0)
                    return;
                const currentIndex = focusable.indexOf(document.activeElement);
                if (e.key === 'ArrowDown') {
                    const next = currentIndex < focusable.length - 1 ? currentIndex + 1 : 0;
                    focusable[next].focus();
                }
                else {
                    const prev = currentIndex > 0 ? currentIndex - 1 : focusable.length - 1;
                    focusable[prev].focus();
                }
            }
        };
        document.addEventListener('keydown', this.handleKeyDown, true);
    }
    removeListeners() {
        document.removeEventListener('click', this.handleClickOutside, true);
        window.removeEventListener('scroll', this.handleScrollOrResize, true);
        window.removeEventListener('resize', this.handleScrollOrResize);
        if (this.handleKeyDown) {
            document.removeEventListener('keydown', this.handleKeyDown, true);
            this.handleKeyDown = null;
        }
    }
    getFocusableElements() {
        if (!this.dropdownEl)
            return [];
        return Array.from(this.dropdownEl.querySelectorAll('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])')).filter(el => !el.closest('[aria-disabled="true"]'));
    }
    handleClickOutside(event) {
        var _a;
        if (!this.host.contains(event.target) && !((_a = this.dropdownEl) === null || _a === void 0 ? void 0 : _a.contains(event.target))) {
            this.close();
        }
    }
    handleScrollOrResize() {
        if (this.isVisible) {
            this.positionDropdown();
        }
    }
    positionDropdown() {
        var _a;
        if (!this.dropdownEl)
            return;
        const trigger = (_a = this.host.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.spw-dropdown__trigger');
        if (!trigger)
            return;
        const rect = trigger.getBoundingClientRect();
        const dropdown = this.dropdownEl;
        dropdown.style.visibility = 'hidden';
        dropdown.style.position = 'fixed';
        dropdown.style.display = 'flex';
        const dropdownRect = dropdown.getBoundingClientRect();
        let top = 0;
        let left = 0;
        const alignedLeft = (() => {
            switch (this.alignment) {
                case 'start': return rect.left;
                case 'end': return rect.right - dropdownRect.width;
                case 'center':
                default: return rect.left + (rect.width - dropdownRect.width) / 2;
            }
        })();
        const alignedTop = (() => {
            switch (this.alignment) {
                case 'start': return rect.top;
                case 'end': return rect.bottom - dropdownRect.height;
                case 'center':
                default: return rect.top + (rect.height - dropdownRect.height) / 2;
            }
        })();
        switch (this.direction) {
            case 'top':
                top = rect.top - dropdownRect.height - 8;
                left = alignedLeft;
                break;
            case 'bottom':
                top = rect.bottom + 8;
                left = alignedLeft;
                break;
            case 'left':
                top = alignedTop;
                left = rect.left - dropdownRect.width - 8;
                break;
            case 'right':
            default:
                top = alignedTop;
                left = rect.right + 8;
                break;
        }
        dropdown.style.top = `${top}px`;
        dropdown.style.left = `${left}px`;
        dropdown.style.zIndex = '9999';
        dropdown.style.visibility = 'visible';
    }
    render() {
        return (index.h("div", { key: '9436b4657389ba587830dcc8f7dc9f13aa33ef0a', class: "spw-dropdown__trigger", onClick: () => (this.open = !this.open), "aria-expanded": this.open ? 'true' : 'false', "aria-haspopup": "menu" }, index.h("slot", { key: '3abcf24a43d046fde173ffe2ac73d376cf78ec6e' })));
    }
    get host() { return index.getElement(this); }
    static get watchers() { return {
        "open": [{
                "onOpenChange": 0
            }]
    }; }
};
SpwDropdown.style = spwDropdownCss();

exports.spw_dropdown = SpwDropdown;
