<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 = 'Email and password are 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 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-4">
    <div v-if="errorMsg" class="p-3 bg-red-500/10 border border-red-500/20 text-red-400 text-sm rounded-lg">
      {{ errorMsg }}
    </div>

    <form @submit.prevent="submitAuth" class="space-y-4 text-left">
      <div class="space-y-1.5">
        <label class="text-xs font-medium text-zinc-300">Email Address</label>
        <input 
          v-model="form.email"
          type="email" 
          required
          class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
          placeholder="your@email.com"
        />
      </div>

      <div class="space-y-1.5">
        <label class="text-xs font-medium text-zinc-300">Password</label>
        <input 
          v-model="form.password"
          type="password" 
          required
          class="w-full bg-[#0A0A0A] border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-primary/50 transition-colors"
          placeholder="••••••••"
        />
      </div>

      <button 
        type="submit"
        :disabled="isLoading"
        class="w-full py-2.5 bg-brand-primary hover:bg-brand-primary/90 text-white rounded-lg text-sm font-medium transition-all shadow-lg flex items-center justify-center gap-2 mt-2 disabled:opacity-70 disabled:cursor-not-allowed"
      >
        <span v-if="isLoading" class="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></span>
        {{ isLoading ? 'Processing...' : (isLogin ? 'Sign In' : 'Create Account') }}
      </button>
    </form>

    <div class="text-center mt-4 border-t border-white/10 pt-4">
      <button 
        type="button"
        @click="isLogin = !isLogin" 
        class="text-xs text-zinc-400 hover:text-white transition-colors"
      >
        {{ isLogin ? "Don't have an account? Sign up" : "Already have an account? Log in" }}
      </button>
    </div>
  </div>
</template>
