<script setup lang="ts">
import { ref } from 'vue'

const emit = defineEmits(['authenticated'])

const isLogin = ref(true)
const isLoading = ref(false)
const errorMsg = ref('')

const form = ref({
  email: '',
  password: ''
})

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'

const submitAuth = async () => {
  if (!form.value.email || !form.value.password) {
    errorMsg.value = 'Security credentials required.'
    return
  }
  
  errorMsg.value = ''
  isLoading.value = true
  
  const endpoint = isLogin.value ? '/auth/login' : '/users/register'
  
  try {
    const res = await fetch(`${API_BASE}${endpoint}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: form.value.email,
        password: form.value.password
      })
    })
    
    const data = await res.json()
    
    if (!res.ok || data.code !== 200) {
      throw new Error(data.message || 'Authentication sequence failed.')
    }
    
    // Auth Success
    const token = data.data.token
    const userId = data.data.user_id || data.data.user?.id
    
    chrome.storage.local.set({ jwt_token: token, user_id: userId }, () => {
      emit('authenticated', token)
    })
    
  } catch (err: any) {
    errorMsg.value = err.message
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="space-y-8">
    <transition enter-active-class="transition duration-300 transform" enter-from-class="opacity-0 -translate-y-2" enter-to-class="opacity-100 translate-y-0">
      <div v-if="errorMsg" class="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-bold rounded-2xl flex items-center gap-3">
        <span class="text-base font-normal">⚠️</span>
        {{ errorMsg }}
      </div>
    </transition>

    <form @submit.prevent="submitAuth" class="space-y-6 text-left animate-in fade-in slide-in-from-bottom-2 duration-500">
      <div class="space-y-3">
        <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Universal Identity (Email)</label>
        <input 
          v-model="form.email"
          type="email" 
          required
          class="dashboard-input"
          placeholder="e.g. user@insight-reply.pro"
        />
      </div>

      <div class="space-y-3">
        <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Security Key (Password)</label>
        <input 
          v-model="form.password"
          type="password" 
          required
          class="dashboard-input"
          placeholder="••••••••••••"
        />
      </div>

      <button 
        type="submit"
        :disabled="isLoading"
        :class="[
          'w-full py-4 rounded-2xl text-[15px] font-bold transition-all shadow-xl flex items-center justify-center gap-3 active:scale-[0.98] disabled:opacity-50 mt-4',
          isLogin 
            ? 'bg-rose-500 hover:bg-rose-400 text-white shadow-rose-900/40' 
            : 'bg-white hover:bg-zinc-200 text-black shadow-white/5'
        ]"
      >
        <span v-if="isLoading" class="w-5 h-5 border-2 border-current/20 border-t-current rounded-full animate-spin"></span>
        <svg v-else xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" x2="3" y1="12" y2="12"/></svg>
        {{ isLoading ? 'Synchronizing...' : (isLogin ? 'Initiate Session' : 'Create Intelligence Profile') }}
      </button>
    </form>

    <div class="text-center pt-2">
      <button 
        type="button"
        @click="isLogin = !isLogin" 
        class="text-xs font-bold text-zinc-500 hover:text-rose-400 transition-apple px-4 py-2 rounded-full hover:bg-rose-500/5 active:scale-95"
      >
        {{ isLogin ? "New to InsightReply? Secure an account" : "Existive user? Authenticate here" }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.dashboard-input {
  @apply w-full bg-black/40 border border-white/5 rounded-2xl px-5 py-3.5 text-sm font-semibold;
  @apply transition-apple focus:outline-none focus:ring-4 focus:ring-rose-500/10 focus:border-rose-500/40 placeholder:text-zinc-700;
}
</style>
