<script setup>
import { computed, useSlots } from 'vue';

const props = defineProps({
  label: { type: String, default: null },
  labelFor: { type: String, default: null },
  help: { type: String, default: null },
  // Handles Inertia.js string errors or standard array errors
  errors: { type: [String, Array], default: null },
});

const slots = useSlots();

// Normalize errors to an array for consistent rendering
const errorList = computed(() => {
  if (!props.errors) return [];
  return Array.isArray(props.errors) ? props.errors : [props.errors];
});

const hasErrors = computed(() => errorList.value.length > 0);

const wrapperClass = computed(() => {
  const base = [];
  const children = slots.default?.().filter(node => node.type.toString() !== 'Symbol(v-cmt)') || [];
  
  // Apply grid logic only if there are multiple child controls
  if (children.length > 1) {
    base.push('grid grid-cols-1 gap-3');
    if (children.length === 2) base.push('md:grid-cols-2');
  }
  
  return base;
});
</script>

<template>
  <div class="mb-6 last:mb-0">
    <label 
      v-if="label" 
      :for="labelFor" 
      class="block font-bold text-xs uppercase tracking-wide mb-2 transition-colors duration-200"
      :class="hasErrors ? 'text-red-600 dark:text-red-400' : 'text-gray-700 dark:text-slate-300'"
    >
      {{ label }}
    </label>
    
    <div :class="wrapperClass">
      <slot />
    </div>

    <div class="mt-1 min-h-[1.25rem]">
      <transition-group 
        enter-active-class="transition duration-150 ease-out"
        enter-from-class="transform -translate-y-1 opacity-0"
        enter-to-class="transform translate-y-0 opacity-100"
      >
        <p 
          v-for="(error, index) in errorList" 
          :key="`err-${index}`"
          class="text-xs text-red-600 dark:text-red-400 italic font-medium"
        >
          {{ error }}
        </p>

        <p 
          v-if="!hasErrors && help" 
          key="help-text"
          class="text-xs text-gray-500 dark:text-slate-400"
        >
          {{ help }}
        </p>
      </transition-group>
    </div>
  </div>
</template>