import h from '#amidala/main/shared/h.js'

const COLUMNS = 12

function getTabletColspan (desktopColspan) {
  // Preserve full width on table only if desktop width is 10 columns or more.
  return desktopColspan < 10 ? 1 : 2
}

export function Grid ({ _tag, _wrap, _parentColspan = COLUMNS, _list, _gap, children, ...props }) {
  const wrappedChildren = []
  for (const [ii, child] of children.entries()) {
    const wrap = _wrap?.[ii] ?? {}
    const colstart = Math.min(_parentColspan, wrap.colstart ?? 0)
    const colspan = Math.min(_parentColspan, wrap.colspan ?? COLUMNS)

    let colstartClass = colstart ? `lg:col-start-${colstart}` : ''
    if (colstart === 1) {
      colstartClass += ' md:col-start-1'
    }

    wrappedChildren.push(h('div', {
      className: `lg:col-span-${colspan ?? COLUMNS} md:col-span-${getTabletColspan(colspan)} sm:col-span-1 ${colstartClass}`,
      ..._list && { role: 'listitem' },
      children: child
    }))
  }

  const gapClass = _gap ? 'gap-5' : ''
  return h(_tag || 'div', {
    ..._list && { role: 'list' },
    ...props,
    children: wrappedChildren,
    className: `grid lg:grid-cols-${_parentColspan} md:grid-cols-${getTabletColspan(_parentColspan)} sm:grid-cols-1 ${gapClass}`
  })
}
