/**
 * EdGEL loading spinner.
 */
if (!document.body) {
  throw new Error('The preloader.js script should be loaded in the body.')
}

// Hide the body content and mark page as busy for assistive technologies.
document.body.classList.add('preloader')
document.body.setAttribute('aria-busy', 'true')

// Add the preloader to the body.
const preloader = document.createElement('div')
preloader.setAttribute('role', 'status')
preloader.setAttribute('aria-label', 'Please wait, content loading...')
preloader.className = 'preloader-spinner'
preloader.append(document.createElement('div'))
preloader.append(document.createElement('div'))
preloader.append(document.createElement('div'))
preloader.append(document.createElement('div'))
document.body.prepend(preloader)

// Remove the preloader and stop hiding content when we receive the page.edgel.custom-element custom event.
// This is raised by the EdGELPage element lit-element.
globalThis.addEventListener('loaded.edgel.preloader', () => {
  const element = document.querySelector('.preloader-spinner')
  if (element) {
    element.remove()
  }

  document.body.setAttribute('aria-busy', 'false')
  document.body.classList.remove('preloader')
}, { once: true })
