import JsonToHtml from "@/components/JsonToHtml"
import DynamicContentBlock from "@/components/Loyalty/Blocks/DynamicContent"
import Shortcuts from "@/components/MyPages/Blocks/Shortcuts"
import { modWebviewLink } from "@/utils/webviews"

import CardsGrid from "../CardsGrid"

import type { BlocksProps } from "@/types/components/loyalty/blocks"
import { LoyaltyBlocksTypenameEnum } from "@/types/components/loyalty/enums"
import { LangParams } from "@/types/params"

export function Blocks({ lang, blocks }: BlocksProps & LangParams) {
  return blocks.map((block) => {
    switch (block.__typename) {
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksCardsGrid:
        return <CardsGrid cards_grid={block.cards_grid} />
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksContent:
        return (
          <section>
            <JsonToHtml
              nodes={block.content.content.json.children}
              embeds={block.content.content.embedded_itemsConnection.edges}
            />
          </section>
        )
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksDynamicContent:
        const dynamicContent = {
          ...block.dynamic_content,
          link: block.dynamic_content.link
            ? {
                ...block.dynamic_content.link,
                href: modWebviewLink(block.dynamic_content.link.href, lang),
              }
            : undefined,
        }

        return <DynamicContentBlock dynamicContent={dynamicContent} />
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksShortcuts:
        const shortcuts = block.shortcuts.shortcuts.map((shortcut) => ({
          ...shortcut,
          url: modWebviewLink(shortcut.url, lang),
        }))
        return (
          <Shortcuts
            shortcuts={shortcuts}
            title={block.shortcuts.title}
            subtitle={block.shortcuts.preamble}
          />
        )
      default:
        return null
    }
  })
}
