const { h, matter } = globalThis.ami

const SHORT_FIELD = 'lg:w-20 md:w-full sm:w-full shrink-0'
const HALF_FIELD = 'lg:w-1/2 md:w-full sm:w-full'

function Subfield ({ field, name, className }) {
  const subfield = field.subfields[name]
  if (!subfield) {
    return null
  }

  const id = `${field.attrs.name}[${name}]`
  return h('div', { className },
    h(matter.Input, {
      ...field.attrs,
      className: 'w-full',
      name: id,
      id,
      'data-label': subfield.label
    }),
    h('label', { for: id, className: 'text-sm' }, subfield.label)
  )
}

export function Name ({ field }) {
  const label = field.required === '1' ? `${field.label} *` : field.label

  return h('fieldset',
    h('legend', { className: 'block font-bold' }, label),
    h('div', { className: 'flex flex-row gap-x-5 md:flex-col sm:flex-col' },
      h(Subfield, { field, name: 'prefix', className: SHORT_FIELD }),
      h(Subfield, { field, name: 'first', className: HALF_FIELD }),
      h(Subfield, { field, name: 'middle', className: SHORT_FIELD }),
      h(Subfield, { field, name: 'initial', className: SHORT_FIELD }),
      h(Subfield, { field, name: 'last', className: HALF_FIELD }),
      h(Subfield, { field, name: 'suffix', className: SHORT_FIELD })
    )
  )
}
