import { EditorSelection } from "@codemirror/state";
import { MantineProvider, Paper, v8CssVariablesResolver } from "@mantine/core";
import { setMarkdownEditorFocused } from "@src/lib/markdown/editor/decorations/editor-focus";
import { MarkdownEditor } from "@src/primitives/MarkdownEditor";
import { MANTINE_THEME } from "@src/theme/mantine";
import { describe, expect, it } from "vitest";
import { getEditorView, mountStory, nextFrame, sleep } from "../../_setup/e2e-helpers";

const IMAGE_DOC = "![A logo](https://surrealdb.com/static/logo/light.svg)\n\nParagraph after.\n";

function shell(doc: string) {
    return (
        <MantineProvider
            theme={MANTINE_THEME}
            cssVariablesResolver={v8CssVariablesResolver}
            forceColorScheme="dark"
        >
            <Paper
                p="md"
                withBorder
            >
                <MarkdownEditor
                    mode="preview"
                    document={doc}
                    autoFocus={false}
                />
            </Paper>
        </MantineProvider>
    );
}

describe("MarkdownEditor / media edit action", () => {
    it("shows an image preview with an edit-source action that reveals the source", async () => {
        mountStory(shell(IMAGE_DOC));
        const view = await getEditorView();

        // Focused, with the caret away from the image, so the image renders as a
        // preview widget rather than raw source.
        view.focus();
        view.dispatch({
            selection: EditorSelection.cursor(view.state.doc.length),
            effects: setMarkdownEditorFocused.of(true),
        });
        await nextFrame();
        await nextFrame();

        expect(document.querySelector(".cm-content")?.textContent).not.toContain("![A logo]");
        expect(document.querySelector("img")).not.toBeNull();

        const action = document.querySelector<HTMLButtonElement>(
            'button[aria-label="Edit source"]',
        );
        expect(action).not.toBeNull();

        action?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));
        await sleep(120);
        await nextFrame();

        // The image markdown source becomes visible and is selected.
        expect(document.querySelector(".cm-content")?.textContent).toContain("![A logo]");
        expect(view.state.selection.main.empty).toBe(false);
    });
});
