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 {
    mountStory,
    nextFrame,
    page,
    preparePreviewEditor,
    scrollEditorTo,
} from "../../_setup/e2e-helpers";
import { md } from "../../_setup/markdown-classes";

const Stories = composeStories(MarkdownStories);

describe("MarkdownEditor / table cell click", () => {
    it("places the caret in the source cell when a rendered cell is clicked", async () => {
        mountStory(<Stories.Editor />);
        const view = await preparePreviewEditor();
        const doc = view.state.doc.toString();

        const tablePos = doc.indexOf("| Feature |");
        expect(tablePos).toBeGreaterThan(-1);
        await scrollEditorTo(view, tablePos);

        // Park the caret far away so the table renders as a widget.
        view.dispatch({ selection: EditorSelection.cursor(0) });
        await nextFrame();
        await nextFrame();

        const widget = document.querySelector(`.${md.tableWidget}`);
        expect(widget).not.toBeNull();

        // Click the "Headers" body cell.
        const cell = page.getByText("Headers", { exact: true });
        await cell.click();
        await nextFrame();

        // The caret should land on the "Headers" cell inside the table source.
        const expected = doc.indexOf("Headers", tablePos);
        expect(view.state.selection.main.head).toBe(expected);

        // Clicking activates the block, revealing the raw source (widget gone).
        await nextFrame();
        expect(document.querySelector(`.${md.tableWidget}`)).toBeNull();
    });
});
