const { h, matter } = globalThis.ami

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,
      type: subfield.options ? 'select' : field.attrs.type,
      'data-label': subfield.label,
      children: subfield.options?.map(option => h('option', { value: option.value }, option.name))
    }),
    h('label', { for: id, className: 'text-sm' }, subfield.label)
  )
}

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

  return h('fieldset',
    h('legend', { className: 'block font-bold' }, label),
    h(Subfield, { field, name: 'address' }),
    h(Subfield, { field, name: 'address2' }),
    h('div', { className: 'flex flex-row gap-x-5 md:flex-col sm:flex-col' },
      h(Subfield, { field, name: 'city', className: 'w-full' }),
      h(Subfield, { field, name: 'state', className: 'w-full' }),
      h(Subfield, { field, name: 'zip', className: 'shrink-0 lg:w-20 md:w-full sm:w-full' })
    ),
    h(Subfield, { field, name: 'country' })
  )
}
