var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _EdenModal_renderModalContent, _EdenModal_renderModalButtons, _EdenModal_handleKeyPress, _EdenModal_focusModal, _EdenModal_handleFocus;
import template from "./eden-modal.template.js";
import styles from "./eden-modal.styles.js";
import html from "../../services/html.js";
const FOCUSABLE_ELEMENTS = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
class EdenModal extends HTMLElement {
    constructor(options) {
        super();
        this.close = () => {
            if (typeof this.options.onClose === "function") {
                this.options.onClose(this);
            }
            this.setAttribute("closing", "");
            setTimeout(() => {
                this.remove();
            }, 220);
        };
        _EdenModal_renderModalContent.set(this, () => {
            const title = this.options.icon?.length
                ? html `<eden-icon
            code="${this.options.icon}"
            class="modal__title-icon"
          ></eden-icon>
          ${this.options.title}`
                : this.options.title;
            this.modalTitle.innerHTML = title;
            if (this.options.id) {
                this.setAttribute("id", this.options.id);
            }
            if (this.options.width) {
                this.modal.style.width = `${this.options.width}px`;
            }
            if (this.options.height) {
                this.modal.style.minHeight = `${this.options.height}px`;
            }
            typeof this.options.content === "object"
                ? this.modalContent.appendChild(this.options.content)
                : (this.modalContent.innerHTML = this.options.content);
            if (this.options.noPadding) {
                this.modal.classList.add("modal--no-padding");
            }
            if (this.options.fullScreen) {
                this.setAttribute("fullScreen", "");
            }
            if (this.options.buttons.length !== 0) {
                __classPrivateFieldGet(this, _EdenModal_renderModalButtons, "f").call(this, this.options.buttons);
            }
        });
        _EdenModal_renderModalButtons.set(this, (buttons) => {
            if (buttons === undefined || buttons === null)
                return;
            buttons.forEach((button) => {
                const { cssClass, value, onClick, autofocus, keepOpened } = button;
                const modalButton = document.createElement("button");
                if (cssClass === "confirm") {
                    modalButton.setAttribute("type", "submit");
                }
                if (autofocus) {
                    modalButton.setAttribute("autofocus", "");
                }
                modalButton.setAttribute("tabindex", "0");
                modalButton.classList.add("modal__button");
                modalButton.innerText = value;
                modalButton.addEventListener("click", (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    if (onClick) {
                        onClick(this);
                    }
                    if (!keepOpened) {
                        this.close();
                    }
                });
                const suffix = button.cssClass || "default";
                modalButton.classList.add(`modal__button--${suffix}`);
                this.modalButtons.appendChild(modalButton);
            });
        });
        _EdenModal_handleKeyPress.set(this, (e) => {
            if (e.key !== "Escape")
                return;
            const allModals = document.querySelectorAll("eden-modal");
            const isLastModal = allModals[allModals.length - 1];
            if (this !== isLastModal)
                return;
            this.close();
        });
        _EdenModal_focusModal.set(this, () => {
            const activeElement = document.activeElement;
            if (activeElement) {
                activeElement.blur();
            }
            const hasAutofocusElement = Boolean(this.shadowRoot.querySelector("[autofocus]"));
            if (!hasAutofocusElement) {
                let elementToFocus = this.shadowRoot.querySelector("[autofocus]");
                if (!elementToFocus) {
                    [elementToFocus] = Array.from(this.shadowRoot.querySelectorAll(FOCUSABLE_ELEMENTS));
                }
                if (elementToFocus) {
                    elementToFocus.focus();
                }
            }
        });
        _EdenModal_handleFocus.set(this, (e) => {
            const event = e;
            const isTabPressed = event.key === "Tab" || event.keyCode === 9;
            if (!isTabPressed)
                return;
            if (event.shiftKey) {
                if (this.shadowRoot.activeElement === this.firstFocusableElement) {
                    this.lastFocusableElement.focus();
                    event.preventDefault();
                }
            }
            else {
                if (this.shadowRoot.activeElement === this.lastFocusableElement) {
                    this.firstFocusableElement.focus();
                    event.preventDefault();
                }
            }
        });
        this.defaults = {
            id: undefined,
            width: undefined,
            height: undefined,
            icon: undefined,
            title: "",
            content: "",
            buttons: [],
            backdrop: false,
            closeButton: true,
            onClose: undefined,
            noPadding: false,
            fullScreen: false,
        };
        this.options = Object.assign({}, this.defaults, options);
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = template();
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(styles);
        this.shadowRoot.adoptedStyleSheets = [sheet];
    }
    connectedCallback() {
        this.modal = this.shadowRoot.querySelector(".modal");
        this.closeButton = this.shadowRoot.querySelector(".modal__close-button");
        this.backdrop = this.shadowRoot.querySelector(".backdrop");
        this.modalTitle = this.shadowRoot.querySelector(".modal__title");
        this.modalContent = this.shadowRoot.querySelector(".modal__content");
        this.modalButtons = this.shadowRoot.querySelector(".modal__buttons");
        document.body.style.overflow = "hidden";
        __classPrivateFieldGet(this, _EdenModal_renderModalContent, "f").call(this);
        this.focusableContent = Array.from(this.shadowRoot.querySelectorAll(FOCUSABLE_ELEMENTS));
        this.firstFocusableElement = this.focusableContent[0];
        this.lastFocusableElement =
            this.focusableContent[this.focusableContent.length - 1];
        this.options.closeButton
            ? this.closeButton.addEventListener("click", this.close)
            : this.closeButton.remove();
        if (this.options.backdrop) {
            this.backdrop.addEventListener("click", this.close);
        }
        document.addEventListener("keydown", __classPrivateFieldGet(this, _EdenModal_handleKeyPress, "f"));
        this.shadowRoot.addEventListener("keydown", __classPrivateFieldGet(this, _EdenModal_handleFocus, "f"));
        __classPrivateFieldGet(this, _EdenModal_focusModal, "f").call(this);
    }
    disconnectedCallback() {
        this.shadowRoot.removeEventListener("keydown", __classPrivateFieldGet(this, _EdenModal_handleFocus, "f"));
        document.removeEventListener("keydown", __classPrivateFieldGet(this, _EdenModal_handleKeyPress, "f"));
        if (this.options.backdrop) {
            this.backdrop.removeEventListener("click", this.close);
        }
        if (this.options.closeButton) {
            this.closeButton.removeEventListener("click", this.close);
        }
        const otherModals = document.querySelectorAll("eden-modal");
        if (otherModals.length === 0) {
            document.body.removeAttribute("style");
        }
    }
}
_EdenModal_renderModalContent = new WeakMap(), _EdenModal_renderModalButtons = new WeakMap(), _EdenModal_handleKeyPress = new WeakMap(), _EdenModal_focusModal = new WeakMap(), _EdenModal_handleFocus = new WeakMap();
export default EdenModal;
if (!customElements.get("eden-modal")) {
    customElements.define("eden-modal", EdenModal);
}
