import { EdenEvents, fireEvent } from "../../services/event.js";
import { smoothScrollTo } from "../../services/util.js";
import { getViewTransitionDuration, removeViewTransitionStyles, setViewTransitionStyles, } from "./transitions.js";
export async function createBlockAtPosition(block, position, code, variant) {
    if (!block.editor) {
        return;
    }
    const created = await block.editor.createBlock(code, variant);
    if (!created) {
        return;
    }
    if ("startViewTransition" in document) {
        setViewTransitionStyles();
        document.startViewTransition(() => {
            block.element.insertAdjacentElement(position, created.element);
            created.showUi();
            const delay = getViewTransitionDuration() + 40;
            setTimeout(() => {
                smoothScrollTo(created.element);
            }, delay);
        });
        removeViewTransitionStyles();
    }
    else {
        block.element.insertAdjacentElement(position, created.element);
        created.showUi();
        smoothScrollTo(created.element);
    }
    if (created.editor) {
        fireEvent(document, EdenEvents.blockCreated, {
            block: created,
            editor: created.editor,
        });
    }
}
export function removeBlockFromEditor(block) {
    if (!block.editor) {
        return;
    }
    fireEvent(document, EdenEvents.blockRemoved, {
        block,
        editor: block.editor,
    });
    if ("startViewTransition" in document) {
        setViewTransitionStyles();
        document.startViewTransition(() => {
            block.element.remove();
        });
        removeViewTransitionStyles();
    }
    else {
        block.element.remove();
    }
    block.editor.blocks =
        block.editor.blocks?.filter((existing) => existing !== block) || [];
    block.editor.showUi();
}
export function moveBlockRelative(block, position) {
    const sibling = position === "beforebegin"
        ? block.element.previousElementSibling
        : block.element.nextElementSibling;
    if (sibling) {
        block.hideUi();
        if ("startViewTransition" in document) {
            setViewTransitionStyles();
            document.startViewTransition(() => {
                sibling.insertAdjacentElement(position, block.element);
                block.showUi();
                const delay = getViewTransitionDuration() + 40;
                setTimeout(() => {
                    smoothScrollTo(block.element);
                }, delay);
            });
            removeViewTransitionStyles();
        }
        else {
            sibling.insertAdjacentElement(position, block.element);
            block.showUi();
            smoothScrollTo(block.element);
        }
    }
}
