import { r as registerInstance, c as createEvent, h, H as Host, a as getElement } from './index-Co4V4Zk-.js';
import { a as animationTo, K as KEYFRAMES } from './animation-BRFNx2DL.js';

/**
 * Copy/pasted from https://github.com/andreasbm/focus-trap
 */
/**
 * Traverses the slots of the open shadowroots and returns all children matching the query.
 * We need to traverse each child-depth one at a time because if an element should be skipped
 * (for example because it is hidden) we need to skip all of it's children. If we use querySelectorAll("*")
 * the information of whether the children is within a hidden parent is lost.
 * @param {ShadowRoot | HTMLElement} root
 * @param skipNode
 * @param isMatch
 * @param {number} maxDepth
 * @param {number} depth
 * @returns {HTMLElement[]}
 */
function queryShadowRoot(root, skipNode, isMatch, maxDepth = 20, depth = 0) {
    const matches = [];
    // If the depth is above the max depth, abort the searching here.
    if (depth >= maxDepth) {
        return matches;
    }
    // Traverses a slot element
    const traverseSlot = ($slot) => {
        // Only check nodes that are of the type Node.ELEMENT_NODE
        // Read more here https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
        const assignedNodes = $slot.assignedNodes().filter(node => node.nodeType === 1);
        if (assignedNodes.length > 0) {
            const $slotParent = assignedNodes[0].parentElement;
            return queryShadowRoot($slotParent, skipNode, isMatch, maxDepth, depth + 1);
        }
        return [];
    };
    // Go through each child and continue the traversing if necessary
    // Even though the typing says that children can't be undefined, Edge 15 sometimes gives an undefined value.
    // Therefore we fallback to an empty array if it is undefined.
    const children = Array.from(root.children || []);
    for (const $child of children) {
        // Check if the element and its descendants should be skipped
        if (skipNode($child)) {
            // console.log('-- SKIP', $child);
            continue;
        }
        // console.log('$child', $child);
        // If the element matches we always add it
        if (isMatch($child)) {
            matches.push($child);
        }
        if ($child.shadowRoot != null) {
            // If the element has a shadow root we need to traverse it
            matches.push(...queryShadowRoot($child.shadowRoot, skipNode, isMatch, maxDepth, depth + 1));
        }
        else if ($child.tagName === 'SLOT') {
            // If the child is a slot we need to traverse each assigned node
            matches.push(...traverseSlot($child));
        }
        else {
            // Traverse the children of the element
            matches.push(...queryShadowRoot($child, skipNode, isMatch, maxDepth, depth + 1));
        }
    }
    return matches;
}
/**
 * Returns whether the element is hidden.
 * @param $elem
 */
function isHidden($elem) {
    return ($elem.hasAttribute('hidden') ||
        ($elem.hasAttribute('aria-hidden') && $elem.getAttribute('aria-hidden') !== 'false') ||
        // A quick and dirty way to check whether the element is hidden.
        // For a more fine-grained check we could use "window.getComputedStyle" but we don't because of bad performance.
        // If the element has visibility set to "hidden" or "collapse", display set to "none" or opacity set to "0" through CSS
        // we won't be able to catch it here. We accept it due to the huge performance benefits.
        $elem.style.display === `none` ||
        $elem.style.opacity === `0` ||
        $elem.style.visibility === `hidden` ||
        $elem.style.visibility === `collapse`);
    // If offsetParent is null we can assume that the element is hidden
    // https://stackoverflow.com/questions/306305/what-would-make-offsetparent-null
    // || $elem.offsetParent == null;
}
/**
 * Returns whether the element is disabled.
 * @param $elem
 */
function isDisabled($elem) {
    return $elem.hasAttribute('disabled') || ($elem.hasAttribute('aria-disabled') && $elem.getAttribute('aria-disabled') !== 'false');
}
/**
 * Determines whether an element is focusable.
 * Read more here: https://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus/1600194#1600194
 * Or here: https://stackoverflow.com/questions/18261595/how-to-check-if-a-dom-element-is-focusable
 * @param $elem
 */
function isFocusable($elem) {
    // Discard elements that are removed from the tab order.
    if ($elem.getAttribute('tabindex') === '-1' || isHidden($elem) || isDisabled($elem)) {
        return false;
    }
    return (
    // At this point we know that the element can have focus (eg. won't be -1) if the tabindex attribute exists
    $elem.hasAttribute('tabindex') ||
        // Anchor tags or area tags with a href set
        (($elem instanceof HTMLAnchorElement || $elem instanceof HTMLAreaElement) && $elem.hasAttribute('href')) ||
        // Form elements which are not disabled
        $elem instanceof HTMLButtonElement ||
        $elem instanceof HTMLInputElement ||
        $elem instanceof HTMLTextAreaElement ||
        $elem instanceof HTMLSelectElement ||
        // IFrames
        $elem instanceof HTMLIFrameElement);
}

