<script setup lang="ts">
/**
 * `card.grid` element composition.
 *
 * Renders nested child elements in a CSS grid with configurable column
 * count and row height. Children are rendered via ElementRenderer; the
 * grid layout is controlled by `gridCols` and `gridRowHeight`.
 *
 * For a visual drag-and-drop grid designer use `builder.grid-builder`.
 * This element focuses on static configured layouts.
 */
import { computed } from "vue"
import type { CardElement } from "@/definitions/elements"
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import ElementRenderer from "@/engine/ElementRenderer.vue"
import { cn } from "@/lib/utils"

export interface GridCardProps {
  label?: string
  title?: string
  showCard?: boolean
  gridCols?: number
  gridRowHeight?: number
  nestedElements?: Array<Record<string, unknown>>
  item?: Record<string, unknown>
  classList?: string[] | string
}

const props = withDefaults(defineProps<GridCardProps>(), {
  showCard: true,
  gridCols: 3,
  gridRowHeight: 60,
  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 gridStyle = computed(() => ({
  display: "grid",
  gridTemplateColumns: `repeat(${props.gridCols}, minmax(0, 1fr))`,
  gridAutoRows: `${props.gridRowHeight}px`,
  gap: "0.5rem",
}))
</script>

<template>
  <Card v-if="props.showCard !== false" :class="cn(props.classList)">
    <CardHeader v-if="heading">
      <CardTitle>{{ heading }}</CardTitle>
    </CardHeader>
    <CardContent>
      <div :style="gridStyle">
        <ElementRenderer
          v-for="child in children"
          :key="child.id"
          :element="child"
          :item="props.item"
        />
        <p
          v-if="!children.length"
          class="col-span-full py-3 text-center text-sm text-muted-foreground"
        >
          No elements configured.
        </p>
      </div>
    </CardContent>
  </Card>

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