<template>
  <div class="flex flex-col min-h-screen">
    <!-- Header & Back Button -->
    <div class="flex items-center mb-8">
      <button @click="$emit('back')"
        class="text-blue-600 hover:text-blue-800 font-semibold inline-flex items-center mr-4">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd"
            d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
            clip-rule="evenodd" />
        </svg>
        Kembali
      </button>
      <h1 class="text-3xl md:text-4xl font-bold text-gray-800">
        Template {{ category }}
      </h1>
    </div>

    <!-- Loading & Error -->
    <div v-if="isLoading" class="text-center py-10">
      <p>Memuat template...</p>
    </div>
    <div v-else-if="error" class="text-center py-10 text-red-600">
      <p>{{ error }}</p>
    </div>

    <!-- Grid Template -->
    <div v-else-if="templates.length > 0"
      class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 items-start">

      <div v-for="tpl in templates" :key="tpl.id"
        class="bg-white border rounded-lg overflow-hidden shadow-md hover:shadow-xl transition-shadow duration-300">
        
        <!-- Image -->
        <img 
          :src="tpl.foto || '/fallback.png'" 
          :alt="tpl.nama_template" 
          class="w-full h-48 object-cover"
          @error="(e) => e.target.src = '/fallback.png'" 
        />

        <!-- Body -->
        <div class="p-5 text-center">
          <h4 class="text-xl font-bold text-gray-800 mb-2">{{ tpl.nama_template }}</h4>
          <p class="text-green-600 font-semibold text-xl mb-4">
            Rp {{ (tpl.harga ?? 0).toLocaleString('id-ID') }}
          </p>

          <!-- Dropdown Fitur -->
          <div v-if="tpl.fiturs?.length > 0" class="relative mb-4">
            <button @click="toggleDropdown(tpl.id)"
              class="w-full bg-white border border-gray-300 rounded-md shadow-sm px-4 py-2 inline-flex justify-between items-center text-center">
              <span class="mx-auto text-gray-700 font-semibold">FITUR YANG TERSEDIA</span>
              <svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
                fill="currentColor">
                <path fill-rule="evenodd"
                  d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                  clip-rule="evenodd" />
              </svg>
            </button>

            <div v-if="openDropdownId === tpl.id">
              <ul class="mt-4 space-y-2 text-gray-600 text-left">
                <li v-for="item_fitur in tpl.fiturs" :key="item_fitur.id" class="flex items-center">
                  <svg class="h-4 w-4 text-green-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  {{ item_fitur.deskripsi }}
                </li>
              </ul>
            </div>
          </div>

          <!-- Buttons -->
          <div class="mt-6 flex flex-col gap-3">
            <a :href="tpl.preview_link || '#'" target="_blank"
              class="w-full bg-white border border-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg hover:bg-gray-100 transition-colors text-center block">
              Preview
            </a>
            <NuxtLink 
              :to="`/form/${tpl.kategori?.id || tpl.id}?template_id=${tpl.id}`"
              class="w-full bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors text-center">
              Order
            </NuxtLink>
          </div>
        </div>
      </div>

    </div>

    <div v-else class="text-center py-10 text-gray-500">
      <p>Belum ada template untuk kategori ini.</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  category: { type: String, required: true },
  id_category: { type: [Number, String], required: true },
})

defineEmits(['back'])

const templates = ref([])
const isLoading = ref(true)
const error = ref(null)
const openDropdownId = ref(null)

const toggleDropdown = (templateId) => {
  openDropdownId.value = openDropdownId.value === templateId ? null : templateId
}

const fetchTemplates = async (categoryId) => {
  isLoading.value = true
  error.value = null
  try {
    const res = await $fetch(`/api/templates/category/${categoryId}`, {
      baseURL: 'http://localhost:8000'
    })
    templates.value = res.map(tpl => ({
      id: tpl.id,
      nama_template: tpl.nama_template,
      harga: tpl.harga,
      kategori: tpl.kategori,
      foto: tpl.foto ?? null,
      fiturs: tpl.fiturs ?? [],
      preview_link: tpl.preview_link ?? null
    }))
  } catch (err) {
    console.error(err)
    error.value = 'Gagal memuat template.'
    templates.value = []
  } finally {
    isLoading.value = false
  }
}

// Fetch saat mount
onMounted(() => fetchTemplates(props.id_category))

// Watch id_category untuk fetch ulang saat berubah
watch(() => props.id_category, (newId) => {
  if (newId) fetchTemplates(newId)
})
</script>
