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: "editor-video-style-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,
    }),
  };
});

// 단순 유튜브 URL, 업로드 비디오 URL 케이스에 대한 에디터 렌더링을 검증한다.
describe("EditorPage - 비디오 블록 스타일", () => {
  it("YouTube URL 비디오 블록은 iframe 으로 렌더되고 기본 16:9 비율 wrapper 를 가져야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_youtube_1",
        type: "video" as any,
        props: {
          sourceUrl: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
          align: "center",
          widthMode: "auto",
          aspectRatio: "16:9",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_youtube_1";

    render(<EditorPage />);

    const iframe = screen.getByTitle("비디오") as HTMLIFrameElement;
    const wrapper = iframe.parentElement as HTMLElement;

    expect(iframe).toBeTruthy();
    expect(iframe.src).toContain("youtube.com/embed");
    expect(wrapper.className).toContain("pb-video-wrapper");
  });

  it("업로드 비디오 URL 은 video 태그로 렌더되고 controls 속성을 포함해야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_upload_1",
        type: "video" as any,
        props: {
          sourceUrl: "/api/video/abc123",
          align: "left",
          widthMode: "fixed",
          widthPx: 640,
          aspectRatio: "16:9",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_upload_1";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;
    expect(video).toBeTruthy();
    expect(video.getAttribute("controls")).not.toBeNull();
    expect(video.style.width).toBe("640px");
  });

  it("posterImageSrc 가 설정된 HTML5 비디오는 video 태그 poster 속성으로 렌더되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_poster_1",
        type: "video" as any,
        props: {
          sourceUrl: "/videos/sample.mp4",
          align: "center",
          widthMode: "auto",
          aspectRatio: "16:9",
          posterImageSrc: "/images/sample-poster.png",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_poster_1";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;
    expect(video).toBeTruthy();
    expect(video.getAttribute("poster")).toBe("/images/sample-poster.png");
  });

  it("startTimeSec/endTimeSec 가 설정된 HTML5 비디오는 loadedmetadata/timeupdate 이벤트에서 시작/종료 범위가 적용되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_range_1",
        type: "video" as any,
        props: {
          sourceUrl: "/videos/range.mp4",
          align: "center",
          widthMode: "auto",
          aspectRatio: "16:9",
          startTimeSec: 5,
          endTimeSec: 10,
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_range_1";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;

    fireEvent(video, new Event("loadedmetadata"));
    expect(video.currentTime).toBe(5);

    (video as any).pause = vi.fn();
    video.currentTime = 10.1;
    fireEvent(video, new Event("timeupdate"));
    expect((video as any).pause).toHaveBeenCalled();
  });

  it("HTML5 비디오의 ariaLabel/titleText/captionText 는 에디터에서 aria-label 및 캡션 요소로 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_a11y_html5",
        type: "video" as any,
        props: {
          sourceUrl: "/videos/a11y.mp4",
          align: "center",
          widthMode: "auto",
          aspectRatio: "16:9",
          titleText: "접근성 비디오 타이틀",
          ariaLabel: "접근성 비디오 설명",
          captionText: "비디오 캡션입니다.",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_a11y_html5";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;
    expect(video).toBeTruthy();
    expect(video.getAttribute("aria-label")).toBe("접근성 비디오 설명");

    const caption = screen.getByTestId("editor-video-caption");
    expect(caption).toBeTruthy();
    expect(caption.textContent).toBe("비디오 캡션입니다.");
  });

  it("sourceUrl 이 비어 있는 HTML5 비디오는 src 속성을 렌더링하지 않아야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_empty_src",
        type: "video" as any,
        props: {
          sourceUrl: "",
          align: "center",
          widthMode: "auto",
          aspectRatio: "16:9",
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_empty_src";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;
    expect(video).toBeTruthy();
    expect(video.getAttribute("src")).toBeNull();
  });

  it("비디오 카드 스타일 props(backgroundColorCustom/cardPaddingPx/borderRadiusPx)는 wrapper 의 스타일에 반영되어야 한다", () => {
    const blocks: Block[] = [
      {
        id: "video_card_1",
        type: "video" as any,
        props: {
          sourceUrl: "/api/video/card-test",
          align: "center",
          widthMode: "fixed",
          widthPx: 480,
          aspectRatio: "16:9",
          backgroundColorCustom: "#123456",
          cardPaddingPx: 24,
          borderRadiusPx: 16,
        },
      } as any,
    ];

    mockState.blocks = blocks;
    mockState.selectedBlockId = "video_card_1";

    render(<EditorPage />);

    const video = screen.getByTestId("editor-video") as HTMLVideoElement;
    const wrapper = video.parentElement as HTMLElement;

    expect(wrapper).toBeTruthy();
    // #123456 -> rgb(18, 52, 86)
    expect(wrapper.style.backgroundColor).toBe("rgb(18, 52, 86)");
    expect(wrapper.style.padding).toBe("24px");
    expect(wrapper.style.borderRadius).toBe("16px");
  });
});
