import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
import EditorPage from "@/app/editor/page";

let mockState: any;

beforeEach(() => {
  const baseProjectConfig: ProjectConfig = {
    title: "배경 테스트",
    slug: "bg-test",
    canvasPreset: "full",
    canvasBgColorHex: "#111111",
    bodyBgColorHex: "#222222",
  } as ProjectConfig;

  mockState = {
    blocks: [] as Block[],
    projectConfig: baseProjectConfig,
    selectedBlockId: null as string | null,
    selectedListItemId: null as string | null,
    undo: vi.fn(),
    redo: vi.fn(),
    removeBlock: vi.fn(),
    duplicateBlock: vi.fn(),
    selectBlock: vi.fn(),
    selectListItem: vi.fn(),
    replaceBlocks: vi.fn(),
    reorderBlocks: vi.fn(),
    moveBlock: vi.fn(),
    addTextBlock: vi.fn(),
    addButtonBlock: vi.fn(),
    addImageBlock: vi.fn(),
    addDividerBlock: vi.fn(),
    addListBlock: vi.fn(),
    addSectionBlock: vi.fn(),
    addFormBlock: vi.fn(),
    addFormInputBlock: vi.fn(),
    addFormSelectBlock: vi.fn(),
    addFormCheckboxBlock: vi.fn(),
    addFormRadioBlock: vi.fn(),
    addHeroTemplateSection: vi.fn(),
    addFeaturesTemplateSection: vi.fn(),
    addCtaTemplateSection: vi.fn(),
    addFaqTemplateSection: vi.fn(),
    addPricingTemplateSection: vi.fn(),
    addTestimonialsTemplateSection: vi.fn(),
    addBlogTemplateSection: vi.fn(),
    addTeamTemplateSection: vi.fn(),
    addFooterTemplateSection: vi.fn(),
    updateBlock: vi.fn(),
  };
});

afterEach(() => {
  cleanup();
});

vi.mock("@/features/editor/state/editorStore", () => {
  const useEditorStore = (selector: (state: any) => any) => selector(mockState);
  (useEditorStore as any).getState = () => mockState;

  return {
    __esModule: true,
    useEditorStore,
  };
});

vi.mock("next/link", () => {
  return {
    __esModule: true,
    default: ({ href, children }: any) => <a href={href}>{children}</a>,
  };
});

vi.mock("next/navigation", () => {
  return {
    __esModule: true,
    useRouter: () => ({
      push: vi.fn(),
    }),
    useSearchParams: () => ({
      get: () => null,
    }),
  };
});

