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 / MarkdownViewerRenderers", () => {
    it("uses heading renderer override", () => {
        const html = shell(
            <MarkdownViewer
                content="## Section title"
                renderers={{
                    heading: () => <span data-custom-heading>HEADING_MARKER</span>,
                }}
            />,
        );
        expect(html).toContain("HEADING_MARKER");
        expect(html).not.toContain("Section title");
    });

    it("uses link renderer override", () => {
        const html = shell(
            <MarkdownViewer
                content="[Example](https://example.com)"
                renderers={{
                    link: () => <span data-custom-link>LINK_MARKER</span>,
                }}
            />,
        );
        expect(html).toContain("LINK_MARKER");
        expect(html).not.toContain("Example");
        expect(html).not.toContain("https://example.com");
    });

    it("uses image renderer override", () => {
        const html = shell(
            <MarkdownViewer
                content='![Alt text](https://example.com/image.png "Title")'
                renderers={{
                    image: () => <span data-custom-image>IMAGE_MARKER</span>,
                }}
            />,
        );
        expect(html).toContain("IMAGE_MARKER");
        expect(html).not.toContain("Alt text");
        expect(html).not.toContain("https://example.com/image.png");
    });
});
