<!--
  FieldInput.vue — Generic field renderer driven by a field descriptor.

  Renders the right Quasar input based on `field.type`. Adding a new field
  type = adding a branch here. Used by StepEditorModal.

  Props:
    - field:      { name, type, label, required, options, placeholder, help, rows }
    - modelValue: current value (v-model)

  Events:
    - update:modelValue(newValue)

  Supported types:
    - 'text'      → q-input type=text
    - 'textarea'  → q-input type=textarea
    - 'number'    → q-input type=number
    - 'select'    → q-select with options
    - 'datetime'  → q-input type=datetime-local
    - 'json'      → q-input textarea with JSON.parse/stringify on blur
    - 'webhook'   → q-input with URL validation
-->
<template>
  <component :is="inputComponent" v-bind="inputProps" />
</template>

<script setup>
import { computed, h } from 'vue'
import { QInput, QSelect } from 'quasar'

const props = defineProps({
  field:      { type: Object, required: true },
  modelValue: { default: null },
})

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

/** Pick the Quasar component based on field.type. */
const inputComponent = computed(() => {
  return props.field.type === 'select' ? QSelect : QInput
})

/** Props passed to the chosen component, computed once per render. */
const inputProps = computed(() => {
  const f = props.field
  const base = {
    'model-value': props.modelValue ?? '',
    'onUpdate:modelValue': (v) => emit('update:modelValue', v),
    label: f.label + (f.required ? ' *' : ''),
    'stack-label': true,
    dense: true,
    outlined: true,
    hint: f.help,
    placeholder: f.placeholder,
  }

  if (f.type === 'select') {
    return {
      ...base,
      options: (f.options || []).map(o => typeof o === 'string' ? { label: o, value: o } : o),
      'emit-value': true,
      'map-options': true,
    }
  }

  if (f.type === 'textarea' || f.type === 'json') {
    return { ...base, type: 'textarea', rows: f.rows || 3, autogrow: false }
  }

  if (f.type === 'number') return { ...base, type: 'number' }
  if (f.type === 'datetime') return { ...base, type: 'datetime-local' }

  // 'text' | 'webhook' | default
  return { ...base, type: 'text' }
})
</script>
