import { Icon } from '../atoms/icon.js'
import { Asset } from '../molecules/asset.js'
import { PromoText } from '../molecules/promo-text.js'
import { ValidationError } from '../routing/error-handler.js'
import h from '../shared/h.js'

export function ListItem ({ _model, ...props }) {
  // Title and either asset or icon are required.
  const { title, asset, links } = _model
  if (!title || !(asset.src || links[0]?.icon)) {
    throw new ValidationError()
  }

  return h('div', {
    ...props,
    className: 'bg-bga text-txa rounded-2xl flex flex-row h-full',
    children: [
      h(AssetOrIcon, { _model }),
      h(PromoText, {
        _model: {
          ..._model,
          links: links.filter(l => l.name).map(l => ({ ...l, icon: null }))
        },
        _variant: 'full'
      })
    ]
  })
}

function AssetOrIcon ({ _model }) {
  const { links, asset } = _model
  const hasAsset = asset.src
  const icon = links[0]?.icon

  if (hasAsset) {
    return h('div', { className: 'w-1/3 grow-0 shrink-0 py-6 ps-6' },
      h('div', { className: 'rounded-lg overflow-hidden' },
        h(Asset, { _model, role: 'presentation' })
      )
    )
  }

  return h('div', { className: 'shrink-0 ps-6 py-6' },
    h('div', { className: 'bg-bgb text-txb w-16 h-16 flex items-center justify-center rounded-full' },
      h(Icon, icon)
    )
  )
}
