<template>
  <div :class="containerClasses">
    <v-container class="fill-height" fluid>
      <v-row align="center" justify="center">
        <v-col cols="12" sm="8" md="6" lg="4">
          <v-card class="elevation-12 rounded-lg">
            <v-card-text class="text-center pa-8">
              <!-- Loading State -->
              <div v-if="verifying" class="mb-6">
                <v-progress-circular
                  color="primary"
                  size="80"
                  width="6"
                  indeterminate
                  class="mb-4"
                />
                
                <h1 class="text-h4 font-weight-bold text-primary mb-3">
                  Verifying Your Email
                </h1>
                
                <p class="text-body-1 text-medium-emphasis">
                  Please wait while we verify your email address...
                </p>
              </div>

              <!-- Error State -->
              <div v-else-if="error" class="mb-6">
                <v-icon 
                  color="error" 
                  size="80"
                  class="mb-4"
                >
                  mdi-alert-circle
                </v-icon>
                
                <h1 class="text-h4 font-weight-bold text-error mb-3">
                  Verification Failed
                </h1>
                
                <p class="text-body-1 text-medium-emphasis mb-4">
                  {{ error }}
                </p>
                
                <v-alert
                  type="error"
                  variant="tonal"
                  class="mb-4 text-start"
                  icon="mdi-information"
                >
                  <div class="text-body-2">
                    <strong>Common Issues:</strong>
                    <ul class="mt-2">
                      <li>The verification link may have expired</li>
                      <li>The link may have already been used</li>
                      <li>The link may be malformed</li>
                    </ul>
                  </div>
                </v-alert>
              </div>

              <div v-if="!verifying" class="d-flex flex-column gap-3">
                <v-btn
                  v-if="error"
                  color="primary"
                  size="large"
                  variant="elevated"
                  block
                  @click="retryVerification"
                  :loading="verifying"
                  class="text-none"
                >
                  <v-icon start>mdi-refresh</v-icon>
                  Retry Verification
                </v-btn>

                <v-btn
                  color="secondary"
                  size="large"
                  variant="outlined"
                  block
                  to="/signup"
                  class="text-none"
                >
                  <v-icon start>mdi-account-plus</v-icon>
                  Register Again
                </v-btn>

                <v-btn
                  color="outline"
                  size="small"
                  variant="text"
                  block
                  to="/"
                  class="text-none"
                >
                  <v-icon start>mdi-home</v-icon>
                  Return to Home
                </v-btn>
              </div>

              <!-- Additional help -->
              <div class="mt-6 pt-4 border-t">
                <p class="text-caption text-medium-emphasis mb-2">
                  Need help? Contact support at:
                </p>
                <v-chip
                  size="small"
                  variant="outlined"
                  prepend-icon="mdi-email"
                >
                  support@monacousa.org
                </v-chip>
              </div>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script setup lang="ts">
import { useMobileDetection } from '~/composables/useMobileDetection';

definePageMeta({
  layout: false,
  middleware: 'guest'
});

// Use unified mobile detection
const mobileDetection = useMobileDetection();

// Mobile Safari optimization classes
const containerClasses = computed(() => {
  const classes = ['verification-page'];
  if (mobileDetection.isMobile) classes.push('is-mobile');
  if (mobileDetection.isMobileSafari) classes.push('is-mobile-safari');
  if (mobileDetection.isIOS) classes.push('is-ios');
  return classes.join(' ');
});

// Reactive state
const verifying = ref(true);
const error = ref('');
const route = useRoute();
const token = computed(() => route.query.token as string || '');

