<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const message = ref('Завершаем вход через Microsoft...')

onMounted(async () => {
  const code = typeof route.query.code === 'string' ? route.query.code : ''
  const state = typeof route.query.state === 'string' ? route.query.state : null
  const error =
    typeof route.query.error_description === 'string' ? route.query.error_description : ''
  const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, ''))
  const accessToken = hashParams.get('access_token')

  try {
    if (error) throw new Error(error)
    if (accessToken) await auth.completeTokenLogin(accessToken)
    else if (code) await auth.completeMicrosoftLogin(code, state)
    else throw new Error('Microsoft не вернул токен авторизации.')

    window.history.replaceState({}, document.title, window.location.pathname)
    const role = auth.user?.activeRole
    if (role === 'teacher') await router.replace('/teacher')
    else if (role === 'admin') await router.replace('/admin')
    else await router.replace('/')
  } catch (err) {
    message.value = err instanceof Error ? err.message : 'Не удалось завершить авторизацию.'
    window.setTimeout(
      () => router.replace({ path: '/login', query: { error: message.value } }),
      1600,
    )
  }
})
</script>

<template>
  <div class="callback-bg">
    <div class="callback-card">
      <div class="spinner"></div>
      <h1>Вход в UniVerse</h1>
      <p>{{ message }}</p>
    </div>
  </div>
</template>

<style scoped>
.callback-bg {
  min-height: 100vh;
  background: var(--gradient-bg);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
}
.callback-card {
  width: min(420px, 100%);
  background: rgba(255, 255, 255, 0.86);
  border: 1px solid var(--color-border-glass);
  border-radius: var(--radius-lg);
  padding: 32px;
  text-align: center;
  box-shadow: 0 24px 70px rgba(0, 0, 0, 0.12);
}
.spinner {
  margin: 0 auto 16px;
}
h1 {
  font-size: 24px;
  margin: 0 0 8px;
}
p {
  color: var(--color-text-secondary);
  margin: 0;
}
</style>
