const { h, register } = globalThis.ami

const PADDING = 14

function BazaarVoice ({ src, product = '', features = '' }) {
  if (!src) {
    console.error('Missing data source.')
    return null
  }

  return h('iframe', {
    // Set temporary source to spoof Bazaarvoice as it needs an origin.
    // - Using current origin allows to interact with the iframe without CORS issues.
    // - The do-not-render parameter prevents Amidala from rendering - see router.js.
    src: `${location.origin}${location.pathname}?do-not-render`,
    height: 0,
    style: 'background: white',
    className: 'block border box-content w-full hidden rounded-2xl animate-fade border-txa/20',
    onLoad: event => createWidget(event.target, src, product, features)
  })
}

function createWidget (iframe, src, product, features) {
  const doc = iframe.contentWindow.document
  const body = doc.body

  body.innerHTML = ''
  body.style = `margin: 0; padding: ${PADDING}px; overflow: hidden`
  iframe.classList.remove('hidden')

  const wrapper = doc.createElement('div')
  body.appendChild(wrapper)

  const featureArr = features.split(/ +/)
  for (const feature of featureArr) {
    const div = document.createElement('div')
    div.dataset.bvShow = feature
    div.dataset.bvProductId = product
    wrapper.appendChild(div)
  }

  // Watch for changes.
  const observer = new MutationObserver(() => {
    iframe.height = `${wrapper.scrollHeight + 2 * PADDING}px`
  })

  // Start observing body.
  observer.observe(body, { attributes: true, childList: true, subtree: true })

  // Add Bazaarvoice script.
  const script = doc.createElement('script')
  script.src = src
  body.appendChild(script)
}

register(BazaarVoice, 'bazaar-voice')
