import { EdenEvents, fireEvent } from "../../services/event.js";
import { getRuntimeEden } from "../../services/runtime.js";
export async function showBlockUi(block, e) {
    const activeBlock = getRuntimeEden().getActiveBlock();
    if (block.editor && block.editor.isFixed) {
        block.editor.element.setAttribute("data-eden-modified", "true");
    }
    if (block.obsolete && e) {
        e.preventDefault();
    }
    if (activeBlock === block) {
        return;
    }
    if (activeBlock !== undefined) {
        activeBlock.hideUi();
    }
    getRuntimeEden().setActiveBlock(block);
    fireEvent(document, EdenEvents.activeBlockChanged, { block });
    const disabledActions = [];
    if (!block.editor?.canAddBlock()) {
        disabledActions.push("add");
    }
    if (block.isFirstChild()) {
        disabledActions.push("moveBefore");
    }
    if (block.isLastChild()) {
        disabledActions.push("moveAfter");
    }
    const { default: EdenBlockUi } = await import("../../user-interface/block/eden-block-ui.js");
    block.ui = new EdenBlockUi(block, {
        addBefore: block.createBefore,
        addAfter: block.createAfter,
        remove: block.remove,
        copy: block.copyBlock,
        cut: block.cutBlock,
        copyEditor: block.copyEditor,
        copyDates: block.copyDates,
        pasteBefore: block.pasteBefore,
        pasteAfter: block.pasteAfter,
        moveBefore: block.moveBefore,
        moveAfter: block.moveAfter,
        duplicate: block.duplicate,
        selectDates: block.selectDates,
        settings: block.settings,
        updateVariant: block.updateVariant,
    }, disabledActions, block.editor?.templates, block.editor?.maxBlocks, block.obsolete, block.variant, block.template?.variants);
    if (block.initialPosition !== "relative") {
        block.element.style.position = "relative";
    }
    document.addEventListener("click", block.handleOutsideClick);
    patchDetails(block.element);
    block.addToolbars();
    block.element.appendChild(block.ui);
    getRuntimeEden().editors.forEach((editor) => {
        if (editor.blocks && editor.blocks.length > 0) {
            editor.hideUi();
        }
    });
}
export function hideBlockUi(block) {
    const activeBlock = getRuntimeEden().getActiveBlock();
    if (activeBlock === block) {
        getRuntimeEden().setActiveBlock(undefined);
        block.ui?.remove();
        delete block.ui;
        block.activePlugins = [];
        if (block.initialPosition && block.initialPosition !== "relative") {
            block.element.style.position = block.initialPosition;
        }
        cleanupDetailsPatch(block.element);
        block.element.style.removeProperty("z-index");
        document.removeEventListener("click", block.handleOutsideClick);
        fireEvent(document, EdenEvents.activeBlockChanged, { block: undefined });
        if (block.contentHasChanged) {
            fireEvent(document, EdenEvents.blockContentChanged, {
                block,
                content: block.element.innerHTML,
            });
        }
    }
}
export async function manageBlockActions(block, pluginsToActivate) {
    await block.showUi();
    const toRemove = block.activePlugins?.filter((activePlugin) => !pluginsToActivate.includes(activePlugin));
    const toAdd = pluginsToActivate.filter((plugin) => !block.activePlugins?.includes(plugin));
    const actionsGroupsToRemove = toRemove?.map((plugin) => plugin.actions);
    block.removeActions(actionsGroupsToRemove);
    const actionsGroupsToAdd = toAdd.map((plugin) => ({
        toolbar: plugin.actions,
        watchSelectionChange: Boolean(plugin.watchSelectionChange),
    }));
    if (actionsGroupsToAdd) {
        block.addActions(actionsGroupsToAdd);
    }
    block.activePlugins = pluginsToActivate;
}
export function handleOutsideBlockClick(block, e) {
    const target = e.target;
    const ignoreClick = target.closest("eden-icon-dropdown, eden-add-block, eden-dropdown, eden-modal");
    const isAnchorClick = target.closest("a");
    const activeBlock = getRuntimeEden().getActiveBlock();
    const selection = window.getSelection();
    if (!selection) {
        return;
    }
    const isSelecting = selection.type === "Range";
    if (!isAnchorClick &&
        (ignoreClick ||
            !activeBlock ||
            activeBlock.element?.contains(target) ||
            isSelecting)) {
        return;
    }
    hideBlockUi(block);
    getRuntimeEden().editors.forEach((editor) => editor.showUi());
}
export async function showBlockHelper(block, e) {
    const currentMode = document.documentElement.getAttribute("data-eden-mode");
    if (currentMode !== "info") {
        return hideBlockHelper(block);
    }
    const target = e.target;
    const hoveredBlock = target.closest("section");
    if (!hoveredBlock) {
        return;
    }
    const { clientX, clientY } = e;
    if (!block.helper) {
        const { default: EdenHelper } = await import("../../user-interface/common/eden-helper.js");
        block.helper = new EdenHelper(hoveredBlock);
        document.body.appendChild(block.helper);
    }
    const helperWidth = block.helper.getBoundingClientRect().width;
    const hasEnoughPlace = clientX + helperWidth < window.innerWidth;
    let transform = `translate(${clientX + 14}px, ${clientY - 10}px)`;
    if (!hasEnoughPlace) {
        transform = `translate(${clientX - helperWidth - 14}px, ${clientY - 10}px)`;
    }
    block.helper.style.transform = transform;
}
export function hideBlockHelper(block) {
    if (block.helper) {
        block.helper.remove();
        block.helper = undefined;
    }
}
function toggleDetails(e) {
    e.preventDefault();
    const target = e.target;
    const details = target.closest("details");
    if (!details) {
        return;
    }
    const open = details.hasAttribute("open");
    if (open) {
        details.removeAttribute("open");
    }
    else {
        details.setAttribute("open", "");
    }
}
function patchDetails(root) {
    const details = Array.from(root.querySelectorAll("a details"));
    details.forEach((detail) => detail.addEventListener("click", toggleDetails));
}
function cleanupDetailsPatch(root) {
    const details = Array.from(root.querySelectorAll("a details"));
    details.forEach((detail) => {
        detail.removeEventListener("click", toggleDetails);
    });
}
