<script setup lang="ts">
/**
 * Props-driven renderer for `configuration-block/modal`.
 *
 * Sister to DialogBlock — wraps inner children (`nestedElements`) in a
 * full-bleed Sheet-style modal 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 {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet"
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 ModalBlockProps {
  label?: string
  name?: string | null
  triggerLabel?: string
  title?: string
  nestedElements?: CardElement[]
  item?: Record<string, unknown>
  classList?: string[] | string
}

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

const styleKey = "modal"

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

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>
  <Sheet>
    <SheetTrigger 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>
    </SheetTrigger>
    <SheetContent side="right" class="sm:max-w-xl">
      <SheetHeader>
        <SheetTitle>{{ resolvedTitle }}</SheetTitle>
      </SheetHeader>
      <div v-if="children.length" class="flex flex-col gap-3 py-4">
        <ElementRenderer
          v-for="child in children"
          :key="child.id"
          :element="child"
          :item="props.item"
        />
      </div>
      <p v-else class="py-4 text-sm text-muted-foreground">
        Modal block — FormBuilder integration coming in task #7.
      </p>
    </SheetContent>
  </Sheet>
</template>
