'use client'

import { useEffect } from 'react'

function resolveAdminNextPath(next: string | null) {
  const fallback = '/admin/dashboard'
  if (!next) return fallback

  if (/^https?:\/\//i.test(next)) return next
  if (next.startsWith('/admin/')) return next
  if (next === '/admin') return '/admin/dashboard'
  if (next.startsWith('/')) return `/admin${next}`

  return `/admin/${next.replace(/^\/+/, '')}`
}

export default function AuthRedirectPage() {
  useEffect(() => {
    const hash = window.location.hash
    const params = new URLSearchParams(hash.replace(/^#/, ''))
    const next = resolveAdminNextPath(params.get('next'))

    // Clear legacy token fragments from the URL. Admin auth now uses an HttpOnly cookie.
    window.history.replaceState(null, '', window.location.pathname)

    window.location.replace(next)
  }, [])

  return (
    <div className="flex min-h-screen items-center justify-center bg-zinc-950">
      <p className="text-sm text-zinc-400">Redirecting to admin dashboard…</p>
    </div>
  )
}
