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

import { toGenreDirective, useGenreGate } from "./useGenreGate";

describe("toGenreDirective", () => {
  it("有题材时形如「本章题材：<genre>」", () => {
    expect(toGenreDirective("玄幻")).toBe("本章题材：玄幻");
  });

  it("空/纯空白/null → 空串", () => {
    expect(toGenreDirective(null)).toBe("");
    expect(toGenreDirective("")).toBe("");
    expect(toGenreDirective("  ")).toBe("");
  });
});

describe("useGenreGate", () => {
  it("项目已有 genre：needsGenre=false，genreDirective 反映项目题材", () => {
    const { result } = renderHook(() => useGenreGate("仙侠"));
    expect(result.current.needsGenre).toBe(false);
    expect(result.current.effectiveGenre).toBe("仙侠");
    expect(result.current.genreDirective).toBe("本章题材：仙侠");
  });

  it("项目 genre 为纯空白也视为缺失", () => {
    const { result } = renderHook(() => useGenreGate("   "));
    expect(result.current.needsGenre).toBe(true);
    expect(result.current.effectiveGenre).toBeNull();
    expect(result.current.genreDirective).toBe("");
  });

  it("无 genre：needsGenre=true，初始无生效题材与题材指令", () => {
    const { result } = renderHook(() => useGenreGate(null));
    expect(result.current.needsGenre).toBe(true);
    expect(result.current.chosenGenre).toBeNull();
    expect(result.current.effectiveGenre).toBeNull();
    expect(result.current.genreDirective).toBe("");
  });

  it("无 genre 时 setChosenGenre 后 effectiveGenre/genreDirective 更新", () => {
    const { result } = renderHook(() => useGenreGate(null));
    act(() => result.current.setChosenGenre("都市"));
    expect(result.current.chosenGenre).toBe("都市");
    expect(result.current.effectiveGenre).toBe("都市");
    expect(result.current.genreDirective).toBe("本章题材：都市");
  });

  it("setChosenGenre 传空串 → 回落 null，不产生题材指令", () => {
    const { result } = renderHook(() => useGenreGate(null));
    act(() => result.current.setChosenGenre("科幻"));
    act(() => result.current.setChosenGenre("  "));
    expect(result.current.chosenGenre).toBeNull();
    expect(result.current.genreDirective).toBe("");
  });

  it("项目 genre 优先于作者点选", () => {
    const { result } = renderHook(() => useGenreGate("历史"));
    act(() => result.current.setChosenGenre("悬疑"));
    // needsGenre=false 时 UI 不会调 setChosenGenre，但即便调了项目题材仍优先。
    expect(result.current.effectiveGenre).toBe("历史");
    expect(result.current.genreDirective).toBe("本章题材：历史");
  });
});