const spwModalCss = () => `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:contents}.spw-modal{display:none;justify-content:center;align-items:center;position:fixed;top:0;left:0;width:100%;height:100%;z-index:1060;overflow-y:auto}.spw-modal::-webkit-scrollbar{width:14px;height:14px}.spw-modal::-webkit-scrollbar-thumb{background:var(--spw-color-themes-grey-grey-400);border-radius:20px;border:4px solid var(--spw-ds-white)}.spw-modal::-webkit-scrollbar-track{background:var(--spw-ds-white)}.spw-modal{scrollbar-face-color:var(--spw-color-themes-grey-grey-400);scrollbar-track-color:var(--spw-ds-white)}.spw-modal--opened{display:flex}.spw-modal__overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:black;opacity:0.7;z-index:0}.spw-modal__content-container{position:absolute;display:flex;justify-content:center;width:90%;background-color:#fff;box-shadow:var(--spw-effect-elevation-6);overflow:hidden;box-sizing:border-box;align-items:stretch;border-radius:var(--spw-spacings-border-radius-lg)}.spw-modal__content-container--small{max-width:480px}.spw-modal__content-container--medium{max-width:600px}.spw-modal__content-container--large{max-width:768px}.spw-modal__content-container--fluid{max-width:100%}.spw-modal__content{display:flex;flex-direction:column;border:1px solid var(--spw-color-themes-grey-grey-300);width:100%;max-height:90vh;overflow-y:auto}.spw-modal__content::-webkit-scrollbar{width:14px;height:14px}.spw-modal__content::-webkit-scrollbar-thumb{background:var(--spw-color-themes-grey-grey-400);border-radius:20px;border:4px solid var(--spw-ds-white)}.spw-modal__content::-webkit-scrollbar-track{background:var(--spw-ds-white)}.spw-modal__content{scrollbar-face-color:var(--spw-color-themes-grey-grey-400);scrollbar-track-color:var(--spw-ds-white)}.spw-modal--sticky-buttons .spw-modal__content{overflow-y:visible}.spw-modal__icon-container{display:flex;align-items:center;justify-content:center;width:32px;background-color:#fff;align-self:stretch}.spw-modal__header{display:flex;justify-content:space-between;align-items:baseline;padding:24px;padding-bottom:0;margin-top:6px;gap:12px;flex-wrap:nowrap;margin-bottom:12px;box-sizing:border-box;border-radius:1px 1px 0px 0px;color:var(--spw-colors-support-grey-grey-900)}.spw-modal__title-container{display:flex;gap:8px}.spw-modal__alert-icon{flex-shrink:0;line-height:1.5}.spw-modal__caption{overflow:hidden;white-space:pre-wrap;word-wrap:break-word}.spw-modal__header h2{margin:0;font-size:18px;color:var(--spw-colors-support-grey-grey-900)}.spw-modal__header button{background:none;border:none;font-size:1.5em;padding:0;cursor:pointer}.spw-modal__close-button{cursor:pointer;z-index:999;font-size:14px;display:inline-flex;align-items:center;flex-wrap:nowrap;justify-content:center;background:white;padding:3px 6px;margin-bottom:1px}.spw-modal__close-button spw-link{--spw-link-color:var(--spw-colors-support-grey-grey-900);--spw-link-wrap:nowrap}.spw-modal__close-button--sticky{position:absolute;top:0;right:0;border-radius:0 0 0 4px;padding:8px;border-bottom:1px solid var(--spw-colors-support-grey-grey-300);border-left:1px solid var(--spw-colors-support-grey-grey-300)}.spw-modal__close-button--sticky spw-link{font-size:14px}.spw-modal__body{padding:0 24px;margin-bottom:12px;box-sizing:border-box;flex:1;font-size:16px;color:var(--spw-colors-support-grey-grey-700)}.spw-modal--sticky-buttons .spw-modal__body{overflow-y:auto}.spw-modal--sticky-buttons .spw-modal__body::-webkit-scrollbar{width:14px;height:14px}.spw-modal--sticky-buttons .spw-modal__body::-webkit-scrollbar-thumb{background:var(--spw-color-themes-grey-grey-400);border-radius:20px;border:4px solid var(--spw-ds-white)}.spw-modal--sticky-buttons .spw-modal__body::-webkit-scrollbar-track{background:var(--spw-ds-white)}.spw-modal--sticky-buttons .spw-modal__body{scrollbar-face-color:var(--spw-color-themes-grey-grey-400);scrollbar-track-color:var(--spw-ds-white)}.spw-modal__buttons{padding-top:12px}.spw-modal__buttons ::slotted([slot=buttons]){padding:24px;padding-top:0}@media (min-width: 768px){.spw-modal__footer--buttons-present ::slotted(*){display:flex;justify-content:flex-end;gap:12px}}.spw-modal__footer--buttons-present ::slotted(*){padding:24px;padding-top:8px}.spw-modal__border{display:flex;align-items:center;justify-content:center;width:100%;font-size:1.5em;flex-grow:1}`;

