export function getSuffix () {
  const url = getUrl()
  return url.pathname.split('.html/')[1]
}

export function updateSuffix (suffix) {
  const url = getUrl()
  const currentSuffix = getSuffix()

  url.pathname = `${url.pathname.split('.html')[0]}.html`

  if (suffix) {
    url.pathname += `/${suffix}`
    url.hash = ''
  } else {
    url.hash = `#_${currentSuffix}`
  }

  return url.toString()
}

export function setParams (params) {
  const url = new URL(location.href)
  url.hash = ''

  for (const [name, value] of Object.entries(params)) {
    value
      ? url.searchParams.set(name, value)
      : url.searchParams.delete(name)
  }

  route(url)
}

export function getParam (name) {
  const url = new URL(location.href)
  return url.searchParams.get(name)
}

export function route (url) {
  history.pushState({}, '', url)
  globalThis.dispatchEvent(new Event('popstate'))
}

function getUrl () {
  const url = new URL(location.href)

  // Hack for homepage.
  if (url.pathname === '/') {
    url.pathname = '/_jcr_content.html'
  }

  return url
}
