<script setup lang="ts">
/**
 * `card.list` element composition.
 *
 * Renders a vertical stack of nested child elements inside an optional
 * Card chrome. Acts as the element-tier equivalent of `ElementListCard`
 * and replaces `configuration-block.elements-block` as the canonical
 * inline element container.
 *
 * In the FormBuilder the canvas resolves `elementList` IDs → objects and
 * passes them here as `nestedElements`. In static JSON the host can also
 * supply `nestedElements` directly.
 */
import { computed } from "vue"
import type { CardElement } from "@/definitions/elements"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import ElementRenderer from "@/engine/ElementRenderer.vue"
import { cn } from "@/lib/utils"

export interface ListCardProps {
  label?: string
  title?: string
  subtitle?: string
  showCard?: boolean
  gutterY?: string
  gutterX?: string
  /** Resolved child elements passed by the engine / FormBuilder canvas. */
  nestedElements?: Array<Record<string, unknown>>
  item?: Record<string, unknown>
  classList?: string[] | string
}

const props = withDefaults(defineProps<ListCardProps>(), {
  showCard: true,
  gutterY: "1rem",
  gutterX: "0",
  nestedElements: () => [],
  item: () => ({}),
})

const heading = computed(() => props.title ?? props.label)

const children = computed(() =>
  (props.nestedElements ?? []).filter(
    (e): boolean =>
      typeof e === "object" &&
      e !== null &&
      typeof (e as Record<string, unknown>).type === "string",
  ) as unknown as CardElement[],
)

const bodyStyle = computed(() => ({
  rowGap: props.gutterY,
  columnGap: props.gutterX,
}))
</script>

<template>
  <Card
    v-if="props.showCard !== false"
    :class="cn(props.classList)"
    data-element-list-card
  >
    <CardHeader v-if="heading || props.subtitle">
      <CardTitle v-if="heading">{{ heading }}</CardTitle>
      <CardDescription v-if="props.subtitle">{{ props.subtitle }}</CardDescription>
    </CardHeader>
    <CardContent class="flex flex-col" :style="bodyStyle">
      <ElementRenderer
        v-for="child in children"
        :key="child.id"
        :element="child"
        :item="props.item"
      />
      <p v-if="!children.length" class="py-3 text-sm text-muted-foreground">
        No elements configured.
      </p>
    </CardContent>
  </Card>

  <div
    v-else
    class="flex flex-col"
    :class="cn(props.classList)"
    :style="bodyStyle"
    data-element-list-card
  >
    <ElementRenderer
      v-for="child in children"
      :key="child.id"
      :element="child"
      :item="props.item"
    />
  </div>
</template>
