<template>
    <div class="" :class="classes">
        <slot name="head" />

        <AisRadio
          v-for="option in options"
          v-model="model"
          :key="optionValue(option, props.valueKey)"
          :value="optionValue(option, props.valueKey)"
          :icon="optionIcon(option, props.iconKey)"
          :disabled="props.disabled || optionDisabled(option, props.disabledKey)"
        >
          {{ optionLabel(option, props.labelKey) }}
        </AisRadio>

        <slot name="default"></slot>
    </div>
</template>

<script setup>
    import { computed, provide } from 'vue'
    import {useVModel} from '@vueuse/core'
    import AisRadio from "@/components/radio/AisRadio.vue";
    import {radioGroupProps} from "@/components/radio-group/radio-group";
    import {ensureArray} from "@/util/util";
    import {optionValue, optionLabel, optionIcon, optionDisabled} from "@/util/label-value";
    import {
      CONTROL_MODEL, CONTROL_PARENT_UPDATE,
      CONTROL_NAME, CONTROL_SIZE, CONTROL_DISABLED,
    } from "@/util/controls";
    import {useInjectedProp, useSize} from "@/composables/useInjections";


    const props = defineProps({
      ...radioGroupProps
    })

    const emit = defineEmits([
      'update:modelValue'
    ])

    const model = useVModel(props, 'modelValue', emit)

    // Provide the group's v-model to child components
    provide(CONTROL_MODEL, computed(() => props.modelValue))

    // Allow children accepting injected model to trigger parent update
    provide(CONTROL_PARENT_UPDATE, (value) => emit('update:modelValue', value))

    const classes = computed(() => {

      if(props.buttons) {
        return ['bttn-group', props.display === 'grid' ? 'vertical' : '']
      } else {
        let displayClasses = [props.display]
        if (props.display === 'flex') displayClasses.push('flex-wrap')

        let gapClasses = ensureArray(props.gap)

        return [
          ...displayClasses,
          ...gapClasses,
        ]
      }
    })

    const injectedDisabled = useInjectedProp(CONTROL_DISABLED, props, 'disabled')
    const fieldDisabled = computed(() => injectedDisabled.value || props.disabled)
    provide(CONTROL_DISABLED, fieldDisabled)

    if(props.name) {
      provide(CONTROL_NAME, computed(() => props.name))
    }

    const groupSize = useSize(props)
    provide(CONTROL_SIZE, groupSize)

    provide( 'isButtons', computed(() => props.buttons) )
    provide( 'buttonVariant', computed(() => props.buttonVariant) )
    provide( 'buttonFont', computed(() => props.buttonFont) )
</script>
