<template>
  <fieldset :class="fieldsetClasses" :disabled="fieldDisabled">
    <legend v-if="legend" class="px-0.5 font-semibold text-lg" :class="disabledClasses">
      {{legend}}
    </legend>
    <slot />
  </fieldset>
</template>

<script setup>
  import { computed, provide, inject } from 'vue'
  import { CONTROL_SIZE, CONTROL_DISABLED } from "@/util/controls";
  import {expectedValues} from "@/util/prop-validators";
  import {useInjectedProp, useSize} from "@/composables/useInjections";

  const props = defineProps({
    legend: { type: String, required: false, default: undefined },

    size: {
      type: String, required: false, default: undefined,
      validator: expectedValues('sm', 'md', 'lg')
    },

    disabled: { type: Boolean, required: false, default: false },
  })

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

  const fieldDisabled = useInjectedProp(CONTROL_DISABLED, props, 'disabled', false)
  provide(CONTROL_DISABLED, fieldDisabled)

  const fieldsetClasses = computed(() => {
    let classes = []
    if(fieldsetSize.value) classes.push(fieldsetSize.value)
    return classes
  })

  const disabledClasses = computed(() => {
    let classes = []
    if(fieldDisabled.value) classes.push('opacity-60', 'cursor-not-allowed')
    return classes
  })
</script>
