<script setup lang="ts">
/**
 * Props-driven renderer for `configuration-block/dialog`.
 *
 * Wraps the inner children (`nestedElements`) in a Dialog opened by a
 * trigger Button. Full FormBuilder integration arrives in task #7.
 */
import { computed } from "vue"
import { Construction } from "@lucide/vue"
import type { CardElement } from "@/definitions/elements"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import ElementRenderer from "@/engine/ElementRenderer.vue"
import { cn } from "@/lib/utils"

export interface DialogBlockProps {
  label?: string
  name?: string | null
  triggerLabel?: string
  title?: string
  nestedElements?: CardElement[]
  item?: Record<string, unknown>
  classList?: string[] | string
}

const props = withDefaults(defineProps<DialogBlockProps>(), {
  label: "Dialog",
  nestedElements: () => [],
  item: () => ({}),
})

const styleKey = "dialog"

const resolvedTrigger = computed(
  () => props.triggerLabel ?? props.label ?? "Open dialog",
)
const resolvedTitle = computed(
  () => props.title ?? props.label ?? "Dialog",
)

const children = computed<CardElement[]>(() =>
  (props.nestedElements ?? []).filter(
    (entry): entry is CardElement =>
      typeof entry === "object" &&
      entry !== null &&
      typeof (entry as { type?: unknown }).type === "string",
  ),
)
</script>

<template>
  <Dialog>
    <DialogTrigger as-child>
      <Button
        type="button"
        variant="outline"
        :class="cn(props.classList)"
        :data-element-name="props.name ?? undefined"
        :data-stub="`configuration-block/${styleKey}`"
        :aria-label="props.label"
      >
        <Construction class="size-4" />
        {{ resolvedTrigger }}
        <Badge variant="outline" size="sm">{{ styleKey }}</Badge>
      </Button>
    </DialogTrigger>
    <DialogContent>
      <DialogHeader>
        <DialogTitle>{{ resolvedTitle }}</DialogTitle>
      </DialogHeader>
      <div v-if="children.length" class="flex flex-col gap-3">
        <ElementRenderer
          v-for="child in children"
          :key="child.id"
          :element="child"
          :item="props.item"
        />
      </div>
      <p v-else class="text-sm text-muted-foreground">
        Dialog block — FormBuilder integration coming in task #7.
      </p>
    </DialogContent>
  </Dialog>
</template>
