export type CarouselImage = { url: string; alt?: string; caption?: string };

export type ContentBlock =
  | { id: string; type: "heading"; text: string; level?: 2 | 3 | 4 }
  | { id: string; type: "paragraph"; text: string }
  | { id: string; type: "image"; url: string; alt?: string; caption?: string }
  | { id: string; type: "link"; label: string; url: string }
  | { id: string; type: "divider" }
  | { id: string; type: "callout"; title?: string; text: string }
  | { id: string; type: "carousel"; images: CarouselImage[]; autoplay?: boolean };

export const BLOCK_LABELS: Record<ContentBlock["type"], string> = {
  heading: "Heading",
  paragraph: "Paragraph",
  image: "Image",
  link: "Link / Button",
  divider: "Divider",
  callout: "Callout box",
  carousel: "Photo carousel",
};

export const ALL_BLOCK_TYPES: ContentBlock["type"][] = [
  "heading",
  "paragraph",
  "image",
  "carousel",
  "link",
  "callout",
  "divider",
];

export function newBlock(type: ContentBlock["type"]): ContentBlock {
  const id =
    typeof crypto !== "undefined" && "randomUUID" in crypto
      ? crypto.randomUUID()
      : `b-${Math.random().toString(36).slice(2)}`;
  switch (type) {
    case "heading":
      return { id, type, text: "Heading", level: 3 };
    case "paragraph":
      return { id, type, text: "" };
    case "image":
      return { id, type, url: "", alt: "" };
    case "link":
      return { id, type, label: "Learn more", url: "https://" };
    case "divider":
      return { id, type };
    case "callout":
      return { id, type, title: "Important", text: "" };
    case "carousel":
      return { id, type, images: [], autoplay: false };
  }
}

export function sanitizeBlocks(value: unknown): ContentBlock[] {
  if (!Array.isArray(value)) return [];
  return value.filter(
    (b: any) => b && typeof b === "object" && typeof b.type === "string"
  ) as ContentBlock[];
}
