<template>
    <div v-if="isOpen" class="fixed inset-0 flex items-center justify-center bg-black/75 z-50">
      <div class="bg-white rounded-lg shadow-lg w-96 p-6 relative">
        <!-- Header -->
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-bold text-gray-800">
            {{ product ? 'Edit Kategori' : 'Tambah Kategori Baru' }}
          </h2>
          <button @click="emit('close')" class="text-gray-400 hover:text-gray-600">✕</button>
        </div>

        <!-- Form -->
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700">Nama Kategori</label>
          <input
            v-model="form.nama"
            type="text"
            placeholder="Masukkan nama kategori"
            class="mt-1 block w-full border border-gray-300 rounded-md px-3 py-2 focus:ring focus:ring-[#c6a77d]"
          />
        </div>

        <!-- Buttons -->
        <div class="flex justify-end gap-2">
          <button
            @click="emit('close')"
            class="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300"
          >
            Batal
          </button>
          <button
            @click="saveKategori"
            :disabled="!form.nama"
            class="px-4 py-2 bg-[#c6a77d] text-white rounded hover:bg-[#b09065] disabled:opacity-50"
          >
            Simpan
          </button>
        </div>
      </div>
    </div>
  </template>

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

  const props = defineProps({
    isOpen: Boolean,
    product: Object
  })
  const emit = defineEmits(['close'])

  const form = ref({ nama: '' })

  // Sync kalau ubah kategori
  watch(() => props.product, (val) => {
    form.value.nama = val ? val.nama : ''
  }, { immediate: true })

  const saveKategori = async () => {
    try {
      if (props.product) {
        await axios.put(`/api/kategori/${props.product.id}`, form.value)
      } else {
        await axios.post('/api/kategori', form.value)
      }
      emit('close') // tutup modal
    } catch (err) {
      console.error(err)
      alert('Gagal menyimpan kategori')
    }
  }
  </script>
