<script setup lang="ts">
/**
 * Props-driven switch composition. Wraps the shadcn-vue Switch primitive
 * with `FieldFrame` chrome.
 *
 *   <SwitchBoolean v-model="notifications" label="Notifications" />
 *   <SwitchBoolean
 *     v-model="online"
 *     label="Visibility"
 *     true-label="Online"
 *     false-label="Offline"
 *   />
 */
import { computed } from "vue"
import { Switch } from "@/components/ui/switch"
import { Label } from "@/components/ui/label"
import { FieldFrame } from "@/components/ui/field-frame"

export interface SwitchBooleanProps {
  modelValue?: boolean
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
  /** Optional label suffix shown when the value is true. */
  trueLabel?: string
  /** Optional label suffix shown when the value is false. */
  falseLabel?: string
}

const props = withDefaults(defineProps<SwitchBooleanProps>(), {
  errors: () => [],
})

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

const stateLabel = computed(() =>
  model.value
    ? (props.trueLabel ?? "")
    : (props.falseLabel ?? ""),
)

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

<template>
  <FieldFrame
    :hide-label="true"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <div class="flex items-center gap-3">
      <Switch
        :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"
        data-testid="field-frame-label"
      >
        {{ label }}
        <span
          v-if="stateLabel"
          class="ml-2 text-xs font-normal text-muted-foreground"
        >
          ({{ stateLabel }})
        </span>
      </Label>
      <span
        v-else-if="label"
        class="sr-only"
        data-testid="field-frame-label-sr"
      >
        {{ label }}
      </span>
    </div>
  </FieldFrame>
</template>
