import {
  Breadcrumbs as BreadcrumbsComponent,
  type BreadcrumbsProps,
} from "@scandic-hotels/design-system/Breadcrumbs"

import { serverClient } from "@/lib/trpc/server"

import { generateBreadcrumbsSchema } from "@/utils/jsonSchemas"

export async function Breadcrumbs({
  subpageTitle,
  ...props
}: Omit<BreadcrumbsProps, "breadcrumbs"> & {
  subpageTitle?: string
}) {
  const caller = await serverClient()
  const breadcrumbs = await caller.contentstack.breadcrumbs.get()
  if (!breadcrumbs?.length) {
    return null
  }

  if (subpageTitle) {
    breadcrumbs.push({ title: subpageTitle, uid: subpageTitle, href: "" })
  }

  const jsonSchema = generateBreadcrumbsSchema(breadcrumbs)

  return (
    <>
      <script
        type={jsonSchema.type}
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonSchema.jsonLd),
        }}
      />
      <BreadcrumbsComponent breadcrumbs={breadcrumbs} {...props} />
    </>
  )
}
