<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary-50 via-white to-primary-50">
    <div class="w-full max-w-md">
      <!-- Logo -->
      <div class="text-center mb-8">
        <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-primary-500 to-primary-700 rounded-xl mb-4 animate-pulse-slow">
          <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        </div>
        <h1 class="text-3xl font-bold text-gray-900">{{ t('setup.title') }}</h1>
        <p class="text-gray-600 mt-2">{{ t('setup.subtitle') }}</p>
      </div>

      <!-- Setup Form -->
      <div class="bg-white rounded-2xl shadow-xl p-8">
        <!-- Progress Steps -->
        <div class="mb-8">
          <div class="flex items-center justify-center">
            <div class="flex items-center">
              <div class="w-8 h-8 bg-primary-600 rounded-full flex items-center justify-center text-white font-semibold">1</div>
              <div class="ml-2 text-sm font-medium text-gray-900">{{ t('setup.step1') }}</div>
            </div>
            <div class="mx-4 w-12 h-0.5 bg-gray-300"></div>
            <div class="flex items-center">
              <div class="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center text-gray-600 font-semibold">2</div>
              <div class="ml-2 text-sm font-medium text-gray-500">{{ t('setup.step2') }}</div>
            </div>
          </div>
        </div>

        <form @submit.prevent="handleSetup" class="space-y-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">{{ t('common.username') }}</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <input
                v-model="form.login"
                type="text"
                required
                minlength="3"
                class="input-field pl-10"
                :class="{ 'border-red-300 focus:ring-red-500': validation.login }"
                placeholder="Choose a username"
              />
            </div>
            <p v-if="validation.login" class="mt-1 text-xs text-red-600">{{ validation.login }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">{{ t('common.email') }}</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
                </svg>
              </div>
              <input
                v-model="form.email"
                type="email"
                required
                class="input-field pl-10"
                :class="{ 'border-red-300 focus:ring-red-500': validation.email }"
                placeholder="admin@example.com"
              />
            </div>
            <p v-if="validation.email" class="mt-1 text-xs text-red-600">{{ validation.email }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">{{ t('common.password') }}</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              </div>
              <input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                required
                minlength="6"
                class="input-field pl-10"
                :class="{ 'border-red-300 focus:ring-red-500': validation.password }"
                placeholder="Choose a strong password"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path v-if="showPassword" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path v-if="showPassword" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
              </button>
            </div>
            <p v-if="validation.password" class="mt-1 text-xs text-red-600">{{ validation.password }}</p>

            <!-- Password Strength -->
            <div v-if="form.password" class="mt-2">
              <div class="flex items-center justify-between mb-1">
                <span class="text-xs text-gray-600">{{ t('setup.passwordStrength') }}</span>
                <span class="text-xs font-medium" :class="strengthColor">{{ strengthText }}</span>
              </div>
              <div class="h-1.5 bg-gray-200 rounded-full overflow-hidden">
                <div
                  class="h-full transition-all duration-300"
                  :class="strengthBarColor"
                  :style="{ width: `${strengthPercent}%` }"
                ></div>
              </div>
            </div>
          </div>

          <button
            type="submit"
            :disabled="loading"
            class="w-full btn-primary py-3 relative overflow-hidden group"
          >
            <span v-if="!loading" class="relative z-10">{{ t('setup.createAccount') }}</span>
            <svg v-else class="animate-spin h-5 w-5 mx-auto text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <div class="absolute inset-0 bg-gradient-to-r from-primary-600 to-primary-700 transform scale-x-0 group-hover:scale-x-100 transition-transform origin-left"></div>
          </button>
        </form>

        <!-- Error Message -->
        <transition name="fade">
          <div v-if="error" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg">
            <div class="flex items-start">
              <svg class="h-5 w-5 text-red-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p class="ml-3 text-sm text-red-600">{{ error }}</p>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const router = useRouter()
const form = ref({ login: '', email: '', password: '' });
const loading = ref(false)
const error = ref('')
const showPassword = ref(false)

const validation = computed(() => {
  const errors: any = {};
  if (form.value.login && form.value.login.length < 3) {
    errors.login = 'Username must be at least 3 characters';
  }
  if (form.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email)) {
    errors.email = 'Please enter a valid email address';
  }
  if (form.value.password && form.value.password.length < 6) {
    errors.password = 'Password must be at least 6 characters';
  }
  return errors;
});

const passwordStrength = computed(() => {
  const pwd = form.value.password
  let strength = 0
  if (pwd.length >= 6) strength++
  if (pwd.length >= 8) strength++
  if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) strength++
  if (/\d/.test(pwd)) strength++
  if (/[^a-zA-Z0-9]/.test(pwd)) strength++
  return Math.min(strength, 5)
})

const strengthPercent = computed(() => (passwordStrength.value / 5) * 100)

const strengthText = computed(() => {
  const keys = ['setup.veryWeak', 'setup.weak', 'setup.fair', 'setup.good', 'setup.strong']
  const key = keys[passwordStrength.value - 1]
  return key ? t(key) : ''
})

const strengthColor = computed(() => {
  const colors = ['text-red-600', 'text-orange-600', 'text-yellow-600', 'text-green-600', 'text-green-700']
  return colors[passwordStrength.value - 1] || ''
})

const strengthBarColor = computed(() => {
  const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-green-500', 'bg-green-600']
  return colors[passwordStrength.value - 1] || ''
})

async function handleSetup() {
  if (Object.keys(validation.value).length > 0) return;

  loading.value = true;
  error.value = '';

  try {
    const res = await fetch('/api/setup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        login: form.value.login,
        email: form.value.email,
        password: form.value.password
      })
    });

    const data = await res.json();

    if (res.ok) {
      router.push('/login');
    } else {
      error.value = data.error || 'Failed to create account';
    }
  } catch (e) {
    error.value = 'Network error. Please try again.';
  } finally {
    loading.value = false;
  }
}
</script>
