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

    <AisCheckbox
      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) }}
    </AisCheckbox>

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

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


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

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

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

  if(props.modelValue) {
    // 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(() => {

    let displayClasses = [props.display]
    if(props.display === 'flex') displayClasses.push('flex-wrap')

    let gapClasses = ensureArray(props.gap)

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

  if(props.disabled) {
    provide(CONTROL_DISABLED, computed(() => props.disabled))
  }

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

  const groupSize = useSize(props)
  provide(CONTROL_SIZE, groupSize)
</script>
