import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { render, screen, cleanup } 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: "selection-focus",
    canvasPreset: "full",
    canvasWidthPx: 1024,
    canvasBgColorHex: "#0f172a",
    bodyBgColorHex: "#020617",
  } 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(),
    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(),
    replaceBlocks: vi.fn(),
    reorderBlocks: vi.fn(),
    moveBlock: 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("선택된 블록은 editor-block 에 border-sky-500 / bg-slate-900/80 하이라이트를 가져야 한다", () => {
    const blocks: Block[] = [
      {
        id: "blk_1",
        type: "text",
        props: {
          text: "첫 번째 블록",
          align: "left",
          size: "base",
        },
      } as any,
      {
        id: "blk_2",
        type: "text",
        props: {
          text: "두 번째 블록",
          align: "left",
          size: "base",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "blk_2";

    render(<EditorPage />);

    const allBlocks = screen.getAllByTestId("editor-block") as HTMLElement[];
    const selected = allBlocks.find((el) => el.dataset.selected === "true");

    expect(selected).toBeTruthy();
    expect(selected!.className).toContain("border-sky-500");
    expect(selected!.className).toContain("bg-slate-900/80");
  });

  it("섹션 블록 자체를 선택하면 섹션 wrapper 가 강조되어야 한다", () => {
    const section: Block = {
      id: "sec_1",
      type: "section",
      props: {
        background: "default",
        paddingY: "md",
        columns: [
          {
            id: "sec_1_col_1",
            span: 12,
          },
        ],
        maxWidthMode: "normal",
        gapX: "md",
        alignItems: "top",
      },
    } as any;

    mockState.blocks = [section];
    mockState.selectedBlockId = "sec_1";

    render(<EditorPage />);

    const sectionEl = screen.getByTestId("editor-section") as HTMLElement;
    expect(sectionEl.className).toContain("border-sky-500");
  });

  it("섹션 자식 블록을 선택해도 섹션 wrapper 가 강조되어야 한다", () => {
    const section: Block = {
      id: "sec_1",
      type: "section",
      props: {
        background: "default",
        paddingY: "md",
        columns: [
          {
            id: "sec_1_col_1",
            span: 12,
          },
        ],
        maxWidthMode: "normal",
        gapX: "md",
        alignItems: "top",
      },
    } as any;

    const child: Block = {
      id: "txt_child",
      type: "text",
      props: {
        text: "섹션 안 텍스트",
        align: "left",
        size: "base",
      },
      sectionId: "sec_1",
      columnId: "sec_1_col_1",
    } as any;

    mockState.blocks = [section, child];
    mockState.selectedBlockId = "txt_child";

    render(<EditorPage />);

    const sectionEl = screen.getByTestId("editor-section") as HTMLElement;
    expect(sectionEl.className).toContain("border-sky-500");
  });
});
