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

// PreviewPage 자동 복원 TDD
// - localStorage 의 pb:autosave:<slug> 스냅샷을 기반으로 초기 렌더에서 replaceBlocks + updateProjectConfig 로 상태를 복원해야 한다.

let mockState: any;

beforeEach(() => {
  const baseProjectConfig: ProjectConfig = {
    title: "프리뷰 자동복원 테스트",
    slug: "preview-autosave-test",
    canvasPreset: "full",
  } as ProjectConfig;

  mockState = {
    blocks: [
      {
        id: "blk_1",
        type: "text",
        props: {
          text: "프리뷰 기본 블록",
          align: "left",
          size: "base",
        },
      },
    ] as Block[],
    projectConfig: baseProjectConfig,
    replaceBlocks: vi.fn(),
    updateProjectConfig: vi.fn(),
  };

  window.localStorage.clear();
});

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(),
    }),
  };
});

describe("PreviewPage - 자동 복원", () => {
  it("pb:autosave:<slug> 스냅샷이 있으면 초기 렌더에서 replaceBlocks 와 updateProjectConfig 로 상태를 복원해야 한다", () => {
    const savedBlocks: Block[] = [
      {
        id: "saved_1",
        type: "text",
        props: {
          text: "저장된 프리뷰 블록",
          align: "center",
          size: "lg",
        },
      } as any,
    ];

    const savedConfig: ProjectConfig = {
      title: "저장된 프리뷰 프로젝트",
      slug: "preview-autosave-test",
      canvasPreset: "full",
    } as ProjectConfig;

    const payload = {
      blocks: savedBlocks,
      projectConfig: savedConfig,
    };

    window.localStorage.setItem("pb:autosave:preview-autosave-test", JSON.stringify(payload));

    render(<PreviewPage />);

    expect(mockState.replaceBlocks).toHaveBeenCalledTimes(1);
    expect(mockState.replaceBlocks).toHaveBeenCalledWith(savedBlocks as any);

    expect(mockState.updateProjectConfig).toHaveBeenCalledTimes(1);
    expect(mockState.updateProjectConfig).toHaveBeenCalledWith(savedConfig as ProjectConfig);
  });
});
