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 / code title", () => {
    it("renders a title attribute as a caption above the code block", () => {
        const html = shell(
            <MarkdownViewer content={'```ts title="Example file"\nconst x = 1;\n```'} />,
        );
        expect(html).toContain("Example file");
    });

    it("omits the caption when no title is present", () => {
        const html = shell(<MarkdownViewer content={"```ts\nconst x = 1;\n```"} />);
        expect(html).not.toContain("code-block-caption");
    });

    it("passes the title through the code renderer override", () => {
        const html = shell(
            <MarkdownViewer
                content={'```ts title="From override"\nconst x = 1;\n```'}
                renderers={{
                    code: ({ title }) => <span data-title={title}>{title}</span>,
                }}
            />,
        );
        expect(html).toContain("From override");
    });
});
