// src/pages/AuthCallbackPage.tsx
import { useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { userManager } from 'auth/oidc' // behåll alias/relativt enligt ditt projekt

// Hjälpare: plocka ut returnTo från okänt state
function pickReturnTo(state: unknown): string | undefined {
  if (state && typeof state === 'object' && 'returnTo' in state) {
    const v = (state as Record<string, unknown>).returnTo
    return typeof v === 'string' ? v : undefined
  }
  return undefined
}

export default function AuthCallbackPage() {
  const navigate = useNavigate()
  const handled = useRef(false)

  useEffect(() => {
    if (handled.current) return
    handled.current = true

    ;(async () => {
      try {
        const res = await userManager.signinRedirectCallback()
        const target = pickReturnTo(res?.state) ?? '/'
        // Städa bort ?code&state ur URL:en:
        window.history.replaceState({}, '', target)
        navigate(target, { replace: true })
      } catch (err) {
        console.error('signinRedirectCallback failed:', err)
        navigate('/', { replace: true })
      }
    })()
  }, [navigate])

  return <p>Completing sign-in…</p>
}
