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 } from "../../_setup/e2e-helpers";

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

async function caretAt(doc: string, index: number) {
    mountStory(shell(doc));
    const view = await getEditorView();
    view.focus();
    view.dispatch({
        selection: EditorSelection.cursor(index),
        effects: setMarkdownEditorFocused.of(true),
    });
    await nextFrame();
    await nextFrame();
    return view;
}

describe("MarkdownEditor / link placeholders", () => {
    it("shows an 'alt text' placeholder for an empty link label", async () => {
        const doc = "[](https://surrealdb.com)";
        await caretAt(doc, 1); // caret between the empty []
        expect(document.querySelector(".cm-content")?.textContent).toContain("alt text");
    });

    it("shows a 'link' placeholder for an empty link destination", async () => {
        const doc = "[label]()";
        await caretAt(doc, doc.indexOf("(") + 1); // caret between the empty ()
        const text = document.querySelector(".cm-content")?.textContent ?? "";
        expect(text).toContain("link");
    });

    it("shows both placeholders for a fully empty link", async () => {
        const doc = "[]()";
        await caretAt(doc, 1);
        const text = document.querySelector(".cm-content")?.textContent ?? "";
        expect(text).toContain("alt text");
        expect(text).toContain("link");
    });

    it("does not show placeholders once the sections have content", async () => {
        const doc = "[label](https://surrealdb.com)";
        await caretAt(doc, 3);
        expect(document.querySelector(".cm-content")?.textContent).not.toContain("alt text");
    });
});
