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, idx) => {
    const firstItem = idx === 0
    switch (block.__typename) {
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksCardsGrid:
        return (
          <CardsGrid
            key={`${block.cards_grid.title}-${idx}`}
            cards_grid={block.cards_grid}
          />
        )
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksContent:
        return (
          <section key={`${block.__typename}-${idx}`}>
            <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}
            firstItem={firstItem}
            key={`${block.dynamic_content.title}-${idx}`}
          />
        )
      case LoyaltyBlocksTypenameEnum.LoyaltyPageBlocksShortcuts:
        const shortcuts = block.shortcuts.shortcuts.map((shortcut) => ({
          ...shortcut,
          url: modWebviewLink(shortcut.url, lang),
        }))
        return (
          <Shortcuts
            firstItem={firstItem}
            key={`${block.shortcuts.title}-${idx}`}
            shortcuts={shortcuts}
            title={block.shortcuts.title}
            subtitle={block.shortcuts.preamble}
          />
        )
      default:
        return null
    }
  })
}
