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: "section-bg-image-test",
    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,
    }),
  };
});

// 섹션 배경 이미지 TDD
// - backgroundImage* 속성이 EditorPage 섹션 wrapper 스타일에 반영되는지 검증한다.

describe("EditorPage - 섹션 배경 이미지", () => {
  it("섹션에 backgroundImageSrc/size/position 이 설정되면 editor-section 스타일에 backgroundImage/Size/Position 이 반영되어야 한다", () => {
    const section: Block = {
      id: "sec_bg_image",
      type: "section",
      props: {
        background: "default",
        paddingY: "md",
        columns: [{ id: "sec_bg_image_col_1", span: 12 }],
        maxWidthMode: "normal",
        gapX: "md",
        alignItems: "top",
        backgroundImageSrc: "/api/image/section-bg-1",
        backgroundImageSize: "cover",
        backgroundImagePosition: "center",
        backgroundImageRepeat: "repeat",
      } as any,
    } as any;

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

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

    render(<EditorPage />);

    const sectionEl = screen.getByTestId("editor-section") as HTMLElement;
    expect(sectionEl.style.backgroundImage).toContain("/api/image/section-bg-1");
    expect(sectionEl.style.backgroundSize).toBe("cover");
    expect(sectionEl.style.backgroundPosition).toBe("center center");
    expect(sectionEl.style.backgroundRepeat).toBe("repeat");
  });

  it("backgroundImagePositionMode 가 custom 이고 X/Y 퍼센트가 설정되면 background-position 은 'X% Y%' 로 설정되어야 한다", () => {
    const section: Block = {
      id: "sec_bg_image_xy",
      type: "section",
      props: {
        background: "default",
        paddingY: "md",
        columns: [{ id: "sec_bg_image_xy_col_1", span: 12 }],
        maxWidthMode: "normal",
        gapX: "md",
        alignItems: "top",
        backgroundImageSrc: "/api/image/section-bg-xy",
        backgroundImageSize: "cover",
        backgroundImagePositionMode: "custom",
        backgroundImagePositionXPercent: 30,
        backgroundImagePositionYPercent: 70,
      } as any,
    } as any;

    const child: Block = {
      id: "txt_xy",
      type: "text",
      props: {
        text: "XY 커스텀 위치 텍스트",
        align: "left",
        size: "base",
      },
      sectionId: "sec_bg_image_xy",
      columnId: "sec_bg_image_xy_col_1",
    } as any;

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

    render(<EditorPage />);

    const sectionEl = screen.getByTestId("editor-section") as HTMLElement;
    expect(sectionEl.style.backgroundImage).toContain("/api/image/section-bg-xy");
    expect(sectionEl.style.backgroundPosition).toBe("30% 70%");
  });

  it("backgroundVideoSrc 가 설정된 섹션은 배경 비디오 video 태그가 렌더되어야 한다", () => {
    const section: Block = {
      id: "sec_bg_video",
      type: "section",
      props: {
        background: "default",
        paddingY: "md",
        columns: [{ id: "sec_bg_video_col_1", span: 12 }],
        maxWidthMode: "normal",
        gapX: "md",
        alignItems: "top",
        backgroundVideoSrc: "/videos/section-bg.mp4",
      } as any,
    } as any;

    const child: Block = {
      id: "txt_video",
      type: "text",
      props: {
        text: "섹션 배경 비디오 텍스트",
        align: "left",
        size: "base",
      },
      sectionId: "sec_bg_video",
      columnId: "sec_bg_video_col_1",
    } as any;

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

    render(<EditorPage />);

    const sectionEl = screen.getByTestId("editor-section") as HTMLElement;
    expect(sectionEl).toBeTruthy();

    const videoEl = screen.getByTestId("editor-section-bg-video") as HTMLVideoElement;
    expect(videoEl).toBeTruthy();
    expect(videoEl.src).toContain("/videos/section-bg.mp4");
    expect(videoEl.autoplay).toBe(true);
    expect(videoEl.loop).toBe(true);
    expect(videoEl.muted).toBe(true);
  });
});
