/* global location */
const { h, register, matter, preactHooks } = globalThis.ami
const { Box, Link } = matter
const { useState, useEffect } = preactHooks

function ExampleRouting () {
  const [state, setState] = useState(getSuffix())

  useEffect(() => {
    globalThis.addEventListener('popstate', () => setState(getSuffix()))
  })

  return h(Box, { className: 'bg-bga text-txa rounded-2xl' },
    h('p', `Current suffix: ${state}`),
    h('div', { className: 'space-x-2' },
      h(Link, {
        _variant: 'underline',
        _model: {
          name: 'Link 1',
          value: setSuffix('/suffix/1')
        }
      }),
      h(Link, {
        _variant: 'underline',
        _model: {
          name: 'Link 2',
          value: setSuffix('/suffix/2')
        }
      })
    )
  )
}

function getSuffix () {
  return location.pathname.split('.html')[1]
}

function setSuffix (suffix) {
  const url = new URL(location)

  const index = url.pathname.indexOf('.html')
  let pathname = url.pathname.substring(0, index + 5)
  if (pathname.endsWith('/')) {
    pathname = `${pathname}index.html`
  }

  url.pathname = pathname + suffix
  return url.href
}

register(ExampleRouting, 'example-routing')
