import { Link } from '../atoms/link.js'
import { RichText } from '../atoms/rich-text.js'
import { Table } from '../atoms/table.js'
import { Asset } from '../molecules/asset.js'
import formatTime from '../shared/format-time.js'
import h from '../shared/h.js'

export function Glossary ({ _model, ...props }) {
  const { title, text, tags, links, image, video, asset, date } = _model

  const list = []
  title && list.push({ name: 'title', value: title })
  text && list.push({ name: 'text', value: h(RichText, text) })
  date && list.push({ name: 'date', value: formatTime(date) })
  tags.length > 0 && list.push({ name: 'tags', value: tags.map(t => t.name).join(', ') })

  list.push(...links.map((l, ii) => ({
    name: `link\u00A0${ii + 1}`,
    value: h(Link, { _model: { ...l, name: `${l.name} (${l.value})` } })
  })))

  const hasAsset = asset?.src
  return h('div', { ...props, className: 'grid gap-5 grid-cols-12 px-6 py-4 text-sm bg-bga text-txa w-full' },
    list.length === 0 && h('div', { className: 'col-span-12' }, 'No data'),
    list.length > 0 && [
      h('div', { className: hasAsset ? 'col-span-10' : 'col-span-12' },
        h(Table,
          h('tbody', list.map(item =>
            h('tr', [
              h('th', item.name),
              h('td', item.value)
            ])
          ))
        )
      ),
      hasAsset && h('figure', { className: 'col-span-2 space-y-1' },
        h('div', { className: 'rounded-lg overflow-hidden' },
          h(Asset, { _model: { image, video } })
        ),
        asset.caption && h('figcaption', asset.caption)
      )
    ]
  )
}
