// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { FOCUS_MODE_KEY, useFocusMode } from "./useFocusMode";

// 本仓库 jsdom 未提供可用的 Storage（setItem/clear 缺失），装一个内存版 localStorage。
function installMemoryStorage(): Storage {
  const map = new Map<string, string>();
  const storage: Storage = {
    get length() {
      return map.size;
    },
    clear: () => map.clear(),
    getItem: (key) => (map.has(key) ? (map.get(key) ?? null) : null),
    key: (index) => Array.from(map.keys())[index] ?? null,
    removeItem: (key) => map.delete(key),
    setItem: (key, value) => map.set(key, String(value)),
  };
  Object.defineProperty(window, "localStorage", {
    value: storage,
    configurable: true,
  });
  return storage;
}

describe("useFocusMode", () => {
  beforeEach(() => {
    installMemoryStorage();
  });
  afterEach(() => {
    window.localStorage.clear();
  });

  it("默认关闭（无存档时 focus=false）", () => {
    const { result } = renderHook(() => useFocusMode());
    expect(result.current.focus).toBe(false);
  });

  it("toggle 翻转并把状态写入 localStorage", () => {
    const { result } = renderHook(() => useFocusMode());

    act(() => result.current.toggle());

    expect(result.current.focus).toBe(true);
    expect(window.localStorage.getItem(FOCUS_MODE_KEY)).toBe("1");

    act(() => result.current.toggle());

    expect(result.current.focus).toBe(false);
    expect(window.localStorage.getItem(FOCUS_MODE_KEY)).toBe("0");
  });

  it("挂载时从 localStorage 恢复已开启状态", () => {
    window.localStorage.setItem(FOCUS_MODE_KEY, "1");

    const { result } = renderHook(() => useFocusMode());

    expect(result.current.focus).toBe(true);
  });
});
