<script setup lang="ts">
/**
 * Props-driven checkbox composition. Wraps the shadcn-vue Checkbox
 * primitive with `FieldFrame` chrome (label + helpText + errors).
 *
 *   <CheckboxBoolean v-model="agreed" label="I agree" required />
 */
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { FieldFrame } from "@/components/ui/field-frame"

export interface CheckboxBooleanProps {
  modelValue?: boolean
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
}

withDefaults(defineProps<CheckboxBooleanProps>(), {
  errors: () => [],
})

const model = defineModel<boolean>("modelValue", { default: false })

function onUpdate(checked: boolean | "indeterminate"): void {
  model.value = checked === true
}
</script>

<template>
  <FieldFrame
    :hide-label="true"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <div class="flex items-start gap-2">
      <Checkbox
        :id="id"
        :name="name"
        :disabled="disabled || readonly"
        :required="required"
        :model-value="model"
        :data-element-name="name ?? undefined"
        @update:model-value="onUpdate"
      />
      <Label
        v-if="!hideLabel && label"
        :for="id"
        :required="required"
        class="cursor-pointer leading-tight"
        data-testid="field-frame-label"
      >
        {{ label }}
      </Label>
      <span
        v-else-if="label"
        class="sr-only"
        data-testid="field-frame-label-sr"
      >
        {{ label }}
      </span>
    </div>
  </FieldFrame>
</template>
