import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { ThemeProvider } from "@/components/providers/ThemeProvider";

import { ThemeToggle } from "./ThemeToggle";

const storage = new Map<string, string>();

function renderThemeToggle() {
  render(
    <ThemeProvider>
      <ThemeToggle />
    </ThemeProvider>,
  );
}

describe("ThemeToggle", () => {
  beforeEach(() => {
    Object.defineProperty(window, "localStorage", {
      configurable: true,
      value: {
        clear: () => storage.clear(),
        getItem: (key: string) => storage.get(key) ?? null,
        removeItem: (key: string) => storage.delete(key),
        setItem: (key: string, value: string) => storage.set(key, value),
      },
    });
  });

  afterEach(() => {
    storage.clear();
    document.documentElement.dataset.theme = "dark";
    document.documentElement.classList.add("dark");
  });

  it("defaults to dark mode", () => {
    renderThemeToggle();

    expect(
      screen.getByRole("button", { name: "Switch to light mode" }),
    ).toBeInTheDocument();
    expect(document.documentElement.dataset.theme).toBe("dark");
    expect(document.documentElement).toHaveClass("dark");
  });

  it("stores the selected light mode", async () => {
    const user = userEvent.setup();
    renderThemeToggle();

    await user.click(
      screen.getByRole("button", { name: "Switch to light mode" }),
    );

    expect(storage.get("openclaw_theme")).toBe("light");
    expect(document.documentElement.dataset.theme).toBe("light");
    expect(document.documentElement).not.toHaveClass("dark");
    expect(
      screen.getByRole("button", { name: "Switch to dark mode" }),
    ).toBeInTheDocument();
  });
});
