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

const props = defineProps<{ token: string }>()

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

const isLoading = ref(true)
const isSaving = ref(false)
const savedMessage = ref('')
const errorMsg = ref('')

// Default LLM Options
const providers = ['openai', 'anthropic', 'gemini', 'deepseek']

const form = ref({
  product_name: '',
  industry: '',
  target_audience: '',
  core_features: '',
  user_intent: '',
  relevance_keywords: '',
  default_llm_provider: '',
  default_llm_model: ''
})

const fetchProfile = async () => {
  try {
    const res = await fetch(`${API_BASE}/users/me/product_profiles`, {
      headers: { 'Authorization': `Bearer ${props.token}` }
    })
    const data = await res.json()
    if (res.ok && data.code === 200 && data.data) {
      const p = data.data
      form.value = {
        product_name: p.product_name || '',
        industry: p.industry || '',
        target_audience: p.target_audience || '',
        core_features: p.core_features || '',
        user_intent: p.user_intent || '',
        relevance_keywords: p.relevance_keywords || '',
        default_llm_provider: p.default_llm_provider || '',
        default_llm_model: p.default_llm_model || ''
      }
      
      chrome.storage.local.set({ relevance_keywords: form.value.relevance_keywords })
    }
  } catch (err: any) {
    console.error('Failed to load profile:', err)
  } finally {
    isLoading.value = false
  }
}

const saveProfile = async () => {
  isSaving.value = true
  savedMessage.value = ''
  errorMsg.value = ''

  try {
    const res = await fetch(`${API_BASE}/users/me/product_profiles`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${props.token}`
      },
      body: JSON.stringify(form.value)
    })
    
    const data = await res.json()
    
    if (!res.ok || data.code !== 200) {
      throw new Error(data.message || 'Failed to save profile')
    }
    
    chrome.storage.local.set({ relevance_keywords: form.value.relevance_keywords })
    
    savedMessage.value = 'Profile successfully synchronized.'
    setTimeout(() => { savedMessage.value = '' }, 4000)
    
  } catch (err: any) {
    errorMsg.value = err.message
  } finally {
    isSaving.value = false
  }
}

onMounted(() => {
  if (props.token) {
    fetchProfile()
  }
})
</script>

<template>
  <div v-if="isLoading" class="py-20 flex justify-center">
    <div class="w-8 h-8 border-2 border-white/10 border-t-rose-500 rounded-full animate-spin"></div>
  </div>

  <div v-else class="space-y-12 animate-in fade-in duration-700">
    <header class="space-y-1">
      <h2 class="text-2xl font-bold tracking-tight">Product DNA</h2>
      <p class="text-sm text-zinc-500 font-medium">Shape your AI's core knowledge about what you're building.</p>
    </header>

    <form @submit.prevent="saveProfile" class="space-y-10">
      
      <!-- Notifications -->
      <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">⚠️</span>
          {{ errorMsg }}
        </div>
      </transition>
      
      <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="savedMessage" class="p-4 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-bold rounded-2xl flex items-center gap-3">
          <span class="text-base">✨</span>
          {{ savedMessage }}
        </div>
      </transition>

      <!-- Basic Info Section -->
      <section class="space-y-6">
        <div class="grid grid-cols-2 gap-8">
          <div class="space-y-3">
            <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Product Name</label>
            <input v-model="form.product_name" required class="dashboard-input" placeholder="e.g. InsightReply" />
          </div>

          <div class="space-y-3">
            <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Industry / Domain</label>
            <input v-model="form.industry" class="dashboard-input" placeholder="e.g. AI-Powered Marketing" />
          </div>
        </div>

        <div class="space-y-3">
          <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Target Persona</label>
          <input v-model="form.target_audience" class="dashboard-input" placeholder="e.g. Founders & Indie Hackers on X" />
        </div>
      </section>

      <!-- Knowledge Base Section -->
      <section class="space-y-8 pt-4">
        <div class="space-y-3">
          <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1 flex items-center gap-2">
            Value Propositions
            <span class="text-[9px] text-zinc-700 font-black lowercase tracking-normal bg-zinc-900 px-2 py-0.5 rounded border border-white/5 italic">essential knowledge</span>
          </label>
          <textarea v-model="form.core_features" rows="4" class="dashboard-input resize-none py-4" placeholder="Distill 3-5 unique features that set your product apart."></textarea>
        </div>

        <div class="space-y-3">
          <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">The "Hook" / Conversation Intent</label>
          <textarea v-model="form.user_intent" rows="3" class="dashboard-input resize-none py-4" placeholder="How do you want to position yourself in replies? Helpful advisor, sharp critic, etc."></textarea>
        </div>

        <div class="space-y-3">
          <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Radar Keywords <span class="text-zinc-700">(comma-separated)</span></label>
          <input v-model="form.relevance_keywords" class="dashboard-input" placeholder="e.g. marketing, automation, twitter growth, productivity" />
        </div>
      </section>

      <!-- System Logic Section -->
      <section class="pt-8 border-t border-white/5 space-y-6">
        <header class="space-y-1">
          <h3 class="text-sm font-bold text-zinc-400">Advanced: Neutral Intelligence</h3>
          <p class="text-[11px] text-zinc-600 font-medium">Override the primary engine models if you have specific performance needs.</p>
        </header>

        <div class="grid grid-cols-2 gap-8">
          <div class="space-y-3">
            <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">LLM Provider</label>
            <div class="relative">
              <select v-model="form.default_llm_provider" class="dashboard-input appearance-none cursor-pointer">
                <option value="">Global Default (Automated)</option>
                <option v-for="p in providers" :key="p" :value="p">{{ p.charAt(0).toUpperCase() + p.slice(1) }}</option>
              </select>
              <div class="absolute right-5 top-1/2 -translate-y-1/2 pointer-events-none text-zinc-600">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
              </div>
            </div>
          </div>
          <div class="space-y-3">
            <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Engine Model Override</label>
            <input v-model="form.default_llm_model" class="dashboard-input" placeholder="e.g. gpt-4o, claude-3-5-sonnet" />
          </div>
        </div>
      </section>

      <!-- Action -->
      <footer class="pt-10 flex justify-end">
        <button 
          type="submit"
          :disabled="isSaving"
          class="px-10 py-4 bg-rose-500 hover:bg-rose-400 text-white rounded-2xl text-[15px] font-bold transition-apple shadow-xl shadow-rose-900/40 flex items-center gap-3 active:scale-95 disabled:opacity-50"
        >
          <div v-if="isSaving" class="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
          <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" class="text-rose-100"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
          {{ isSaving ? 'Committing Changes...' : 'Synchronize Product DNA' }}
        </button>
      </footer>
    </form>
  </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>
