import { redo, undo } from "@codemirror/commands";
import { EditorSelection } from "@codemirror/state";
import * as MarkdownStories from "@src/stories/playground/Markdown.stories";
import { composeStories } from "@storybook/react-vite";
import { describe, expect, it } from "vitest";
import { getEditorView, mountStory, nextFrame } from "../../_setup/e2e-helpers";

const Stories = composeStories(MarkdownStories);

describe("MarkdownEditor / undo and redo", () => {
    it("restores undone document edits via redo", async () => {
        mountStory(<Stories.Editor />);
        const view = await getEditorView();

        const start = Date.now();
        while (view.state.doc.length === 0 && Date.now() - start < 5000) {
            await nextFrame();
        }
        expect(view.state.doc.length).toBeGreaterThan(0);

        const before = view.state.doc.toString();

        view.dispatch({
            changes: { from: view.state.doc.length, insert: "\nredo-marker" },
            selection: EditorSelection.cursor(view.state.doc.length),
        });
        await nextFrame();

        const afterEdit = view.state.doc.toString();
        expect(afterEdit).toContain("redo-marker");

        expect(undo(view)).toBe(true);
        expect(view.state.doc.toString()).toBe(before);

        expect(redo(view)).toBe(true);
        expect(view.state.doc.toString()).toBe(afterEdit);
    });
});
