import { MantineProvider, Paper, v8CssVariablesResolver } from "@mantine/core";
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";

const TAG = '<Since v={"2.0.0"} t="true" b="false" />';

/** Dark-theme string green from {@link VIVID_THEME}. */
const STRING_COLOR = "rgb(0, 255, 110)";
/** Dark-theme property name from {@link VIVID_THEME}. */
const PROPERTY_COLOR = "rgb(224, 108, 117)";

describe("MarkdownEditor / JSX attribute highlighting", () => {
    it("does not let the nested HTML parser mis-highlight attributes after an expression", async () => {
        mountStory(
            <MantineProvider
                theme={MANTINE_THEME}
                cssVariablesResolver={v8CssVariablesResolver}
                forceColorScheme="dark"
            >
                <Paper
                    p="md"
                    withBorder
                >
                    <MarkdownEditor
                        mode="source"
                        document={TAG}
                        autoFocus={false}
                        mih={120}
                    />
                </Paper>
            </MantineProvider>,
        );
        await getEditorView();
        await nextFrame();

        const colors = readLineTokenColors();
        expect(colors.v).toBe(PROPERTY_COLOR);
        expect(colors.t).toBe(PROPERTY_COLOR);
        expect(colors.b).toBe(PROPERTY_COLOR);
        expect(colors.trueQuoted).toBe(STRING_COLOR);
        expect(colors.falseQuoted).toBe(STRING_COLOR);
        expect(colors.exprLiteral).toBe(STRING_COLOR);
    });
});

function readLineTokenColors(): Record<string, string> {
    const line = document.querySelector(".cm-line");
    expect(line).not.toBeNull();
    if (!line) return {};

    const out: Record<string, string> = {};
    for (const span of Array.from(line.querySelectorAll("span"))) {
        const text = span.textContent ?? "";
        if (!text) continue;
        const color = getComputedStyle(span).color;

        if (text === "v") out.v = color;
        if (text === "t") out.t = color;
        if (text === "b") out.b = color;
        if (text === '"2.0.0"') out.exprLiteral = color;
        if (text === '"true"') out.trueQuoted = color;
        if (text === '"false"') out.falseQuoted = color;
    }

    return out;
}
