import ICON_CART from './icon-cart.svg'

const { h, preactHooks, matter, register } = globalThis.ami
const { useMemo, useState } = preactHooks
const { Box, Button, Heading, Link } = matter

const IS_PUBLISH = document.documentElement.dataset.mode === 'publish'
const VISIBLE_VENDOR_COUNT = 3

const getSpaceSeparatedValues = text => {
  const [, name, value] = text?.match(/^(.*)\s(\S+)$/) || []
  return (name && value) ? { name, value } : null
}

function ProductLinks ({ heading = 'Buy now', 'view-more': viewMore = 'View more retailers', ...props }) {
  const [isExpanded, setIsExpanded] = useState(false)

  const vendors = useMemo(() =>
    Object.entries(props)
      .filter(([propName]) => propName.startsWith('vendor-'))
      .map(([, propValue], i) => {
        const parserVals = getSpaceSeparatedValues(propValue)
        return parserVals ? { ...parserVals, order: i === 0 ? -1 : Math.random() } : null // eslint-disable-line sonarjs/pseudo-random
      })
      .filter(Boolean) // Filter out empty/incorrect values.
      .sort((v1, v2) => IS_PUBLISH ? v1.order - v2.order : 0), // Randomize order for publish mode (except for the first link).
  [])

  if (!vendors.length) {
    return null
  }

  return h(Box, { className: 'rounded-2xl bg-bga text-txa space-y-5' },
    h(Heading, { _level: 2 }, heading),
    ...vendors.map((vendor, i) =>
      (isExpanded || i < VISIBLE_VENDOR_COUNT) && h(Button, { _model: { ...vendor, icon: ICON_CART }, _wide: true })
    ),
    !isExpanded && (vendors.length > VISIBLE_VENDOR_COUNT) &&
      h(Link, { _variant: 'full', _model: { name: viewMore }, onClick: () => setIsExpanded(true) })
  )
}

register(ProductLinks, 'product-links')
