<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 strategies = ref<Array<any>>([])
const isLoading = ref(true)
const isSubmitting = ref(false)
const errorMsg = ref('')

const showForm = ref(false)
const form = ref({
  strategy_key: '',
  label: '',
  description: ''
})

const fetchStrategies = async () => {
  isLoading.value = true
  try {
    const res = await fetch(`${API_BASE}/users/me/strategies`, {
      headers: { 'Authorization': `Bearer ${props.token}` }
    })
    const data = await res.json()
    if (res.ok && data.code === 200) {
      strategies.value = data.data || []
    }
  } catch (err) {
    console.error(err)
  } finally {
    isLoading.value = false
  }
}

const createStrategy = async () => {
  isSubmitting.value = true
  errorMsg.value = ''
  try {
    const res = await fetch(`${API_BASE}/users/me/strategies`, {
      method: 'POST',
      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 create strategy')
    }
    
    form.value = { strategy_key: '', label: '', description: '' }
    showForm.value = false
    await fetchStrategies()
    
  } catch (err: any) {
    errorMsg.value = err.message
  } finally {
    isSubmitting.value = false
  }
}

const deleteStrategy = async (id: number) => {
  if (!confirm('Are you sure you want to delete this custom strategy?')) return
  
  try {
    const res = await fetch(`${API_BASE}/users/me/strategies/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${props.token}` }
    })
    if (res.ok) {
      strategies.value = strategies.value.filter(s => s.id !== id)
    }
  } catch (err) {
    console.error(err)
  }
}

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

<template>
  <div class="space-y-12">
    
    <header class="flex justify-between items-end">
      <div class="space-y-1">
        <h2 class="text-2xl font-bold tracking-tight">AI Content Strategies</h2>
        <p class="text-sm text-zinc-500 font-medium">Fine-tune how your AI assistant approaches engagement for different personas.</p>
      </div>
      <button 
        v-if="!showForm"
        @click="showForm = true"
        class="px-5 py-2.5 bg-rose-500 hover:bg-rose-400 text-white rounded-[14px] text-sm font-bold transition-apple shadow-lg shadow-rose-900/20 active:scale-95 flex items-center gap-2"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
        New Strategy
      </button>
    </header>

    <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-8">
      <!-- Create Form Modal View -->
      <transition enter-active-class="transition duration-500 ease-out transform" enter-from-class="opacity-0 scale-95 -translate-y-4" enter-to-class="opacity-100 scale-100 translate-y-0">
        <form v-if="showForm" @submit.prevent="createStrategy" class="bg-white/[0.03] border border-white/5 rounded-[32px] p-8 space-y-8 shadow-2xl relative">
          <div class="flex justify-between items-center">
            <h3 class="text-lg font-bold">New Prompt Angle</h3>
            <button type="button" @click="showForm = false" class="p-2 rounded-full hover:bg-white/5 transition-apple">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
          </div>

          <div v-if="errorMsg" class="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs font-bold rounded-xl animate-pulse">
            {{ errorMsg }}
          </div>

          <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">Internal Reference ID</label>
              <input v-model="form.strategy_key" required class="dashboard-input" placeholder="e.g. vc_advisor" />
            </div>
            <div class="space-y-3">
              <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Display Label</label>
              <input v-model="form.label" required class="dashboard-input" placeholder="e.g. VC Advisor" />
            </div>
          </div>

          <div class="space-y-3">
            <label class="text-[10px] font-bold text-zinc-500 uppercase tracking-[0.2em] ml-1">Prompt Instructions & constraints</label>
            <textarea v-model="form.description" required rows="4" class="dashboard-input resize-none py-4" placeholder="Be authoritative yet encouraging. Focus on market metrics. Avoid safe 'that's great' comments."></textarea>
          </div>

          <div class="flex justify-end">
            <button type="submit" :disabled="isSubmitting" class="px-8 py-3.5 bg-rose-500 hover:bg-rose-400 text-white rounded-2xl text-[15px] font-bold transition-apple shadow-xl shadow-rose-900/30 flex items-center gap-3 active:scale-95 disabled:opacity-50">
               <div v-if="isSubmitting" class="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin"></div>
               {{ isSubmitting ? 'Architecting...' : 'Save Strategy' }}
            </button>
          </div>
        </form>
      </transition>

      <!-- Strategy List -->
      <div v-if="strategies.length === 0 && !showForm" class="text-center py-20 bg-white/[0.01] border-2 border-dashed border-white/5 rounded-[40px] space-y-4">
        <div class="w-16 h-16 bg-white/[0.03] rounded-3xl mx-auto flex items-center justify-center border border-white/5">
           <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="text-zinc-700"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
        </div>
        <p class="text-zinc-500 font-bold tracking-tight">No custom strategies deployed yet.</p>
      </div>

      <div class="grid grid-cols-1 gap-4">
        <div v-for="s in strategies" :key="s.id" class="group bg-white/[0.02] border border-white/5 rounded-[28px] p-6 flex justify-between items-center transition-apple hover:bg-white/[0.04] hover:border-white/10 hover:shadow-2xl">
          <div class="flex items-center gap-6">
            <div class="w-14 h-14 bg-rose-500/5 border border-rose-500/10 rounded-2xl flex items-center justify-center text-rose-500 group-hover:scale-110 transition-apple">
               <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
            </div>
            <div class="space-y-1.5">
              <div class="flex items-center gap-3">
                <span class="text-[17px] font-black tracking-tight group-hover:text-rose-400 transition-apple">{{ s.label }}</span>
                <span class="text-[9px] font-black font-mono text-zinc-500 bg-black/40 px-2 py-0.5 rounded-md border border-white/5 uppercase tracking-tighter">{{ s.strategy_key }}</span>
              </div>
              <p class="text-[13px] text-zinc-500 leading-relaxed font-medium max-w-xl group-hover:text-zinc-400 transition-apple">{{ s.description }}</p>
            </div>
          </div>
          <button @click="deleteStrategy(s.id)" class="p-4 rounded-2xl text-zinc-700 hover:text-rose-500 hover:bg-rose-500/10 transition-apple opacity-0 group-hover:opacity-100 active:scale-95">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
          </button>
        </div>
      </div>
      
    </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>
