<script setup lang="ts">
/**
 * Props-driven range slider composition. Wraps the shadcn `Slider`
 * primitive (which always emits an array internally) and exposes a
 * scalar `modelValue` to the consumer.
 *
 * Self-contained — usable directly in any Vue app:
 *
 *   <RangeSliderInput v-model="volume" label="Volume" :min="0" :max="100" />
 */
import { computed } from "vue"
import { Slider } from "@/components/ui/slider"
import { FieldFrame } from "@/components/ui/field-frame"

export interface RangeSliderInputProps {
  modelValue?: number
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  min?: number
  max?: number
  step?: number
  helpText?: string
  errors?: string[]
}

const props = withDefaults(defineProps<RangeSliderInputProps>(), {
  min: 0,
  max: 100,
  step: 1,
  errors: () => [],
})

const model = defineModel<number>("modelValue")

const currentValue = computed<number>(() =>
  typeof model.value === "number" ? model.value : props.min,
)

const sliderModel = computed<number[]>(() => [currentValue.value])

function onUpdate(...args: unknown[]): void {
  const next = args[0]
  if (Array.isArray(next)) {
    const first = next[0]
    model.value = typeof first === "number" ? first : props.min
  }
  else if (typeof next === "number") {
    model.value = next
  }
  else {
    model.value = props.min
  }
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <div class="flex items-center gap-3">
      <Slider
        :id="id"
        :name="name ?? undefined"
        :min="min"
        :max="max"
        :step="step"
        :disabled="disabled || readonly"
        :model-value="sliderModel"
        :data-element-name="name ?? undefined"
        class="flex-1"
        @update:model-value="onUpdate"
      />
      <span
        class="min-w-10 text-right text-sm text-muted-foreground tabular-nums"
        data-testid="range-slider-value"
      >
        {{ currentValue }}
      </span>
    </div>
  </FieldFrame>
</template>
