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 {
    focusEditor,
    getEditorView,
    mountStory,
    nextFrame,
    userEvent,
} from "../../_setup/e2e-helpers";

const Stories = composeStories(MarkdownStories);

describe("MarkdownEditor / table formatter", () => {
    it("realigns the table columns after typing in a cell", async () => {
        mountStory(<Stories.EditorTableFormatter />);
        const view = await getEditorView();
        await nextFrame();

        const doc = view.state.doc.toString();
        const target = doc.indexOf("Ada") + "Ada".length;
        expect(target).toBeGreaterThan(0);

        view.dispatch({ selection: EditorSelection.cursor(target) });
        await focusEditor();
        await userEvent.keyboard("lyn"); // "Ada" -> "Adalyn"
        await nextFrame();
        await nextFrame();

        const next = view.state.doc.toString();
        // Column 1 grew to fit "Adalyn"; the delimiter row should align to it.
        expect(next).toContain("Adalyn");
        const lines = next.split("\n");
        const widths = lines
            .filter((l) => l.includes("|"))
            .map((l) => l.indexOf("|", l.indexOf("|") + 1));
        // All rows share the same position for the second pipe (aligned column 1).
        expect(new Set(widths).size).toBe(1);
    });
});
