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 _EdenBlockUi_addBefore, _EdenBlockUi_addAfter, _EdenBlockUi_moveBefore, _EdenBlockUi_moveAfter, _EdenBlockUi_delete, _EdenBlockUi_selectDates, _EdenBlockUi_duplicate, _EdenBlockUi_copy, _EdenBlockUi_settings, _EdenBlockUi_toggleCopyDropdown, _EdenBlockUi_closeCopyDropdown, _EdenBlockUi_closeVariantsDropdown, _EdenBlockUi_toggleVariantsDropdown, _EdenBlockUi_openObsoletePopup, _EdenBlockUi_updateSettingsIcon, _EdenBlockUi_removeBlock;
import EdenDropdown from "../common/eden-dropdown.js";
import EdenModal from "../common/eden-modal.js";
import EdenAddBlock from "./eden-add-block.js";
import template, { obsoleteTemplate } from "./eden-block-ui.template.js";
import styles, { obsoleteStyles } from "./eden-block-ui.styles.js";
import { isContentNotValidForPaste } from "../../services/clipboard.js";
import EdenToolbar from "./eden-toolbar.js";
import { EdenEvents, fireEvent } from "../../services/event.js";
import html, { htmlStringToElement } from "../../services/html.js";
import t from "../../i18n/index.js";
class EdenBlockUi extends HTMLElement {
    constructor(block, callbacks, disabledActions, templates, maxBlocks, obsolete, variant, variants) {
        super();
        this.copyDropdown = null;
        this.variantsDropdown = null;
        _EdenBlockUi_addBefore.set(this, async (e) => {
            this.hidePaste = await isContentNotValidForPaste(this.editor);
            if (this.hidePaste && this.templates?.length === 1) {
                this.callbacks.addBefore(this.templates[0]);
            }
            else {
                document.body.append(new EdenAddBlock(e, {
                    addBlock: this.callbacks.addBefore,
                    paste: this.callbacks.pasteBefore,
                }, this.templates, this.hidePaste));
            }
        });
        _EdenBlockUi_addAfter.set(this, async (e) => {
            this.hidePaste = await isContentNotValidForPaste(this.editor);
            if (this.hidePaste && this.templates?.length === 1) {
                this.callbacks.addAfter(this.templates[0]);
            }
            else {
                document.body.append(new EdenAddBlock(e, {
                    addBlock: this.callbacks.addAfter,
                    paste: this.callbacks.pasteAfter,
                }, this.templates, this.hidePaste));
            }
        });
        _EdenBlockUi_moveBefore.set(this, (e) => {
            e.preventDefault();
            this.callbacks.moveBefore();
        });
        _EdenBlockUi_moveAfter.set(this, (e) => {
            e.preventDefault();
            this.callbacks.moveAfter();
        });
        _EdenBlockUi_delete.set(this, (e) => {
            e?.preventDefault();
            document.body.append(new EdenModal({
                icon: "delete",
                title: t("ui.block-ui.remove-block"),
                content: t("ui.block-ui.removal-confirmation"),
                buttons: [
                    { value: t("common.cancel"), cssClass: "cancel" },
                    {
                        value: t("common.remove"),
                        onClick: this.callbacks.remove,
                        cssClass: "confirm",
                        autofocus: true,
                    },
                ],
                closeButton: false,
            }));
        });
        _EdenBlockUi_selectDates.set(this, () => {
            this.callbacks.selectDates();
        });
        _EdenBlockUi_duplicate.set(this, (e) => {
            e.stopPropagation();
            e.preventDefault();
            this.callbacks.duplicate();
        });
        _EdenBlockUi_copy.set(this, (e) => {
            e.preventDefault();
            __classPrivateFieldGet(this, _EdenBlockUi_toggleCopyDropdown, "f").call(this);
        });
        _EdenBlockUi_settings.set(this, (e) => {
            e.preventDefault();
            const isShiftPressed = e.shiftKey;
            if (this.variants && isShiftPressed) {
                __classPrivateFieldGet(this, _EdenBlockUi_toggleVariantsDropdown, "f").call(this);
            }
            else {
                __classPrivateFieldGet(this, _EdenBlockUi_closeVariantsDropdown, "f").call(this);
                this.callbacks.settings();
            }
        });
        _EdenBlockUi_toggleCopyDropdown.set(this, () => {
            if (!this.copyDropdown) {
                const baseButtons = [
                    {
                        icon: "copy",
                        text: t("ui.block-ui.copy-block"),
                        onClick: this.callbacks.copy,
                    },
                    {
                        icon: "cut",
                        text: t("ui.block-ui.cut-block"),
                        onClick: this.callbacks.cut,
                    },
                    {
                        icon: "copy",
                        text: t("ui.block-ui.copy-block-group"),
                        onClick: this.callbacks.copyEditor,
                    },
                ];
                const buttons = this.canSelectDate
                    ? [
                        ...baseButtons,
                        {
                            icon: "calendar_copy",
                            text: t("ui.block-ui.copy-dates"),
                            onClick: this.callbacks.copyDates,
                        },
                    ]
                    : baseButtons;
                this.copyDropdown = new EdenDropdown(this.copyButton, buttons, __classPrivateFieldGet(this, _EdenBlockUi_closeCopyDropdown, "f"));
                const dropdown = this.copyDropdown;
                window.requestAnimationFrame(() => {
                    if (!dropdown || dropdown !== this.copyDropdown)
                        return;
                    document.body.appendChild(dropdown);
                });
            }
            else {
                __classPrivateFieldGet(this, _EdenBlockUi_closeCopyDropdown, "f").call(this);
            }
        });
        _EdenBlockUi_closeCopyDropdown.set(this, () => {
            if (this.copyDropdown) {
                this.copyDropdown.remove();
                this.copyDropdown = null;
            }
        });
        _EdenBlockUi_closeVariantsDropdown.set(this, () => {
            if (this.variantsDropdown) {
                this.variantsDropdown.remove();
                this.variantsDropdown = null;
            }
        });
        _EdenBlockUi_toggleVariantsDropdown.set(this, () => {
            if (!this.variants)
                return;
            if (!this.variantsDropdown) {
                const options = this.variants.map((v) => {
                    const { name, cssClass } = v;
                    const isSelected = this.variant === cssClass;
                    const toggleVariant = (e) => {
                        e.stopPropagation();
                        const newVariant = isSelected ? undefined : cssClass;
                        this.callbacks.updateVariant(newVariant);
                        __classPrivateFieldGet(this, _EdenBlockUi_toggleVariantsDropdown, "f").call(this);
                    };
                    return {
                        text: name,
                        current: isSelected,
                        onClick: toggleVariant,
                    };
                });
                this.variantsDropdown = new EdenDropdown(this.settingsButton, options, __classPrivateFieldGet(this, _EdenBlockUi_closeVariantsDropdown, "f"));
                const dropdown = this.variantsDropdown;
                window.requestAnimationFrame(() => {
                    if (!dropdown || dropdown !== this.variantsDropdown)
                        return;
                    document.body.appendChild(dropdown);
                });
            }
            else {
                __classPrivateFieldGet(this, _EdenBlockUi_closeVariantsDropdown, "f").call(this);
            }
        });
        _EdenBlockUi_openObsoletePopup.set(this, () => {
            document.body.prepend(new EdenModal({
                icon: "information",
                title: t("ui.block-ui.obsolete-block-title"),
                content: html ` <div style="max-width: 420px; line-height: 1.55em;">
          ${t("ui.block-ui.obsolete-description")}
        </div>`,
                buttons: [
                    { value: t("common.close"), cssClass: "cancel" },
                    {
                        value: t("common.remove"),
                        onClick: this.callbacks.remove,
                        cssClass: "confirm",
                        autofocus: true,
                    },
                ],
                closeButton: false,
            }));
        });
        _EdenBlockUi_updateSettingsIcon.set(this, (e) => {
            if (this.settingsButton && this.variants) {
                const isShiftPressed = e.shiftKey;
                const icon = this.settingsButton.querySelector(".action__icon");
                if (!icon)
                    return;
                const code = isShiftPressed ? "list" : "tune";
                icon.setAttribute("code", code);
            }
        });
        _EdenBlockUi_removeBlock.set(this, (e) => {
            if (e.key === "Delete") {
                const documentHasOpenedModal = Boolean(document.querySelector("eden-modal"));
                const isManipulatingField = document.activeElement?.closest("input, textarea");
                const isManipulatingContentEditable = document.activeElement?.hasAttribute("contenteditable");
                const preventRemove = documentHasOpenedModal ||
                    isManipulatingField ||
                    isManipulatingContentEditable;
                if (preventRemove)
                    return;
                __classPrivateFieldGet(this, _EdenBlockUi_delete, "f").call(this);
            }
        });
        this.addToolbars = (toolbars) => {
            toolbars.forEach(({ toolbar, watchSelectionChange }) => {
                const toolbarUi = new EdenToolbar(watchSelectionChange);
                toolbar.ui = toolbarUi;
                const buttons = toolbar.map((action) => {
                    const buttonStr = html `
          <button is="eden-button" class="option option__edit">
            <eden-icon code="${action.icon}" class="option__icon"></eden-icon>
          </button>
        `;
                    const button = htmlStringToElement(buttonStr);
                    if (action.tooltip) {
                        button.setAttribute("tooltip", action.tooltip);
                    }
                    if (action.command) {
                        button.setAttribute("data-command", action.command);
                    }
                    if (action.dropdown === true) {
                        button.setAttribute("data-dropdown", "");
                    }
                    if (Array.isArray(action.action)) {
                        const commands = action.action
                            .map((action) => {
                            return action.value || action.name;
                        })
                            .join(",");
                        button.setAttribute("data-dropdown", commands);
                        const newDropdown = new EdenDropdown(button, action.action.map((action) => {
                            const onClick = (e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                action.action(e);
                                fireEvent(document, EdenEvents.textFormatted);
                            };
                            return {
                                onClick,
                                icon: action.icon,
                                property: action.property,
                                text: action.name,
                                value: action.value,
                                formatter: action.formatter,
                                current: action.current,
                                disabled: action.disabled,
                            };
                        }), () => newDropdown.remove(), watchSelectionChange);
                        const dropdownId = `dropdown-${Math.random()
                            .toString(36)
                            .substring(2, 9)}`;
                        newDropdown.setAttribute("id", dropdownId);
                        button.addEventListener("click", (e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            const existingDropdown = document.getElementById(dropdownId);
                            if (!existingDropdown) {
                                button.setAttribute("data-open", "");
                                document.body.appendChild(newDropdown);
                            }
                            else {
                                button.removeAttribute("data-open");
                                existingDropdown.remove();
                            }
                        });
                    }
                    else {
                        const onClick = (e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            const mouseEvent = e;
                            if (typeof action.action === "function") {
                                action.action(mouseEvent);
                            }
                            fireEvent(document, EdenEvents.textFormatted);
                        };
                        button.addEventListener("click", onClick);
                    }
                    return button;
                });
                toolbarUi.addButtons(buttons);
                if (buttons.length > 1) {
                    toolbarUi.classList.add("multiple");
                }
                const toolbars = this.shadowRoot.querySelector(".toolbars");
                if (toolbars) {
                    toolbars.appendChild(toolbarUi);
                }
            });
        };
        this.removeActions = (toolbars) => {
            toolbars.forEach((toolbar) => {
                if (toolbar.ui) {
                    toolbar.ui.remove();
                }
            });
        };
        const { timeProgrammableBlocks } = window.EdenConfig;
        this.block = block;
        this.editor = this.block.editor;
        this.canSelectDate = checkDateSelection(timeProgrammableBlocks);
        this.obsolete = obsolete;
        this.callbacks = callbacks;
        this.templates = templates;
        this.maxBlocks = maxBlocks;
        this.disabledActions = disabledActions;
        this.variant = variant;
        this.variants = variants;
        const user = window.Eden.user;
        this.isAdmin = user?.roles?.includes("eden_admin");
        this.isSuperAdmin = user?.email === "mail@jeantinland.com";
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = this.obsolete
            ? obsoleteTemplate()
            : template(this.canSelectDate);
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(this.obsolete ? obsoleteStyles : styles);
        this.shadowRoot.adoptedStyleSheets = [sheet];
    }
    connectedCallback() {
        if (this.obsolete) {
            this.obsoleteInfoButton = this.shadowRoot.querySelector(".info-button");
            this.obsoleteRemoveButton =
                this.shadowRoot.querySelector(".remove-button");
            this.obsoleteInfoButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_openObsoletePopup, "f"));
            this.obsoleteRemoveButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_delete, "f"));
        }
        else {
            this.addBeforeButton = this.shadowRoot.querySelector(".action--add-before");
            this.addAfterButton =
                this.shadowRoot.querySelector(".action--add-after");
            this.moveBeforeButton = this.shadowRoot.querySelector(".action--move-before");
            this.moveAfterButton = this.shadowRoot.querySelector(".action--move-after");
            this.selectWeeksButton = this.shadowRoot.querySelector(".action--select-weeks");
            this.duplicateButton =
                this.shadowRoot.querySelector(".action--duplicate");
            this.copyButton = this.shadowRoot.querySelector(".action--copy");
            this.deleteButton = this.shadowRoot.querySelector(".action--delete");
            this.settingsButton = this.shadowRoot.querySelector(".action--settings");
            if (this.disabledActions.includes("add")) {
                this.addBeforeButton.setAttribute("disabled", "");
                this.addAfterButton.setAttribute("disabled", "");
                this.duplicateButton.setAttribute("disabled", "");
            }
            else {
                this.addBeforeButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_addBefore, "f"));
                this.addAfterButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_addAfter, "f"));
                this.duplicateButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_duplicate, "f"));
            }
            if (this.disabledActions.includes("moveBefore")) {
                this.moveBeforeButton.setAttribute("disabled", "");
            }
            else {
                this.moveBeforeButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_moveBefore, "f"));
            }
            if (this.disabledActions.includes("moveAfter")) {
                this.moveAfterButton.setAttribute("disabled", "");
            }
            else {
                this.moveAfterButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_moveAfter, "f"));
            }
            if (this.canSelectDate && this.selectWeeksButton) {
                this.selectWeeksButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_selectDates, "f"));
            }
            window.addEventListener("keydown", __classPrivateFieldGet(this, _EdenBlockUi_updateSettingsIcon, "f"));
            window.addEventListener("keyup", __classPrivateFieldGet(this, _EdenBlockUi_updateSettingsIcon, "f"));
            window.addEventListener("keydown", __classPrivateFieldGet(this, _EdenBlockUi_removeBlock, "f"));
            this.copyButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_copy, "f"));
            this.deleteButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_delete, "f"));
            this.settingsButton.addEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_settings, "f"));
        }
    }
    disconnectedCallback() {
        __classPrivateFieldGet(this, _EdenBlockUi_closeCopyDropdown, "f").call(this);
        __classPrivateFieldGet(this, _EdenBlockUi_closeVariantsDropdown, "f").call(this);
        if (this.obsolete) {
            this.obsoleteRemoveButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_delete, "f"));
            this.obsoleteInfoButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_openObsoletePopup, "f"));
        }
        else {
            this.settingsButton &&
                this.settingsButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_settings, "f"));
            this.deleteButton &&
                this.deleteButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_delete, "f"));
            this.copyButton &&
                this.copyButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_copy, "f"));
            window.removeEventListener("keydown", __classPrivateFieldGet(this, _EdenBlockUi_removeBlock, "f"));
            window.removeEventListener("keyup", __classPrivateFieldGet(this, _EdenBlockUi_updateSettingsIcon, "f"));
            window.removeEventListener("keydown", __classPrivateFieldGet(this, _EdenBlockUi_updateSettingsIcon, "f"));
            if (this.canSelectDate && this.selectWeeksButton) {
                this.selectWeeksButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_selectDates, "f"));
            }
            if (!this.disabledActions.includes("moveAfter")) {
                this.moveAfterButton &&
                    this.moveAfterButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_moveAfter, "f"));
            }
            if (!this.disabledActions.includes("moveBefore")) {
                this.moveBeforeButton &&
                    this.moveBeforeButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_moveBefore, "f"));
            }
            if (!this.disabledActions.includes("add")) {
                this.duplicateButton &&
                    this.duplicateButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_duplicate, "f"));
                this.addAfterButton &&
                    this.addAfterButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_addAfter, "f"));
                this.addBeforeButton &&
                    this.addBeforeButton.removeEventListener("click", __classPrivateFieldGet(this, _EdenBlockUi_addBefore, "f"));
            }
        }
    }
}
_EdenBlockUi_addBefore = new WeakMap(), _EdenBlockUi_addAfter = new WeakMap(), _EdenBlockUi_moveBefore = new WeakMap(), _EdenBlockUi_moveAfter = new WeakMap(), _EdenBlockUi_delete = new WeakMap(), _EdenBlockUi_selectDates = new WeakMap(), _EdenBlockUi_duplicate = new WeakMap(), _EdenBlockUi_copy = new WeakMap(), _EdenBlockUi_settings = new WeakMap(), _EdenBlockUi_toggleCopyDropdown = new WeakMap(), _EdenBlockUi_closeCopyDropdown = new WeakMap(), _EdenBlockUi_closeVariantsDropdown = new WeakMap(), _EdenBlockUi_toggleVariantsDropdown = new WeakMap(), _EdenBlockUi_openObsoletePopup = new WeakMap(), _EdenBlockUi_updateSettingsIcon = new WeakMap(), _EdenBlockUi_removeBlock = new WeakMap();
export default EdenBlockUi;
if (!customElements.get("eden-block-ui")) {
    customElements.define("eden-block-ui", EdenBlockUi);
}
function checkDateSelection(config) {
    if (!config || config.enabled !== true)
        return false;
    if (config.paths) {
        const currentPath = window.location.pathname;
        const canSelectDate = config.paths.some((path) => {
            const pathStartsWith = path.endsWith("*");
            const pathEndsWith = path.startsWith("*");
            const cleanPath = path.replace(/\*/g, "");
            if (pathStartsWith && pathEndsWith) {
                return currentPath.includes(cleanPath);
            }
            if (pathStartsWith) {
                return currentPath.startsWith(cleanPath);
            }
            if (pathEndsWith) {
                return currentPath.endsWith(cleanPath);
            }
            return currentPath === path;
        });
        return canSelectDate;
    }
    return true;
}
