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";
import { md } from "../../_setup/markdown-classes";

const Stories = composeStories(MarkdownStories);

describe("MarkdownEditor / heading folds", () => {
    it("MarkdownViewer: heading fold control collapses the first section", async () => {
        mountStory(<Stories.Viewer />);
        await nextFrame();
        await nextFrame();

        const folds = document.querySelectorAll<HTMLButtonElement>(
            `.${md.headingFold}[data-level="1"]`,
        );
        expect(folds.length).toBeGreaterThan(0);

        const h1Fold = folds[0];
        if (!h1Fold) throw new Error("expected an H1 fold control");

        expect(h1Fold.getAttribute("data-folded")).toBe("false");
        expect(h1Fold.getAttribute("aria-label")).toBe("Collapse section");

        h1Fold.click();
        await nextFrame();
        await nextFrame();

        const folded = document.querySelector<HTMLButtonElement>(
            `.${md.headingFold}[data-level="1"]`,
        );
        expect(folded?.getAttribute("data-folded")).toBe("true");
        expect(folded?.getAttribute("aria-label")).toBe("Expand section");
    });

    it("preview mode does not render heading fold controls in the editor", async () => {
        mountStory(<Stories.Editor />);
        await getEditorView();
        await nextFrame();

        expect(document.querySelectorAll(`.${md.headingFold}`).length).toBe(0);
    });
});
