<template>
  <div class="p-8">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-3xl font-bold">My Products</h1>
      <button @click="openAddModal" class="bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-3 rounded-lg hover:shadow-lg">
        ➕ Create New Product
      </button>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
      <div class="bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-lg shadow-lg p-4">
        <div class="text-2xl mb-1">📦</div>
        <div class="text-xl font-bold">{{ products.length }}</div>
        <div class="text-xs text-blue-100">Total Products</div>
      </div>
      <div class="bg-gradient-to-br from-green-500 to-green-600 text-white rounded-lg shadow-lg p-4">
        <div class="text-2xl mb-1">✅</div>
        <div class="text-xl font-bold">{{ products.filter(p => p.is_available).length }}</div>
        <div class="text-xs text-green-100">Available</div>
      </div>
      <div class="bg-gradient-to-br from-red-500 to-red-600 text-white rounded-lg shadow-lg p-4">
        <div class="text-2xl mb-1">❌</div>
        <div class="text-xl font-bold">{{ products.filter(p => !p.is_available).length }}</div>
        <div class="text-xs text-red-100">Unavailable</div>
      </div>
      <div @click="showUnavailableVariations" class="bg-gradient-to-br from-orange-500 to-orange-600 text-white rounded-lg shadow-lg p-4 cursor-pointer hover:shadow-xl transition">
        <div class="text-2xl mb-1">🔴</div>
        <div class="text-xl font-bold">{{ unavailableVariationsCount }}</div>
        <div class="text-xs text-orange-100">Unavailable Variations</div>
      </div>
      <div @click="showDeletedProducts" class="bg-gradient-to-br from-gray-500 to-gray-600 text-white rounded-lg shadow-lg p-4 cursor-pointer hover:shadow-xl transition">
        <div class="text-2xl mb-1">🗑️</div>
        <div class="text-xl font-bold">{{ deletedProductsCount }}</div>
        <div class="text-xs text-gray-100">Deleted Products</div>
      </div>
      <div class="bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-lg shadow-lg p-4">
        <div class="text-2xl mb-1">📊</div>
        <div class="text-xl font-bold">{{ categories.length }}</div>
        <div class="text-xs text-purple-100">Categories</div>
      </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <input v-model="filters.search" @input="fetchProducts" placeholder="🔍 Search products..." class="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
        <select v-model="filters.category_id" @change="fetchProducts" class="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
          <option value="">All Categories</option>
          <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
        </select>
        <select v-model="filters.status" @change="fetchProducts" class="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
          <option value="">All Status</option>
          <option value="1">Available</option>
          <option value="0">Unavailable</option>
        </select>
      </div>
    </div>

    <!-- Products Table -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gradient-to-r from-orange-500 to-orange-600 text-white">
            <tr>
              <th class="px-4 py-3 text-left text-sm font-semibold">Image</th>
              <th class="px-4 py-3 text-left text-sm font-semibold">Product Name</th>
              <th class="px-4 py-3 text-left text-sm font-semibold">Category</th>
              <th class="px-4 py-3 text-left text-sm font-semibold">Price / Variations</th>
              <th class="px-4 py-3 text-left text-sm font-semibold">Status</th>
              <th class="px-4 py-3 text-center text-sm font-semibold">Actions</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            <tr v-for="product in paginatedProducts" :key="product.id" class="hover:bg-gray-50 transition">
              <td class="px-4 py-3">
                <img v-if="product.image || product.pivot?.custom_image" 
                  :src="product.pivot?.custom_image || product.image" 
                  loading="lazy"
                  class="w-12 h-12 object-cover rounded-lg bg-gray-100">
                <div v-else class="w-12 h-12 bg-gray-200 rounded-lg flex items-center justify-center text-xl">🍔</div>
              </td>
              <td class="px-4 py-3">
                <div class="font-semibold text-gray-800">{{ product.name }}</div>
                <div class="text-xs text-gray-500 line-clamp-1">{{ product.description }}</div>
                <div class="flex gap-1 mt-1">
                  <span v-if="product.pivot?.is_featured" class="text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded">⭐</span>
                  <span v-if="product.pivot?.is_spicy" class="text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded">🌶️</span>
                  <span v-if="product.pivot?.is_vegetarian" class="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded">🥬</span>
                </div>
              </td>
              <td class="px-4 py-3">
                <span class="text-sm text-gray-600">{{ product.category?.name || 'N/A' }}</span>
              </td>
              <td class="px-4 py-3">
                <div v-if="product.variations?.length" class="flex flex-wrap gap-2">
                  <span v-for="v in product.variations" :key="v.id" class="text-xs bg-gray-100 px-2 py-1 rounded">
                    <span class="text-gray-700 font-medium">{{ v.name }}</span>
                    <span v-if="v.discount && v.discount > 0" class="ml-1">
                      <span class="text-gray-400 line-through text-xs">Rs {{ v.price }}</span>
                      <span class="text-green-600 font-semibold ml-1">Rs {{ v.discount }}</span>
                    </span>
                    <span v-else class="text-green-600 font-semibold ml-1">Rs {{ v.price }}</span>
                  </span>
                </div>
                <div v-else>
                  <div v-if="product.pivot?.offer_price">
                    <div class="text-gray-400 line-through text-sm">Rs {{ product.pivot?.price || product.price }}</div>
                    <div class="font-bold text-green-600">Rs {{ product.pivot.offer_price }}</div>
                  </div>
                  <div v-else>
                    <div class="font-bold text-green-600">Rs {{ product.pivot?.price || product.price }}</div>
                  </div>
                </div>
              </td>
              <td class="px-4 py-3">
                <button @click="toggleAvailability(product)" 
                  :class="(product.pivot?.is_available ?? product.is_available) ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
                  class="px-3 py-1 rounded-full text-xs font-medium hover:shadow transition">
                  {{ (product.pivot?.is_available ?? product.is_available) ? '✓' : '✗' }}
                </button>
              </td>
              <td class="px-4 py-3">
                <div class="flex items-center justify-center gap-2">
                  <button @click="viewProduct(product)" class="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition" title="View">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                    </svg>
                  </button>
                  <button @click="editProduct(product)" class="p-2 text-orange-600 hover:bg-orange-50 rounded-lg transition" title="Edit">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                    </svg>
                  </button>
                  <button @click="deleteProduct(product.id)" class="p-2 text-red-600 hover:bg-red-50 rounded-lg transition" title="Delete">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-if="products.length === 0" class="text-center py-12">
        <div class="text-6xl mb-4">📦</div>
        <h3 class="text-xl font-bold text-gray-800 mb-2">No Products Found</h3>
        <p class="text-gray-600 mb-6">Add products to your menu to get started</p>
      </div>
      
      <!-- Pagination -->
      <div v-if="products.length > 0" class="px-6 py-4 border-t flex items-center justify-between">
        <div class="text-sm text-gray-600">
          Showing {{ (currentPage - 1) * perPage + 1 }} to {{ Math.min(currentPage * perPage, products.length) }} of {{ products.length }} products
        </div>
        <div class="flex gap-2">
          <button @click="currentPage--" :disabled="currentPage === 1" 
            class="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50">
            Previous
          </button>
          <button v-for="page in totalPages" :key="page" @click="currentPage = page"
            :class="currentPage === page ? 'bg-orange-500 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'"
            class="px-4 py-2 border rounded-lg">
            {{ page }}
          </button>
          <button @click="currentPage++" :disabled="currentPage === totalPages" 
            class="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50">
            Next
          </button>
        </div>
      </div>
    </div>

    <!-- View Product Modal -->
    <div v-if="showViewModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl">
        <div class="sticky top-0 bg-gradient-to-r from-orange-500 to-orange-600 text-white px-6 py-4 flex justify-between items-center rounded-t-xl">
          <h2 class="text-2xl font-bold">📦 Product Details</h2>
          <button @click="showViewModal = false" class="text-white hover:bg-white hover:bg-opacity-20 rounded-full p-2 transition">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>
        
        <div v-if="viewingProduct" class="p-6">
          <!-- Product Header with Image on Side -->
          <div class="flex gap-6 mb-6">
            <!-- Product Image -->
            <div v-if="viewingProduct.image || viewingProduct.pivot?.custom_image" class="flex-shrink-0">
              <img :src="viewingProduct.pivot?.custom_image || viewingProduct.image" class="w-48 h-48 object-cover rounded-xl shadow-lg">
            </div>
            
            <!-- Product Info -->
            <div class="flex-1">
              <h3 class="text-3xl font-bold text-gray-800 mb-2">{{ viewingProduct.name }}</h3>
              <span class="inline-block bg-orange-100 text-orange-700 px-4 py-1 rounded-full text-sm font-medium mb-4">
                {{ viewingProduct.category?.name || 'Uncategorized' }}
              </span>
              
              <!-- Badges -->
              <div class="flex flex-wrap gap-2 mb-4">
                <span v-if="viewingProduct.pivot?.is_featured || viewingProduct.is_featured" class="bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full text-sm font-semibold">
                  ⭐ Featured
                </span>
                <span v-if="viewingProduct.pivot?.is_spicy || viewingProduct.is_spicy" class="bg-red-100 text-red-700 px-3 py-1 rounded-full text-sm font-semibold">
                  🌶️ Spicy
                </span>
                <span v-if="viewingProduct.pivot?.is_vegetarian || viewingProduct.is_vegetarian" class="bg-green-100 text-green-700 px-3 py-1 rounded-full text-sm font-semibold">
                  🥬 Vegetarian
                </span>
                <span :class="(viewingProduct.pivot?.is_available ?? viewingProduct.is_available) ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'" class="px-3 py-1 rounded-full text-sm font-semibold">
                  {{ (viewingProduct.pivot?.is_available ?? viewingProduct.is_available) ? '✅ Available' : '❌ Unavailable' }}
                </span>
              </div>
              
              <!-- Description -->
              <div v-if="viewingProduct.description" class="bg-gray-50 rounded-lg p-3 text-sm text-gray-600">
                {{ viewingProduct.description }}
              </div>
            </div>
          </div>

          <!-- Pricing Info -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
              <div class="text-sm text-green-600 font-medium mb-1">💰 Regular Price</div>
              <div class="text-2xl font-bold text-green-700">Rs {{ viewingProduct.pivot?.price || viewingProduct.price }}</div>
            </div>
            <div v-if="viewingProduct.pivot?.offer_price" class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-4 border border-orange-200">
              <div class="text-sm text-orange-600 font-medium mb-1">🎉 Offer Price</div>
              <div class="text-2xl font-bold text-orange-700">Rs {{ viewingProduct.pivot.offer_price }}</div>
            </div>
            <div v-if="viewingProduct.pivot?.discount_percentage" class="bg-gradient-to-br from-red-50 to-red-100 rounded-lg p-4 border border-red-200">
              <div class="text-sm text-red-600 font-medium mb-1">🏷️ Discount</div>
              <div class="text-2xl font-bold text-red-700">{{ viewingProduct.pivot.discount_percentage }}% OFF</div>
            </div>
          </div>

          <!-- Product Details Grid -->
          <div class="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-blue-50 rounded-lg p-4 border border-blue-200">
              <div class="text-xs text-blue-600 font-medium mb-1">📦 Stock</div>
              <div class="text-lg font-bold text-blue-700">{{ viewingProduct.pivot?.stock_quantity || viewingProduct.stock_quantity }}</div>
            </div>
            <div class="bg-purple-50 rounded-lg p-4 border border-purple-200">
              <div class="text-xs text-purple-600 font-medium mb-1">⏱️ Prep Time</div>
              <div class="text-lg font-bold text-purple-700">{{ viewingProduct.pivot?.preparation_time || viewingProduct.preparation_time }} min</div>
            </div>
            <div v-if="viewingProduct.pivot?.min_order_quantity || viewingProduct.min_order_quantity" class="bg-indigo-50 rounded-lg p-4 border border-indigo-200">
              <div class="text-xs text-indigo-600 font-medium mb-1">🔢 Min Order</div>
              <div class="text-lg font-bold text-indigo-700">{{ viewingProduct.pivot?.min_order_quantity || viewingProduct.min_order_quantity }}</div>
            </div>
          </div>

          <!-- Availability Times -->
          <div v-if="viewingProduct.pivot?.available_from || viewingProduct.pivot?.available_until || viewingProduct.available_from || viewingProduct.available_until" class="bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-200 rounded-lg p-4 mb-6">
            <h4 class="font-semibold text-blue-800 mb-3 flex items-center gap-2">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              ⏰ Availability Times
            </h4>
            <div class="flex items-center gap-4 text-blue-700">
              <span v-if="viewingProduct.pivot?.available_from || viewingProduct.available_from" class="font-medium">
                From: {{ viewingProduct.pivot?.available_from || viewingProduct.available_from }}
              </span>
              <span v-if="viewingProduct.pivot?.available_until || viewingProduct.available_until" class="font-medium">
                Until: {{ viewingProduct.pivot?.available_until || viewingProduct.available_until }}
              </span>
            </div>
          </div>

          <!-- Special Notes -->
          <div v-if="viewingProduct.pivot?.special_notes || viewingProduct.special_notes" class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
            <h4 class="font-semibold text-yellow-800 mb-2 flex items-center gap-2">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/>
              </svg>
              📝 Special Notes
            </h4>
            <p class="text-yellow-700">{{ viewingProduct.pivot?.special_notes || viewingProduct.special_notes }}</p>
          </div>

          <!-- Variations -->
          <div v-if="viewingProduct.variations?.length" class="bg-gray-50 border border-gray-200 rounded-lg p-4 mb-6">
            <h4 class="font-semibold text-gray-800 mb-3 flex items-center gap-2">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
              </svg>
              📋 Variations
            </h4>
            <div class="grid grid-cols-2 gap-2">
              <div v-for="v in viewingProduct.variations" :key="v.id" class="bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm flex items-center justify-between">
                <div>
                  <span class="font-medium text-gray-700">{{ v.name }}</span>
                  <span class="text-green-600 font-semibold ml-2">+Rs {{ v.price }}</span>
                </div>
                <button @click="toggleVariation(v.id)" 
                  :class="v.is_available ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
                  class="px-2 py-1 rounded text-xs font-medium hover:shadow transition">
                  {{ v.is_available ? '✓' : '✗' }}
                </button>
              </div>
            </div>
          </div>
          <div v-else class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <p class="text-sm text-blue-700">📌 This product has no variations. Use the Status toggle in the products table to enable/disable availability.</p>
          </div>

          <!-- Add-ons -->
          <div v-if="viewingProduct.addons?.length" class="bg-gray-50 border border-gray-200 rounded-lg p-4">
            <h4 class="font-semibold text-gray-800 mb-3 flex items-center gap-2">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
              </svg>
              🍕 Add-ons
            </h4>
            <div class="grid grid-cols-2 gap-2">
              <div v-for="a in viewingProduct.addons" :key="a.id" class="bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm flex items-center justify-between">
                <div>
                  <span class="font-medium text-gray-700">{{ a.name }}</span>
                  <span class="text-green-600 font-semibold ml-2">Rs {{ a.price }}</span>
                </div>
                <button @click="toggleAddon(a.id)" 
                  :class="a.is_available ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
                  class="px-2 py-1 rounded text-xs font-medium hover:shadow transition">
                  {{ a.is_available ? '✓' : '✗' }}
                </button>
              </div>
            </div>
          </div>
          <div v-else-if="!viewingProduct.variations?.length" class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <p class="text-sm text-blue-700">📌 This product has no add-ons. Use the Status toggle in the products table to enable/disable availability.</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <AddProductModal
      v-if="showModal"
      :product="editingProduct"
      :isManager="true"
      @close="closeModal"
      @saved="fetchProducts"
    />

    <!-- Customize Product Modal -->
    <div v-if="showCustomizeModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl">
        <div class="sticky top-0 bg-gradient-to-r from-orange-500 to-orange-600 text-white px-6 py-4 flex justify-between items-center rounded-t-xl">
          <h2 class="text-2xl font-bold">{{ editingProduct ? '✏️ Edit Product' : '🎨 Customize Product' }}</h2>
          <button @click="showCustomizeModal = false; editingProduct = null;" class="text-white hover:bg-white hover:bg-opacity-20 rounded-full p-2 transition">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>

        <form @submit.prevent="addProductToMenu" class="p-6 space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Product Name</label>
            <input v-model="customizeForm.name" readonly class="w-full px-4 py-2 border rounded-lg bg-gray-50">
          </div>

          <div class="grid grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Your Price (Rs) *</label>
              <input v-model="customizeForm.price" type="number" step="0.01" :required="customizeForm.variations.length === 0" :disabled="customizeForm.variations.length > 0" :class="customizeForm.variations.length > 0 ? 'bg-gray-100 cursor-not-allowed' : ''" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Offer Price (Rs)</label>
              <input v-model="customizeForm.offer_price" type="number" step="0.01" :disabled="customizeForm.variations.length > 0" :class="customizeForm.variations.length > 0 ? 'bg-gray-100 cursor-not-allowed' : ''" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Discount %</label>
              <input v-model="customizeForm.discount_percentage" type="number" min="0" max="100" :disabled="customizeForm.variations.length > 0" :class="customizeForm.variations.length > 0 ? 'bg-gray-100 cursor-not-allowed' : ''" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
          </div>

          <div class="grid grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Stock Quantity</label>
              <input v-model="customizeForm.stock_quantity" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Prep Time (min)</label>
              <input v-model="customizeForm.preparation_time" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Min Order Qty</label>
              <input v-model="customizeForm.min_order_quantity" type="number" min="1" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium mb-1">Special Notes</label>
            <textarea v-model="customizeForm.special_notes" rows="2" placeholder="Any special instructions..." class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500"></textarea>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div class="space-y-2">
              <label class="block text-sm font-medium">Product Attributes</label>
              <label class="flex items-center gap-2">
                <input v-model="customizeForm.is_vegetarian" type="checkbox" class="w-4 h-4 text-orange-600">
                <span class="text-sm">🥬 Vegetarian</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="customizeForm.is_spicy" type="checkbox" class="w-4 h-4 text-orange-600">
                <span class="text-sm">🌶️ Spicy</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="customizeForm.is_featured" type="checkbox" class="w-4 h-4 text-orange-600">
                <span class="text-sm">⭐ Featured</span>
              </label>
              <label class="flex items-center gap-2">
                <input v-model="customizeForm.is_available" type="checkbox" class="w-4 h-4 text-orange-600">
                <span class="text-sm">✅ Available</span>
              </label>
            </div>
            <div class="space-y-2">
              <label class="block text-sm font-medium">Availability Times</label>
              <div>
                <label class="block text-xs text-gray-600 mb-1">Available From</label>
                <input v-model="customizeForm.available_from" type="time" class="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-xs text-gray-600 mb-1">Available Until</label>
                <input v-model="customizeForm.available_until" type="time" class="w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-orange-500">
              </div>
            </div>
          </div>

          <!-- Variations -->
          <div class="border-t pt-4">
            <div class="flex justify-between items-center mb-2">
              <h3 class="font-bold text-gray-700">📏 Variations (Size, Type)</h3>
              <button type="button" @click="addCustomizeVariation" class="text-orange-600 text-sm font-medium hover:text-orange-700">+ Add Variation</button>
            </div>
            <div v-if="customizeForm.variations.length === 0" class="text-sm text-gray-500 italic">No variations added</div>
            <div v-for="(v, i) in customizeForm.variations" :key="i" class="flex gap-2 mb-2">
              <input v-model="v.name" placeholder="Name (e.g., Small, Medium, Large)" class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              <input v-model="v.price" type="number" step="0.01" placeholder="Extra Price" class="w-32 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              <button type="button" @click="customizeForm.variations.splice(i, 1)" class="text-red-600 px-3 hover:bg-red-50 rounded">×</button>
            </div>
          </div>

          <!-- Add-ons -->
          <div class="border-t pt-4">
            <div class="flex justify-between items-center mb-2">
              <h3 class="font-bold text-gray-700">🍕 Add-ons (Extra Items)</h3>
              <button type="button" @click="addCustomizeAddon" class="text-orange-600 text-sm font-medium hover:text-orange-700">+ Add Add-on</button>
            </div>
            <div v-if="customizeForm.addons.length === 0" class="text-sm text-gray-500 italic">No add-ons added</div>
            <div v-for="(a, i) in customizeForm.addons" :key="i" class="flex gap-2 mb-2">
              <input v-model="a.name" placeholder="Name (e.g., Extra Cheese, Bacon)" class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              <input v-model="a.price" type="number" step="0.01" placeholder="Price" class="w-32 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              <button type="button" @click="customizeForm.addons.splice(i, 1)" class="text-red-600 px-3 hover:bg-red-50 rounded">×</button>
            </div>
          </div>

          <div class="flex gap-3 pt-4">
            <button type="button" @click="showCustomizeModal = false; editingProduct = null;" class="flex-1 px-6 py-3 border rounded-lg">Cancel</button>
            <button type="submit" class="flex-1 px-6 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700">
              {{ editingProduct ? 'Update Product' : 'Add to Menu' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Unavailable Variations Modal -->
    <div v-if="showVariationsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto shadow-2xl">
        <div class="sticky top-0 bg-gradient-to-r from-orange-500 to-orange-600 text-white px-6 py-4 flex justify-between items-center rounded-t-xl">
          <h2 class="text-2xl font-bold">🔴 Unavailable Variations & Addons</h2>
          <button @click="showVariationsModal = false" class="text-white hover:bg-white hover:bg-opacity-20 rounded-full p-2 transition">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>
        
        <div class="p-6">
          <div v-if="unavailableVariationsList.length === 0" class="text-center py-12">
            <div class="text-6xl mb-4">✅</div>
            <h3 class="text-xl font-bold text-gray-800 mb-2">All variations are available!</h3>
          </div>
          
          <div v-for="item in unavailableVariationsList" :key="item.product.id" class="mb-6 bg-gray-50 rounded-lg p-4">
            <div class="flex items-center gap-4 mb-4">
              <img v-if="item.product.image" :src="item.product.image" class="w-16 h-16 object-cover rounded-lg">
              <div class="flex-1">
                <h3 class="font-bold text-lg">{{ item.product.name }}</h3>
                <span class="text-sm text-gray-600">{{ item.product.category?.name }}</span>
              </div>
            </div>
            
            <div v-if="item.variations.length" class="mb-3">
              <h4 class="font-semibold text-gray-700 mb-2">📋 Unavailable Variations:</h4>
              <div class="grid grid-cols-2 gap-2">
                <div v-for="v in item.variations" :key="v.id" class="bg-white border border-red-300 rounded-lg px-3 py-2 text-sm flex items-center justify-between">
                  <div>
                    <span class="font-medium text-gray-700">{{ v.name }}</span>
                    <span class="text-green-600 font-semibold ml-2">+Rs {{ v.price }}</span>
                  </div>
                  <button @click="toggleVariationFromList(item.product.id, v.id)" 
                    class="bg-green-500 text-white px-3 py-1 rounded text-xs font-medium hover:bg-green-600 transition">
                    Enable
                  </button>
                </div>
              </div>
            </div>
            
            <div v-if="item.addons.length">
              <h4 class="font-semibold text-gray-700 mb-2">🍕 Unavailable Addons:</h4>
              <div class="grid grid-cols-2 gap-2">
                <div v-for="a in item.addons" :key="a.id" class="bg-white border border-red-300 rounded-lg px-3 py-2 text-sm flex items-center justify-between">
                  <div>
                    <span class="font-medium text-gray-700">{{ a.name }}</span>
                    <span class="text-green-600 font-semibold ml-2">Rs {{ a.price }}</span>
                  </div>
                  <button @click="toggleAddonFromList(item.product.id, a.id)" 
                    class="bg-green-500 text-white px-3 py-1 rounded text-xs font-medium hover:bg-green-600 transition">
                    Enable
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Deleted Products Modal -->
    <div v-if="showDeletedModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto shadow-2xl">
        <div class="sticky top-0 bg-gradient-to-r from-gray-500 to-gray-600 text-white px-6 py-4 flex justify-between items-center rounded-t-xl">
          <h2 class="text-2xl font-bold">🗑️ Deleted Products</h2>
          <button @click="showDeletedModal = false" class="text-white hover:bg-white hover:bg-opacity-20 rounded-full p-2 transition">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>
        
        <div class="p-6">
          <div v-if="deletedProducts.length === 0" class="text-center py-12">
            <div class="text-6xl mb-4">✅</div>
            <h3 class="text-xl font-bold text-gray-800 mb-2">No deleted products</h3>
          </div>
          
          <div v-else class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-100">
                <tr>
                  <th class="px-4 py-3 text-left text-sm font-semibold">Image</th>
                  <th class="px-4 py-3 text-left text-sm font-semibold">Product</th>
                  <th class="px-4 py-3 text-left text-sm font-semibold">Category</th>
                  <th class="px-4 py-3 text-left text-sm font-semibold">Price</th>
                  <th class="px-4 py-3 text-center text-sm font-semibold">Action</th>
                </tr>
              </thead>
              <tbody class="divide-y">
                <tr v-for="product in deletedProducts" :key="product.id" class="hover:bg-gray-50">
                  <td class="px-4 py-3">
                    <img v-if="product.image" :src="product.image" class="w-12 h-12 object-cover rounded-lg">
                    <div v-else class="w-12 h-12 bg-gray-200 rounded-lg flex items-center justify-center">🍔</div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="font-semibold">{{ product.name }}</div>
                    <div class="text-xs text-gray-500">{{ product.description }}</div>
                  </td>
                  <td class="px-4 py-3 text-sm">{{ product.category?.name }}</td>
                  <td class="px-4 py-3 text-sm font-semibold text-green-600">Rs {{ product.price }}</td>
                  <td class="px-4 py-3 text-center">
                    <button @click="restoreProduct(product.id)" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition text-sm">
                      ↻ Restore
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Confirm Modal -->
    <ConfirmModal
      :show="confirmModal.show"
      :title="confirmModal.title"
      :message="confirmModal.message"
      :icon="confirmModal.icon"
      :type="confirmModal.type"
      :confirmText="confirmModal.confirmText"
      @confirm="confirmModal.onConfirm"
      @cancel="handleConfirmModalCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import api from '../../services/api';
import ConfirmModal from '../ConfirmModal.vue';
import AddProductModal from '../SuperAdmin/ProductManagement/AddProductModal.vue';
import { useToast } from '../../composables/useToast';

const { success: showSuccess, error: showError } = useToast();

const products = ref([]);
const categories = ref([]);
const currentPage = ref(1);
const perPage = ref(10);
const showModal = ref(false);
const showCustomizeModal = ref(false);
const showViewModal = ref(false);
const showVariationsModal = ref(false);
const showDeletedModal = ref(false);
const viewingProduct = ref(null);
const deletedProducts = ref([]);
const deletedProductsCount = ref(0);
const confirmModal = ref({
  show: false,
  title: '',
  message: '',
  icon: '',
  type: 'warning',
  confirmText: 'Confirm',
  onConfirm: null
});
const editingProduct = ref(null);
const filters = ref({ search: '', category_id: '', status: '' });

const customizeForm = ref({
  product_id: null,
  name: '',
  price: 0,
  offer_price: null,
  stock_quantity: 100,
  preparation_time: 15,
  is_vegetarian: false,
  is_spicy: false,
  is_featured: false,
  is_available: true,
  discount_percentage: null,
  special_notes: '',
  available_from: null,
  available_until: null,
  min_order_quantity: 1,
  variations: [],
  addons: []
});

const fetchProducts = async () => {
  try {
    const { data } = await api.get('/manager/products', { params: filters.value });
    console.log('Products loaded:', data);
    if (data && data.length > 0) {
      console.log('First product:', data[0]);
      console.log('First product has pivot?', data[0]?.pivot);
    } else {
      console.log('No products found');
    }
    products.value = data;
  } catch (error) {
    console.error('Error loading products:', error);
  }
};

const fetchCategories = async () => {
  try {
    const { data } = await api.get('/manager/categories');
    console.log('Categories loaded:', data);
    categories.value = data.data || data;
  } catch (error) {
    console.error('Error loading categories:', error);
  }
};

const addCustomizeVariation = () => customizeForm.value.variations.push({ name: '', price: 0 });
const addCustomizeAddon = () => customizeForm.value.addons.push({ name: '', price: 0 });

const addProductToMenu = async () => {
  try {
    if (editingProduct.value && editingProduct.value.pivot) {
      await api.put(`/manager/restaurant-products/${editingProduct.value.id}`, customizeForm.value);
      showSuccess('Product updated successfully!');
    } else {
      await api.post('/manager/restaurant-products', customizeForm.value);
      showSuccess('Product added to your menu!');
    }
    showCustomizeModal.value = false;
    editingProduct.value = null;
    await fetchProducts();
  } catch (error) {
    showError(error.response?.data?.message || 'Failed to save product');
  }
};

const openAddModal = () => {
  editingProduct.value = null;
  showModal.value = true;
};

const editProduct = (product) => {
  console.log('Editing product:', product);
  console.log('Has pivot?', !!product.pivot);
  console.log('Pivot data:', product.pivot);
  
  editingProduct.value = product;
  
  // Check if this is a pivot product (from restaurant_products table)
  if (product.pivot && typeof product.pivot === 'object') {
    console.log('Opening customize modal for pivot product');
    customizeForm.value = {
      product_id: product.id,
      name: product.name,
      price: product.pivot.price || product.price || 0,
      offer_price: product.pivot.offer_price || null,
      stock_quantity: product.pivot.stock_quantity || 100,
      preparation_time: product.pivot.preparation_time || 15,
      is_vegetarian: !!(product.pivot.is_vegetarian ?? product.is_vegetarian ?? false),
      is_spicy: !!(product.pivot.is_spicy ?? product.is_spicy ?? false),
      is_featured: !!(product.pivot.is_featured ?? false),
      is_available: !!(product.pivot.is_available ?? true),
      discount_percentage: product.pivot.discount_percentage || null,
      special_notes: product.pivot.special_notes || '',
      available_from: product.pivot.available_from || product.available_from || null,
      available_until: product.pivot.available_until || product.available_until || null,
      min_order_quantity: product.pivot.min_order_quantity || product.min_order_quantity || 1,
      variations: product.variations?.map(v => ({ name: v.name, price: v.price || 0 })) || [],
      addons: product.addons?.map(a => ({ name: a.name, price: a.price || 0 })) || []
    };
    console.log('Customize form data:', customizeForm.value);
    showCustomizeModal.value = true;
  } else {
    console.log('Opening regular modal for non-pivot product');
    showModal.value = true;
  }
};

const deleteProduct = async (id) => {
  if (confirm('Delete this product? This will mark it as deleted but can be restored later.')) {
    try {
      await api.delete(`/manager/products/${id}`);
      await fetchProducts();
      showSuccess('Product deleted successfully!');
    } catch (error) {
      showError('Failed to delete product');
    }
  }
};

const toggleAvailability = async (product) => {
  try {
    await api.post(`/manager/products/${product.id}/availability`);
    await fetchProducts();
    showSuccess('Product availability updated');
  } catch (error) {
    showError('Failed to update availability');
  }
};

const viewProduct = (product) => {
  viewingProduct.value = product;
  showViewModal.value = true;
};

const toggleVariation = async (variationId) => {
  try {
    await api.post(`/manager/products/${viewingProduct.value.id}/variations/${variationId}/availability`);
    const variation = viewingProduct.value.variations.find(v => v.id === variationId);
    if (variation) variation.is_available = !variation.is_available;
    showSuccess('Variation availability updated');
  } catch (error) {
    showError('Failed to update variation');
  }
};

const toggleAddon = async (addonId) => {
  try {
    await api.post(`/manager/products/${viewingProduct.value.id}/addons/${addonId}/availability`);
    const addon = viewingProduct.value.addons.find(a => a.id === addonId);
    if (addon) addon.is_available = !addon.is_available;
    showSuccess('Addon availability updated');
  } catch (error) {
    showError('Failed to update addon');
  }
};

const unavailableVariationsCount = computed(() => {
  let count = 0;
  if (!products.value) return 0;
  products.value.forEach(p => {
    if (p.variations) count += p.variations.filter(v => !v.is_available).length;
    if (p.addons) count += p.addons.filter(a => !a.is_available).length;
  });
  return count;
});

const unavailableVariationsList = computed(() => {
  if (!products.value) return [];
  const list = [];
  products.value.forEach(p => {
    const unavailableVars = p.variations?.filter(v => !v.is_available) || [];
    const unavailableAddons = p.addons?.filter(a => !a.is_available) || [];
    if (unavailableVars.length || unavailableAddons.length) {
      list.push({ product: p, variations: unavailableVars, addons: unavailableAddons });
    }
  });
  return list;
});

const showUnavailableVariations = () => {
  showVariationsModal.value = true;
};

const toggleVariationFromList = async (productId, variationId) => {
  try {
    await api.post(`/manager/products/${productId}/variations/${variationId}/availability`);
    await fetchProducts();
    showSuccess('Variation enabled');
  } catch (error) {
    showError('Failed to enable variation');
  }
};

const toggleAddonFromList = async (productId, addonId) => {
  try {
    await api.post(`/manager/products/${productId}/addons/${addonId}/availability`);
    await fetchProducts();
    showSuccess('Addon enabled');
  } catch (error) {
    showError('Failed to enable addon');
  }
};

const fetchDeletedProducts = async () => {
  try {
    const { data } = await api.get('/manager/products/trashed');
    deletedProducts.value = data;
    deletedProductsCount.value = data.length;
  } catch (error) {
    console.error('Error loading deleted products:', error);
  }
};

const showDeletedProducts = async () => {
  await fetchDeletedProducts();
  showDeletedModal.value = true;
};

const restoreProduct = async (id) => {
  try {
    await api.post(`/manager/products/${id}/restore`);
    await fetchDeletedProducts();
    await fetchProducts();
    showSuccess('Product restored successfully!');
  } catch (error) {
    showError('Failed to restore product');
  }
};

const closeModal = () => showModal.value = false;

const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * perPage.value;
  const end = start + perPage.value;
  return products.value.slice(start, end);
});

const totalPages = computed(() => {
  return Math.ceil(products.value.length / perPage.value);
});

const calculateDiscountPrice = (product) => {
  const price = product.pivot?.price || product.price;
  const discount = product.pivot?.discount_percentage || product.discount || 0;
  return (price - (price * discount / 100)).toFixed(2);
};

onMounted(() => {
  fetchProducts();
  fetchCategories();
  fetchDeletedProducts();
});
</script>
