document.addEventListener('DOMContentLoaded', function () {

  // Inline error auto-dismiss (wp-login.php)
  var errorElement = document.querySelector('.seslp-logins .seslp-inline-error.is-error')
  if (errorElement) {
    setTimeout(function () {
      errorElement.classList.add('is-dismissed')
    }, 5000)
  }

  // Clean up Facebook's trailing fragment `#_=_` after OAuth redirect
  if (window.location && window.location.hash === '#_=_') {
    if (window.history && typeof window.history.replaceState === 'function') {
      window.history.replaceState(null, document.title, window.location.href.split('#')[0])
    } else {
      window.location.hash = ''
    }
  }

  // Toast notification for frontend error redirects
  var params = new URLSearchParams(window.location.search)
  var errCode = params.get('seslp_err')

  if (errCode && !document.querySelector('.login')) {
    var messages = (typeof SESLP !== 'undefined' && SESLP.errorMessages) ? SESLP.errorMessages : {}
    var msg = messages[errCode] || messages['_default'] || ''
    if (msg) {
      showSeslpToast(msg)

      // Clean seslp_err from URL without page reload
      params.delete('seslp_err')
      var cleanUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '')
      window.history.replaceState(null, document.title, cleanUrl)
    }
  }

  function showSeslpToast(message) {
    var toast = document.createElement('div')
    toast.className = 'seslp-toast'
    toast.setAttribute('role', 'alert')
    toast.setAttribute('aria-live', 'assertive')
    toast.innerHTML =
      '<span class="seslp-toast-icon" aria-hidden="true"></span>' +
      '<span class="seslp-toast-msg">' + escapeHtml(message) + '</span>' +
      '<span class="seslp-toast-close" role="button" tabindex="0" aria-label="닫기">&times;</span>'

    document.body.appendChild(toast)

    // Trigger slide-in
    requestAnimationFrame(function () {
      requestAnimationFrame(function () {
        toast.classList.add('seslp-toast-visible')
      })
    })

    var timer = setTimeout(function () { dismissToast(toast) }, 5000)

    toast.querySelector('.seslp-toast-close').addEventListener('click', function () {
      clearTimeout(timer)
      dismissToast(toast)
    })
  }

  function dismissToast(toast) {
    toast.classList.remove('seslp-toast-visible')
    toast.classList.add('seslp-toast-hiding')
    toast.addEventListener('transitionend', function () {
      if (toast.parentNode) toast.parentNode.removeChild(toast)
    }, { once: true })
  }

  function escapeHtml(str) {
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
  }

})
