export const AUTH_SHELL_BACKDROP_ID = 'hypertwist-auth-shell-backdrop'

function applyAuthShellBackdropStyles(backdrop: HTMLElement) {
  backdrop.id = AUTH_SHELL_BACKDROP_ID
  backdrop.setAttribute('data-testid', 'supertokens-auth-backdrop')
  backdrop.setAttribute('aria-hidden', 'true')
  backdrop.style.position = 'fixed'
  backdrop.style.inset = '0'
  backdrop.style.zIndex = '0'
  backdrop.style.pointerEvents = 'none'
  backdrop.style.background =
    'radial-gradient(circle at top, rgba(84,203,255,0.12), transparent 32%), radial-gradient(circle at 82% 14%, rgba(247,178,103,0.12), transparent 24%), linear-gradient(180deg, rgba(9,12,24,0.26), rgba(7,10,19,0.38))'
}

export function isAuthShellRoute(pathname: string) {
  return pathname === '/login'
    || pathname.startsWith('/login/')
    || pathname === '/register'
    || pathname.startsWith('/register/')
    || pathname.startsWith('/auth/')
}

export function ensureAuthShellBackdrop(doc: Document = document) {
  const existingBackdrop = doc.getElementById(AUTH_SHELL_BACKDROP_ID)
  if (existingBackdrop instanceof HTMLElement) {
    applyAuthShellBackdropStyles(existingBackdrop)
    return existingBackdrop
  }

  const backdrop = doc.createElement('div')
  applyAuthShellBackdropStyles(backdrop)
  doc.body.appendChild(backdrop)
  return backdrop
}

export function syncAuthShellBackdrop(pathname: string, doc: Document = document) {
  const shouldRender = isAuthShellRoute(pathname)
  const existingBackdrop = doc.getElementById(AUTH_SHELL_BACKDROP_ID)

  if (!shouldRender) {
    existingBackdrop?.remove()
    return
  }

  ensureAuthShellBackdrop(doc)
}
