<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'

import { useAuthStore } from '../stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const errorMessage = ref('')
const statusMessage = ref('Twitch Login wird abgeschlossen...')

const hasError = computed(() => Boolean(errorMessage.value))

onMounted(async () => {
  const params = readCallbackParams()
  const returnUrl = normalizeReturnUrl(params.get('returnUrl'))
  const status = params.get('status')
  const sessionToken = params.get('sessionToken')
  const message = params.get('message')

  window.history.replaceState(null, '', '/auth/twitch/callback')

  if (status === 'error') {
    errorMessage.value = message || 'Twitch Login konnte nicht abgeschlossen werden.'
    return
  }

  try {
    if (sessionToken) {
      await authStore.completeOAuthSession(sessionToken)
    } else if (!authStore.hydrated) {
      await authStore.hydrate()
    }

    if (authStore.session?.mustChangePassword) {
      await router.replace({ name: 'login', query: { redirect: returnUrl, change: 'password' } })
      return
    }

    statusMessage.value = status === 'connected'
      ? 'Twitch Account wurde verbunden.'
      : 'Twitch Login war erfolgreich.'
    await router.replace(returnUrl)
  } catch (error) {
    errorMessage.value = error instanceof Error
      ? error.message
      : 'Twitch Login konnte nicht abgeschlossen werden.'
  }
})

function readCallbackParams() {
  const hash = window.location.hash.startsWith('#')
    ? window.location.hash.slice(1)
    : window.location.hash

  return new URLSearchParams(hash || window.location.search.replace(/^\?/, ''))
}

function normalizeReturnUrl(value: string | null) {
  if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/auth/twitch/callback')) {
    return '/admin'
  }

  return value
}
</script>

<template>
  <main class="twitch-callback-page">
    <section class="twitch-callback-card" aria-live="polite">
      <div class="twitch-callback-card__icon" aria-hidden="true">
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
          <path d="M4 2L2.4 6v14.5h5V23h2.7l2.5-2.5h4L21.6 16V2H4zm15.3 13.1l-2.9 2.9h-4.4l-2.5 2.5v-2.5H6.7V3.7h12.6v11.4z" />
          <path d="M11.1 7.1h1.7v5h-1.7zM15.7 7.1h1.7v5h-1.7z" />
        </svg>
      </div>
      <p class="twitch-callback-card__eyebrow">Twitch</p>
      <h1>{{ hasError ? 'Login fehlgeschlagen' : 'Login wird bestätigt' }}</h1>
      <p>{{ hasError ? errorMessage : statusMessage }}</p>
      <RouterLink v-if="hasError" class="twitch-callback-card__link" to="/login">
        Zur Login-Maske
      </RouterLink>
    </section>
  </main>
</template>

<style scoped>
.twitch-callback-page {
  min-height: 100vh;
  display: grid;
  place-items: center;
  padding: 24px;
  background:
    radial-gradient(circle at 20% 20%, rgba(145, 70, 255, 0.16), transparent 30%),
    radial-gradient(circle at 80% 20%, rgba(247, 108, 173, 0.14), transparent 32%),
    linear-gradient(145deg, #fbf6ff 0%, #f4edff 58%, #fff8f1 100%);
  color: #3f3556;
  font-family: 'Outfit', sans-serif;
}

.twitch-callback-card {
  width: min(100%, 430px);
  display: grid;
  gap: 12px;
  justify-items: center;
  padding: 34px 28px;
  border: 1px solid #ede4fb;
  border-radius: 24px;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 28px 70px rgba(80, 48, 132, 0.18);
  text-align: center;
}

.twitch-callback-card__icon {
  width: 58px;
  height: 58px;
  display: grid;
  place-items: center;
  border-radius: 18px;
  background: #9146ff;
  color: #fff;
}

.twitch-callback-card__eyebrow {
  margin: 8px 0 0;
  color: #8b6cdb;
  font-size: 12px;
  font-weight: 900;
  letter-spacing: 0.18em;
  text-transform: uppercase;
}

.twitch-callback-card h1 {
  margin: 0;
  font-family: 'Cormorant Garamond', serif;
  font-size: 32px;
  line-height: 1.05;
}

.twitch-callback-card p {
  margin: 0;
  color: #6f6685;
  font-size: 15px;
  line-height: 1.55;
}

.twitch-callback-card__link {
  margin-top: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 44px;
  padding: 0 18px;
  border-radius: 999px;
  background: #6f4fd1;
  color: #fff;
  font-weight: 800;
  text-decoration: none;
}
</style>
