"use client";

import type { Block, SectionBlockProps, TextBlockProps, ImageBlockProps } from "@/features/editor/state/editorStore";

export function createBlogTemplateBlocks(opts: {
  sectionId: string;
  createId: () => string;
}): { blocks: Block[]; lastSelectedId: string } {
  const { sectionId, createId } = opts;

  const columns: SectionBlockProps["columns"] = [
    { id: `${sectionId}_col_1`, span: 4 },
    { id: `${sectionId}_col_2`, span: 4 },
    { id: `${sectionId}_col_3`, span: 4 },
  ];

  const sectionProps: SectionBlockProps = {
    background: "default",
    paddingY: "lg",
    // 블로그 리스트는 넓은 폭과 충분한 카드 간격을 사용한다.
    paddingYPx: 72,
    maxWidthPx: 1120,
    gapXPx: 32,
    backgroundColorCustom: "#020617",
    columns,
  } as any;

  const sectionBlock: Block = {
    id: sectionId,
    type: "section",
    props: sectionProps,
    sectionId: null,
    columnId: null,
  };

  const postDefinitions = [
    { title: "블로그 포스트 1", summary: "첫 번째 포스트 요약을 여기에 입력하세요." },
    { title: "블로그 포스트 2", summary: "두 번째 포스트 요약을 여기에 입력하세요." },
    { title: "블로그 포스트 3", summary: "세 번째 포스트 요약을 여기에 입력하세요." },
  ];

  const blogBlocks: Block[] = columns.flatMap((col, index) => {
    const post = postDefinitions[index] ?? postDefinitions[0];

    const imageId = createId();
    const titleId = createId();
    const summaryId = createId();

    const imageProps: ImageBlockProps = {
      src: "https://via.placeholder.com/400x250/1e293b/94a3b8?text=Blog+Image",
      alt: post.title,
      align: "center",
      widthMode: "auto",
      borderRadius: "md",
    };

    const titleProps: TextBlockProps = {
      text: post.title,
      align: "left",
      size: "lg",
      bold: true,
    } as any;

    const summaryProps: TextBlockProps = {
      text: post.summary,
      align: "left",
      size: "sm",
      color: "muted",
    } as any;

    const imageBlock: Block = {
      id: imageId,
      type: "image",
      props: imageProps,
      sectionId,
      columnId: col.id,
    };

    const titleBlock: Block = {
      id: titleId,
      type: "text",
      props: titleProps,
      sectionId,
      columnId: col.id,
    };

    const summaryBlock: Block = {
      id: summaryId,
      type: "text",
      props: summaryProps,
      sectionId,
      columnId: col.id,
    };

    return [imageBlock, titleBlock, summaryBlock];
  });

  const blocks: Block[] = [sectionBlock, ...blogBlocks];
  const lastSelectedId = blogBlocks[blogBlocks.length - 1]?.id ?? sectionId;

  return { blocks, lastSelectedId };
}