const SpwModal = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.spwModalOpen = createEvent(this, "spwModalOpen", 7);
        this.spwModalClose = createEvent(this, "spwModalClose", 7);
        /** Indique si la modal est ouverte ou fermée, mutable et reflétée dans le DOM */
        this.opened = false;
        this.showModal = this.opened || false;
        /** Titre de la modal */
        this.caption = 'Titre de la modal';
        /** Texte du bouton de fermeture */
        this.closeButtonText = 'Fermer';
        /** Indique si la fermeture de la modal est possible en cliquant sur l'overlay */
        this.closeOnOverlayClick = true;
        /** Rend les boutons en bas de la modal "collants" (toujours visibles) si vrai */
        this.stickyButtons = false;
        /** Définit la taille de la modal : 'small', 'medium', 'large' ou 'fluid' */
        this.size = 'small';
        /** Icône d'alerte à afficher dans la modal (référence font awesome) */
        this.alertIcon = '';
        this.slotButtonsPresent = false;
        this.isCloseButtonSticky = false;
        /** Indique si le bouton de fermeture est visible */
        this.showCloseButton = true;
        this.focusableElements = [];
        this.handleClick = (event) => {
            const path = event.composedPath();
            const trigger = path.find(el => { var _a; return el instanceof HTMLElement && ((_a = el.hasAttribute) === null || _a === void 0 ? void 0 : _a.call(el, 'data-modal-trigger')); });
            if (trigger) {
                const modalId = trigger.getAttribute('data-modal-trigger');
                if (modalId === this.hostElement.id) {
                    this.opened = true;
                }
            }
        };
        this.handleClose = (event) => {
            const path = event.composedPath();
            const trigger = path.find(el => { var _a; return el instanceof HTMLElement && ((_a = el.hasAttribute) === null || _a === void 0 ? void 0 : _a.call(el, 'data-modal-close')); });
            if (trigger) {
                const modalId = trigger.getAttribute('data-modal-close');
                if (modalId === this.hostElement.id) {
                    this.opened = false;
                }
            }
        };
        // private getLastFocusableElement(): HTMLElement | null {
        //   return this.focusableElements[this.focusableElements.length - 1];
        // }
        // private handleTopFocus = () => {
        //   this.attemptFocus(this.getLastFocusableElement());
        // };
        this.handleBottomFocus = () => {
            this.attemptFocus(this.getFirstFocusableElement());
        };
        this.handleKeypress = (event) => {
            if (this.showModal && event.key === 'Escape') {
                this.doBeforeClose('ESCAPE_KEY');
            }
        };
        this.handleContentScroll = () => {
            if (this.modalContent) {
                this.isCloseButtonSticky = this.modalContent.scrollTop >= 60;
            }
        };
    }
    /**
     * Méthode publique pour fermer la modal programmatiquement
     * @returns Promise qui se résout quand la modal est fermée
     */
    async closeModal() {
        this.doBeforeClose('PROGRAMMATIC');
    }
    /**
     * Méthode publique pour ouvrir la modal programmatiquement
     * @returns Promise qui se résout quand la modal est ouverte
     */
    async openModal() {
        this.opened = true;
    }
    componentDidLoad() {
        this.focusableElements = queryShadowRoot(this.hostElement.shadowRoot, el => isHidden(el) || el.matches('[data-focus-trap-edge]'), isFocusable);
        window.addEventListener('click', this.handleClick, { capture: true });
        window.addEventListener('click', this.handleClose, { capture: true });
        window.addEventListener('keydown', this.handleKeypress);
    }
    disconnectedCallback() {
        window.removeEventListener('click', this.handleClick);
        window.removeEventListener('click', this.handleClose);
        window.removeEventListener('keydown', this.handleKeypress);
    }
    getFirstFocusableElement() {
        return this.focusableElements[0];
    }
    attemptFocus(element) {
        if (element == null) {
            setTimeout(() => {
                this.closeButton.focus();
            });
            return;
        }
        setTimeout(() => {
            element.focus();
        }, 0);
    }
    open() {
        this.showModal = true;
        this.isCloseButtonSticky = false;
        requestAnimationFrame(() => {
            if (this.modalContent) {
                this.modalContent.scrollTop = 0;
            }
        });
        try {
            const anim = animationTo(this.modalContainer, KEYFRAMES.fadeIn, {
                duration: 200,
            });
            anim.addEventListener('finish', () => {
                setTimeout(() => {
                    // this.getLastFocusableElement()?.focus();
                    // this.getLastFocusableElement()?.blur();
                }, 0);
                this.spwModalOpen.emit();
            });
        }
        catch (err) {
            this.spwModalOpen.emit();
        }
    }
    close() {
        this.stopAllVideos();
        try {
            const anim = animationTo(this.modalContainer, KEYFRAMES.fadeOut, {
                duration: 200,
            });
            anim.addEventListener('finish', () => {
                this.showModal = false;
                this.spwModalClose.emit();
            });
        }
        catch (err) {
            this.showModal = false;
            this.spwModalClose.emit();
        }
    }
    stopAllVideos() {
        const iframes = this.hostElement.querySelectorAll('iframe');
        iframes.forEach(iframe => {
            iframe.src = iframe.src;
        });
    }
    doBeforeClose(trigger) {
        const triggers = [];
        triggers.push(trigger);
        const prevented = triggers.some(event => event.defaultPrevented);
        if (!prevented) {
            this.opened = false;
        }
    }
    openedChanged(newValue) {
        newValue === true ? this.open() : this.close();
    }
    handleOverlayClick() {
        if (this.closeOnOverlayClick) {
            this.doBeforeClose('BACKDROP');
        }
    }
    get elementClass() {
        return {
            'spw-modal': true,
            'spw-modal--opened': this.showModal,
            'spw-modal--sticky-buttons': this.stickyButtons,
        };
    }
    render() {
        return (h(Host, { key: '4eb87501a9a4cc098250700f58c027e3f3fc13c6' }, h("div", { key: '100bc778f67fca4ebc8ca8e1933033a362f94c24', ref: el => (this.modalContainer = el), class: this.elementClass }, h("div", { key: '56918adc60d5b97ffd43e66323a4fc28f72c6297', class: "spw-modal__overlay", onClick: () => this.handleOverlayClick() }), h("div", { key: '65612030c666acfaa5bafccff02b265e2df49408', class: `spw-modal__content-container spw-modal__content-container--${this.size}`, role: "dialog", "aria-modal": "true", "aria-label": this.caption }, h("div", { key: '51ce6d5e32a972e6c7c7ff95844c6aab0793a979', class: "spw-modal__content", ref: el => (this.modalContent = el), onScroll: this.handleContentScroll }, h("div", { key: '92deb26800d917a018012ae8dab17491fdfade57', class: "spw-modal__header" }, h("div", { key: 'a96de8538e42a2ef89c2669459a4921bb818ad03', class: "spw-modal__title-container" }, this.alertIcon && h("spw-icon", { key: '4328a281475bb9fb969234010872d83ad7c7db72', class: "spw-modal__alert-icon", icon: this.alertIcon }), h("h2", { key: '7c16016aaaced617feb2cbdddb225c0de07c9294', class: "spw-modal__caption" }, this.caption)), this.showCloseButton && (h("div", { key: '3cfd868ed08d69d6eacbc2e2908da0f1ae68236e', class: {
                'spw-modal__close-button': true,
                'spw-modal__close-button--sticky': this.isCloseButtonSticky,
            }, ref: el => (this.closeButton = el), onClick: () => this.doBeforeClose('CLOSE_BUTTON') }, h("spw-link", { key: '36577f9858f3eaa116b41af3e2654b6a0d803fe5', "icon-position": "right", icon: "fa-xmark" }, this.closeButtonText)))), h("div", { key: 'f1fae039840a285805410fee667a4e5c53d441ea', class: "spw-modal__body" }, h("slot", { key: '199cc1dfa3507fee34d5a86f90c35948ad656549', name: "content" })), h("div", { key: '83bfe6dfccb359f373c3e0b7080893a716eb6812', class: { 'spw-modal__buttons': true, 'spw-modal__footer--buttons-present': this.slotButtonsPresent } }, h("slot", { key: '7bc4e5745527068f0cc6eb2bfedc7440e99a0199', name: "buttons", onSlotchange: (e) => {
                const slot = e.target;
                this.slotButtonsPresent = slot.assignedNodes({ flatten: true }).length > 0;
            } })))), h("div", { key: '57d4de3c3d2d5769b14388d16c30471091007af0', "data-focus-trap-edge": true, onFocus: this.handleBottomFocus, tabindex: "0" }))));
    }
    get hostElement() { return getElement(this); }
    static get watchers() { return {
        "opened": [{
                "openedChanged": 0
            }]
    }; }
};
SpwModal.style = spwModalCss();

export { SpwModal as spw_modal };