describe("EditorPage - 페이지/캔버스 배경", () => {
  it("main 요소는 bodyBgColorHex 로 직접 배경색을 갖지 않아야 하고, 캔버스 래퍼만 배경색을 가져야 한다", () => {
    const { container } = render(<EditorPage />);

    const mainEl = container.querySelector("main") as HTMLElement | null;
    expect(mainEl).not.toBeNull();
    // main 은 bodyBgColorHex 기반 배경색을 직접 갖지 않는다.
    expect(mainEl!.style.backgroundColor).toBe("");

    const canvasOuter = screen.getByTestId("editor-canvas") as HTMLElement;
    expect(canvasOuter.style.backgroundColor).toBe("rgb(34, 34, 34)");
  });

  it("main 요소는 전역 라이트/다크 테마 클래스(bg-slate-100 text-slate-900 dark:bg-slate-950 dark:text-slate-50)를 사용해야 한다", () => {
    const { container } = render(<EditorPage />);

    const mainEl = container.querySelector("main") as HTMLElement | null;
    expect(mainEl).not.toBeNull();

    const className = mainEl!.getAttribute("class") ?? "";
    expect(className).toContain("bg-slate-100");
    expect(className).toContain("text-slate-900");
    expect(className).toContain("dark:bg-slate-950");
    expect(className).toContain("dark:text-slate-50");
  });

  it("프로젝트 저장/불러오기 모달 카드는 라이트/다크 테마에 맞는 카드/인풋 크롬을 사용해야 한다", () => {
    render(<EditorPage />);

    const menuButton = screen.getByRole("button", { name: /Menu/ });
    fireEvent.click(menuButton);

    const projectMenuItem = screen.getByRole("button", { name: "Save / load project" });
    fireEvent.click(projectMenuItem);

    const heading = screen.getByText("Save / load project");
    const headerDiv = heading.closest("div") as HTMLDivElement | null;
    expect(headerDiv).not.toBeNull();

    const card = headerDiv!.parentElement as HTMLDivElement | null;
    expect(card).not.toBeNull();

    const cardClass = card!.getAttribute("class") ?? "";
    expect(cardClass).toContain("bg-white");
    expect(cardClass).toContain("text-slate-900");
    expect(cardClass).toContain("border-slate-200");
    expect(cardClass).toContain("dark:bg-slate-900");
    expect(cardClass).toContain("dark:text-slate-100");
    expect(cardClass).toContain("dark:border-slate-700");

    const titleSpan = Array.from(card!.querySelectorAll("span")).find(
      (el) => el.textContent === "Project title",
    );
    expect(titleSpan).not.toBeUndefined();
    const titleWrapper = (titleSpan as HTMLSpanElement).parentElement as HTMLElement | null;
    expect(titleWrapper).not.toBeNull();

    const titleInput = titleWrapper!.querySelector("input") as HTMLInputElement | null;
    expect(titleInput).not.toBeNull();

    const inputClass = titleInput!.getAttribute("class") ?? "";
    expect(inputClass).toContain("bg-white");
    expect(inputClass).toContain("text-slate-900");
    expect(inputClass).toContain("border-slate-300");
    expect(inputClass).toContain("dark:bg-slate-900");
    expect(inputClass).toContain("dark:text-slate-100");
    expect(inputClass).toContain("dark:border-slate-700");
  });

  it("JSON Export / Import 모달 카드는 라이트/다크 테마에 맞는 카드/textarea 크롬을 사용해야 한다", () => {
    render(<EditorPage />);

    const menuButton = screen.getByRole("button", { name: /Menu/ });
    fireEvent.click(menuButton);

    const jsonMenuItem = screen.getByRole("button", { name: "JSON export / import" });
    fireEvent.click(jsonMenuItem);

    const heading = screen.getByText(/JSON Export \/ Import/);
    const headerDiv = heading.closest("div") as HTMLDivElement | null;
    expect(headerDiv).not.toBeNull();

    const card = headerDiv!.parentElement as HTMLDivElement | null;
    expect(card).not.toBeNull();

    const cardClass = card!.getAttribute("class") ?? "";
    expect(cardClass).toContain("bg-white");
    expect(cardClass).toContain("text-slate-900");
    expect(cardClass).toContain("border-slate-200");
    expect(cardClass).toContain("dark:bg-slate-900");
    expect(cardClass).toContain("dark:text-slate-100");
    expect(cardClass).toContain("dark:border-slate-700");

    const jsonLabel = screen.getByText("Editor state JSON");
    const jsonWrapper = jsonLabel.parentElement as HTMLElement | null;
    expect(jsonWrapper).not.toBeNull();

    const textarea = jsonWrapper!.querySelector("textarea") as HTMLTextAreaElement | null;
    expect(textarea).not.toBeNull();

    const textareaClass = textarea!.getAttribute("class") ?? "";
    expect(textareaClass).toContain("bg-white");
    expect(textareaClass).toContain("text-slate-900");
    expect(textareaClass).toContain("border-slate-300");
    expect(textareaClass).toContain("dark:bg-slate-900");
    expect(textareaClass).toContain("dark:text-slate-100");
    expect(textareaClass).toContain("dark:border-slate-700");
  });
});
