"use client";

import type { Block, SectionBlockProps, TextBlockProps } from "@/features/editor/state/editorStore";
import type { EditorFaqTemplateMessages } from "@/features/i18n/messages/editorTemplates";

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

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

  const sectionProps: SectionBlockProps = {
    background: "default",
    paddingY: "md",
    // FAQ 는 비교적 좁은 폭과 보통 여백을 사용한다.
    paddingYPx: 80,
    maxWidthPx: 1024,
    gapXPx: 48,
    backgroundColorCustom: "#020617",
    columns,
  } as any;

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

  const leftColumnId = `${sectionId}_col_1`;
  const rightColumnId = `${sectionId}_col_2`;

  // Left Column: Title
  const titleId = createId();
  const titleProps: TextBlockProps = {
    text: messages.title,
    align: "left",
    size: "xl",
    bold: true,
  } as any;
  const titleBlock: Block = {
    id: titleId,
    type: "text",
    props: titleProps,
    sectionId,
    columnId: leftColumnId,
  };

  const subTitleId = createId();
  const subTitleProps: TextBlockProps = {
    text: messages.subtitle,
    align: "left",
    size: "sm",
    color: "muted",
  } as any;
  const subTitleBlock: Block = {
    id: subTitleId,
    type: "text",
    props: subTitleProps,
    sectionId,
    columnId: leftColumnId,
  };


  // Right Column: Q&A List
  const faqBlocks: Block[] = messages.items.flatMap((pair) => {
    const qId = createId();
    const aId = createId();

    const questionProps: TextBlockProps = {
      text: pair.question,
      align: "left",
      size: "lg",
      bold: true,
    } as any;

    const answerProps: TextBlockProps = {
      text: pair.answer,
      align: "left",
      size: "base",
      color: "muted",
    } as any;

    const questionBlock: Block = {
      id: qId,
      type: "text",
      props: questionProps,
      sectionId,
      columnId: rightColumnId,
    };

    const answerBlock: Block = {
      id: aId,
      type: "text",
      props: answerProps,
      sectionId,
      columnId: rightColumnId,
    };

    return [questionBlock, answerBlock];
  });

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

  return { blocks, lastSelectedId };
}
