import { MantineProvider, v8CssVariablesResolver } from "@mantine/core";
import { MarkdownViewer } from "@src/primitives/MarkdownViewer";
import { MANTINE_THEME } from "@src/theme/mantine";
import type { ReactElement } from "react";
import { renderToString } from "react-dom/server";
import { beforeAll, describe, expect, it } from "vitest";

beforeAll(() => {
    if (typeof window !== "undefined" && typeof window.matchMedia !== "function") {
        Object.defineProperty(window, "matchMedia", {
            writable: true,
            value: (query: string) => ({
                matches: false,
                media: query,
                onchange: null,
                addListener: () => {},
                removeListener: () => {},
                addEventListener: () => {},
                removeEventListener: () => {},
                dispatchEvent: () => false,
            }),
        });
    }
});

function shell(node: ReactElement): string {
    return renderToString(
        <MantineProvider
            theme={MANTINE_THEME}
            cssVariablesResolver={v8CssVariablesResolver}
            forceColorScheme="dark"
        >
            {node}
        </MantineProvider>,
    );
}

describe("MarkdownViewer / runnable code", () => {
    it("renders RunnableCodeBlock when fenced info includes runnable", () => {
        const html = shell(
            <MarkdownViewer content={'```surql runnable="SELECT 1"\nRETURN 1;\n```'} />,
        );
        expect(html).toContain("Run Query");
    });

    it("renders RunnableCodeBlock for a loose runnable flag with no value", () => {
        const html = shell(<MarkdownViewer content={"```surql runnable\nRETURN 1;\n```"} />);
        expect(html).toContain("Run Query");
    });

    it("does not render RunnableCodeBlock for plain fenced code", () => {
        const html = shell(<MarkdownViewer content={"```surql\nRETURN 1;\n```"} />);
        expect(html).not.toContain("Run Query");
    });

    it("preserves runnable attribute casing through the render pipeline", () => {
        const html = shell(
            <MarkdownViewer
                content={'```surql runnable="SELECT 1"\nRETURN 1;\n```'}
                codeRenderers={{}}
                renderers={{
                    code: ({ runnable }) => <span data-runnable={runnable}>{runnable}</span>,
                }}
            />,
        );
        expect(html).toContain("SELECT 1");
        expect(html).not.toContain("select 1");
    });
});
