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

const emit = defineEmits<{
  unlocked: []
}>()

const authStore = useAuthStore()
const lockMethod = ref<'biometric' | 'pin' | null>(null)
const pin = ref('')
const error = ref('')
const loading = ref(false)
const pinDigits = ref<string[]>(['', '', '', '', '', ''])
const currentDigit = ref(0)

onMounted(() => {
  // Get user's preferred lock method
  lockMethod.value = localStorage.getItem('lockMethod') as 'biometric' | 'pin' | null
  
  // If biometric is set, try it automatically
  if (lockMethod.value === 'biometric') {
    tryBiometric()
  }
})

async function tryBiometric() {
  loading.value = true
  error.value = ''
  
  try {
    // Check if WebAuthn is available
    if (!window.PublicKeyCredential) {
      throw new Error('Biometrie nicht verfügbar')
    }

    // Get stored credential ID
    const credentialId = localStorage.getItem('biometricCredentialId')
    if (!credentialId) {
      throw new Error('Keine biometrischen Daten gespeichert')
    }

    // Request biometric authentication
    const credential = await navigator.credentials.get({
      publicKey: {
        challenge: new Uint8Array(32),
        timeout: 60000,
        userVerification: 'required',
        allowCredentials: [{
          id: Uint8Array.from(atob(credentialId), c => c.charCodeAt(0)),
          type: 'public-key',
          transports: ['internal']
        }]
      }
    })

    if (credential) {
      emit('unlocked')
    }
  } catch (e: any) {
    console.error('Biometric auth failed:', e)
    error.value = 'Biometrie fehlgeschlagen. Bitte PIN verwenden.'
    lockMethod.value = 'pin'
  }
  
  loading.value = false
}

function addDigit(digit: string) {
  if (currentDigit.value < 6) {
    pinDigits.value[currentDigit.value] = digit
    currentDigit.value++
    
    if (currentDigit.value === 6) {
      verifyPin()
    }
  }
}

function removeDigit() {
  if (currentDigit.value > 0) {
    currentDigit.value--
    pinDigits.value[currentDigit.value] = ''
  }
  error.value = ''
}

function clearPin() {
  pinDigits.value = ['', '', '', '', '', '']
  currentDigit.value = 0
  error.value = ''
}

async function verifyPin() {
  const enteredPin = pinDigits.value.join('')
  const storedPin = localStorage.getItem('appPin')
  
  if (enteredPin === storedPin) {
    emit('unlocked')
  } else {
    error.value = 'Falscher PIN'
    // Shake animation + clear after delay
    setTimeout(clearPin, 500)
  }
}

function switchToPin() {
  lockMethod.value = 'pin'
  error.value = ''
}
</script>

<template>
  <div class="fixed inset-0 bg-gradient-to-br from-purple-600 to-indigo-700 flex flex-col items-center justify-center z-50">
    <!-- Logo -->
    <div class="text-6xl mb-4">🔐</div>
    <h1 class="text-2xl font-bold text-white mb-2">SeCu</h1>
    <p class="text-white/70 mb-8">Bitte entsperren</p>

    <!-- Biometric -->
    <div v-if="lockMethod === 'biometric' && !error" class="text-center">
      <button 
        @click="tryBiometric"
        :disabled="loading"
        class="w-20 h-20 bg-white/20 rounded-full flex items-center justify-center text-4xl mb-4 hover:bg-white/30 transition"
      >
        <span v-if="loading" class="animate-spin">⏳</span>
        <span v-else>👆</span>
      </button>
      <p class="text-white/70 text-sm">Fingerabdruck oder Face ID</p>
      <button 
        @click="switchToPin"
        class="mt-4 text-white/50 text-sm underline"
      >
        Stattdessen PIN verwenden
      </button>
    </div>

    <!-- PIN Entry -->
    <div v-else class="text-center">
      <!-- PIN Dots -->
      <div class="flex space-x-3 mb-8">
        <div 
          v-for="(digit, i) in pinDigits" 
          :key="i"
          :class="[
            'w-4 h-4 rounded-full transition-all',
            digit ? 'bg-white scale-110' : 'bg-white/30',
            error ? 'animate-shake bg-red-400' : ''
          ]"
        ></div>
      </div>

      <!-- Error -->
      <p v-if="error" class="text-red-300 text-sm mb-4">{{ error }}</p>

      <!-- Number Pad -->
      <div class="grid grid-cols-3 gap-4 max-w-xs">
        <button 
          v-for="n in [1,2,3,4,5,6,7,8,9]" 
          :key="n"
          @click="addDigit(String(n))"
          class="w-16 h-16 bg-white/20 rounded-full text-white text-2xl font-semibold hover:bg-white/30 transition"
        >
          {{ n }}
        </button>
        <button 
          v-if="lockMethod === 'biometric' || localStorage.getItem('biometricCredentialId')"
          @click="tryBiometric"
          class="w-16 h-16 bg-white/20 rounded-full text-white text-2xl hover:bg-white/30 transition"
        >
          👆
        </button>
        <div v-else class="w-16 h-16"></div>
        <button 
          @click="addDigit('0')"
          class="w-16 h-16 bg-white/20 rounded-full text-white text-2xl font-semibold hover:bg-white/30 transition"
        >
          0
        </button>
        <button 
          @click="removeDigit"
          class="w-16 h-16 bg-white/10 rounded-full text-white text-xl hover:bg-white/20 transition"
        >
          ⌫
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}
.animate-shake {
  animation: shake 0.3s ease-in-out;
}
</style>