// Set page title with mobile viewport optimization
useHead({
  title: 'Verifying Email - MonacoUSA Portal',
  meta: [
    {
      name: 'description',
      content: 'Verifying your email address for the MonacoUSA Portal.'
    },
    { name: 'viewport', content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' }
  ]
});

// Verify email function
const verifyEmail = async () => {
  if (!token.value) {
    error.value = 'No verification token provided. Please check your email for the correct verification link.';
    verifying.value = false;
    return;
  }

  try {
    verifying.value = true;
    error.value = '';

    // Call the API endpoint to verify the email
    const response = await $fetch(`/api/auth/verify-email?token=${token.value}`, {
      method: 'GET'
    }) as any;

    console.log('[auth/verify] Email verification successful:', response);

    // Extract email from response
    const email = response?.data?.email || '';
    const partialSuccess = response?.data?.partialSuccess || false;
    
    // Redirect to success page with email info
    let redirectUrl = `/auth/verify-success`;
    const queryParams = [];
    
    if (email) {
      queryParams.push(`email=${encodeURIComponent(email)}`);
    }
    
    if (partialSuccess) {
      queryParams.push('warning=partial');
    }
    
    if (queryParams.length > 0) {
      redirectUrl += '?' + queryParams.join('&');
    }
    
    await navigateTo(redirectUrl);

  } catch (err: any) {
    console.error('[auth/verify] Email verification failed:', err);
    
    if (err.statusCode === 410) {
      error.value = 'Verification link has expired. Please request a new verification email.';
    } else if (err.statusCode === 409) {
      error.value = 'This verification link has already been used or is invalid.';
    } else if (err.statusCode === 400) {
      error.value = 'Invalid verification token. Please request a new verification email.';
    } else if (err.statusCode === 404) {
      error.value = 'User not found. The verification token may be invalid.';
    } else {
      error.value = err.data?.message || err.message || 'Email verification failed. Please try again or contact support.';
    }
    
    verifying.value = false;
  }
};

// Retry verification
const retryVerification = () => {
  verifyEmail();
};

// Start verification on mount
onMounted(() => {
  console.log('[auth/verify] Starting email verification with token:', token.value?.substring(0, 20) + '...');
  
  // Start verification process
  verifyEmail();
});
</script>

<style scoped>
.verification-page {
  min-height: 100vh;
  min-height: calc(var(--vh, 1vh) * 100); /* Mobile Safari fallback */
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow-x: hidden; /* Prevent horizontal scroll on mobile */
}

/* Mobile Safari optimizations */
.verification-page.is-mobile-safari {
  min-height: 100vh;
  min-height: -webkit-fill-available;
}

.verification-page.performance-mode {
  will-change: auto;
  transform: translateZ(0); /* Lighter hardware acceleration */
}

.fill-height {
  min-height: 100vh;
  min-height: calc(var(--vh, 1vh) * 100); /* Mobile Safari fallback */
}

/* Mobile Safari fill-height optimization */
.is-mobile-safari .fill-height {
  min-height: -webkit-fill-available;
}

.border-t {
  border-top: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.gap-3 {
  gap: 12px;
}

/* Loading animation */
.v-progress-circular {
  animation: pulse 2s ease-in-out infinite;
}

.performance-mode .v-progress-circular {
  animation: none; /* Disable animations on performance mode */
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
  100% {
    opacity: 1;
  }
}

/* Custom scrollbar for mobile */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

::-webkit-scrollbar-thumb {
  background: rgba(163, 21, 21, 0.5);
  border-radius: 2px;
}

/* Responsive adjustments */
@media (max-width: 600px) {
  .verification-page {
    padding: 16px;
  }
  
  .v-card {
    margin: 0;
  }
  
  /* Optimize button spacing on mobile */
  .gap-3 {
    gap: 8px;
  }
}

/* Improve touch targets on mobile */
@media (hover: none) and (pointer: coarse) {
  .v-btn {
    min-height: 48px; /* Ensure touch-friendly button size */
  }
}

/* Performance mode optimizations */
.performance-mode .v-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important; /* Lighter shadow */
}

.performance-mode .v-btn {
  transition: none; /* Remove button transitions for better performance */
}

/* Error state styling */
.text-error {
  color: rgb(var(--v-theme-error));
}

/* Better list styling */
ul {
  margin: 0;
  padding-left: 20px;
}

li {
  margin: 4px 0;
}
</style>
