<template>
  <div class="oauth-callback">
    <div class="container">
      <div class="callback-card">
        <div v-if="loading" class="loading-state">
          <div class="spinner"></div>
          <h2>Authenticating...</h2>
          <p>Please wait while we complete your {{ provider }} OAuth login</p>
        </div>

        <div v-else-if="error" class="error-state">
          <div class="error-icon">✕</div>
          <h2>Authentication Failed</h2>
          <p class="error-message">{{ error }}</p>
          <router-link to="/auth" class="btn btn-primary">
            Back to Authentication Settings
          </router-link>
        </div>

        <div v-else-if="success" class="success-state">
          <div class="success-icon">✓</div>
          <h2>{{ provider }} Authentication Successful!</h2>
          <p>You're now authenticated with {{ provider }}</p>
          <p class="redirect-info">Redirecting in {{ countdown }} seconds...</p>
          <router-link :to="returnTo || '/auth'" class="btn btn-primary">
            Continue to Authentication Settings
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useOAuth } from '../composables/useOAuth.js';

const route = useRoute();
const router = useRouter();

const loading = ref(true);
const error = ref(null);
const success = ref(false);
const countdown = ref(3);
const provider = ref('challonge');
const returnTo = ref(null);

onMounted(async () => {
  // Get provider from query or sessionStorage (default: 'challonge' for backwards compatibility)
  provider.value =
    route.query.provider ||
    sessionStorage.getItem('oauth_provider') ||
    'challonge';

  // Get redirect destination (default: /auth)
  returnTo.value =
    route.query.return_to ||
    sessionStorage.getItem('oauth_return_to') ||
    '/auth';

  // Get OAuth parameters from URL
  const code = route.query.code;
  const state = route.query.state;
  const errorParam = route.query.error;
  const errorDescription = route.query.error_description;

  // Handle OAuth errors from provider
  if (errorParam) {
    loading.value = false;
    error.value = errorDescription || `OAuth error: ${errorParam}`;
    console.warn(`OAuth error from ${provider.value}:`, errorParam);
    return;
  }

  // Validate required parameters
  if (!code || !state) {
    loading.value = false;
    error.value = 'Missing authorization code or state parameter';
    return;
  }

  try {
    // Exchange code for tokens using unified OAuth handler
    const oauth = useOAuth(provider.value);
    await oauth.exchangeCode(code, state);

    loading.value = false;
    success.value = true;

    // Start countdown redirect
    const interval = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(interval);
        router.push(returnTo.value);
      }
    }, 1000);
  } catch (err) {
    loading.value = false;
    error.value = err.message || 'Failed to complete OAuth authentication';
    console.error('OAuth callback error:', err);
  }
});
</script>

<style scoped>
.oauth-callback {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 2rem;
}

.container {
  max-width: 400px;
  width: 100%;
}

.callback-card {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.loading-state,
.error-state,
.success-state {
  text-align: center;
}

.spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #667eea;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-icon {
  font-size: 3rem;
  color: #dc3545;
  margin-bottom: 1rem;
}

.success-icon {
  font-size: 3rem;
  color: #28a745;
  margin-bottom: 1rem;
}

h2 {
  margin: 1rem 0;
  font-size: 1.5rem;
  color: #333;
}

p {
  color: #666;
  margin: 0.5rem 0;
}

.error-message {
  background: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 4px;
  padding: 1rem;
  margin: 1rem 0;
  color: #856404;
}

.redirect-info {
  font-size: 0.9rem;
  font-weight: 500;
  color: #666;
}

.btn {
  display: inline-block;
  margin-top: 1.5rem;
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.2s;
  border: none;
  cursor: pointer;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5568d3;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
</style>
