<script setup lang="ts">
/**
 * Props-driven multi-select pill composition. Each option becomes a
 * toggleable Badge with multi-select semantics.
 *
 *   <PillSelectOption v-model="tags" :options="[...]" label="Tags" />
 */
import { computed } from "vue"
import type { SelectOptionLike } from "@/definitions/shared/select-options"
import { Badge } from "@/components/ui/badge"
import { FieldFrame } from "@/components/ui/field-frame"

export interface PillSelectOptionProps {
  modelValue?: Array<string | number> | null
  options?: SelectOptionLike[]
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  helpText?: string
  errors?: string[]
}

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

const model = defineModel<Array<string | number> | null>("modelValue")

interface NormalisedOption {
  label: string
  value: string
  disabled: boolean
}

function normaliseOption(opt: SelectOptionLike): NormalisedOption {
  if (typeof opt === "string") {
    return { label: opt, value: opt, disabled: false }
  }
  return {
    label: opt.label,
    value: String(opt.value),
    disabled: Boolean(opt.disabled),
  }
}

const normalised = computed<NormalisedOption[]>(() =>
  (props.options ?? []).map(normaliseOption),
)

const selected = computed<string[]>(() => {
  const v = model.value
  if (!v) {
    return []
  }
  if (Array.isArray(v)) {
    return v.map((x) => String(x))
  }
  return [String(v)]
})

function isActive(val: string): boolean {
  return selected.value.includes(val)
}

function togglePill(opt: NormalisedOption): void {
  if (opt.disabled || props.disabled || props.readonly) {
    return
  }
  const current = selected.value
  if (current.includes(opt.value)) {
    model.value = current.filter((v) => v !== opt.value)
  } else {
    model.value = [...current, opt.value]
  }
}
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :help-text="helpText"
    :errors="errors"
  >
    <div
      class="flex flex-wrap gap-2"
      :data-element-name="name ?? undefined"
    >
      <Badge
        v-for="opt in normalised"
        :key="opt.value"
        as="button"
        type="button"
        :variant="isActive(opt.value) ? 'default' : 'outline'"
        size="lg"
        :class="[
          'cursor-pointer transition-colors',
          opt.disabled || disabled || readonly
            ? 'pointer-events-none opacity-50'
            : '',
        ]"
        :data-active="isActive(opt.value)"
        :aria-pressed="isActive(opt.value)"
        @click="togglePill(opt)"
      >
        {{ opt.label }}
      </Badge>
    </div>
  </FieldFrame>
</template>
