<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 py-6">
      <!-- Restaurant Header -->
      <div v-if="restaurant" class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-start gap-4">
          <img :src="restaurant.image || '/placeholder.jpg'" class="w-24 h-24 rounded-lg object-cover">
          <div class="flex-1">
            <h1 class="text-3xl font-bold text-gray-900">{{ restaurant.name }}</h1>
            <p class="text-gray-600 mt-1">{{ restaurant.description }}</p>
            <div class="flex items-center gap-4 mt-3 text-sm text-gray-500">
              <span>⭐ {{ restaurant.rating || '4.5' }}</span>
              <span>🚚 Rs {{ restaurant.delivery_fee || '100' }} Delivery</span>
              <span>⏱️ {{ restaurant.delivery_time || '30-45' }} mins</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Category Tabs -->
      <div class="bg-white rounded-lg shadow-sm mb-6 sticky top-0 z-10">
        <div class="flex overflow-x-auto">
          <button v-for="category in categories" :key="category.id" @click="selectedCategory = category.id" :class="selectedCategory === category.id ? 'bg-gradient-to-r from-orange-500 to-orange-600 text-white' : 'text-gray-600 hover:bg-gray-50'" class="px-6 py-4 font-medium whitespace-nowrap transition">
            {{ category.name }}
          </button>
        </div>
      </div>

      <!-- Products Grid -->
      <div v-if="loading" class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div v-for="i in 6" :key="i" class="bg-white rounded-lg p-4 animate-pulse">
          <div class="h-40 bg-gray-200 rounded mb-3"></div>
          <div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
          <div class="h-3 bg-gray-200 rounded w-1/2"></div>
        </div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div v-for="product in filteredProducts" :key="product.id" class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition cursor-pointer" @click="openProductModal(product)">
          <img :src="product.image || '/placeholder.jpg'" class="w-full h-48 object-cover">
          <div class="p-4">
            <h3 class="font-semibold text-gray-900 mb-1">{{ product.name }}</h3>
            <p class="text-sm text-gray-500 mb-3 line-clamp-2">{{ product.description }}</p>
            <div class="flex items-center justify-between">
              <span class="text-lg font-bold text-orange-600">Rs {{ product.base_price }}</span>
              <button class="bg-gradient-to-r from-orange-500 to-orange-600 text-white px-4 py-2 rounded-lg text-sm hover:shadow-lg transition">
                Add
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Product Modal -->
    <div v-if="showModal && selectedProduct" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" @click.self="closeModal">
      <div class="bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="relative">
          <img :src="selectedProduct.image || '/placeholder.jpg'" class="w-full h-64 object-cover">
          <button @click="closeModal" class="absolute top-4 right-4 bg-white rounded-full p-2 shadow-lg hover:bg-gray-100">
            <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">
          <h2 class="text-2xl font-bold text-gray-900 mb-2">{{ selectedProduct.name }}</h2>
          <p class="text-gray-600 mb-4">{{ selectedProduct.description }}</p>

          <!-- Variants Selection -->
          <div v-if="selectedProduct.has_variants && variants.length" class="mb-6">
            <h3 class="font-semibold text-gray-900 mb-3">Select Size <span class="text-red-500">*</span></h3>
            <div class="space-y-2">
              <label v-for="variant in variants" :key="variant.id" class="flex items-center justify-between p-3 border rounded-lg cursor-pointer hover:border-orange-500 transition" :class="selectedVariant === variant.id ? 'border-orange-500 bg-orange-50' : 'border-gray-200'">
                <div class="flex items-center gap-3">
                  <input v-model="selectedVariant" :value="variant.id" type="radio" name="variant" class="text-orange-600 focus:ring-orange-500">
                  <span class="font-medium text-gray-900">{{ variant.name }}</span>
                </div>
                <span class="font-semibold text-orange-600">Rs {{ variant.price }}</span>
              </label>
            </div>
          </div>

          <!-- Add-ons Selection -->
          <div v-if="addons.length" class="mb-6">
            <h3 class="font-semibold text-gray-900 mb-3">Add-ons (Optional)</h3>
            <div class="space-y-2">
              <label v-for="addon in addons" :key="addon.id" class="flex items-center justify-between p-3 border rounded-lg cursor-pointer hover:border-orange-500 transition" :class="selectedAddons.includes(addon.id) ? 'border-orange-500 bg-orange-50' : 'border-gray-200'">
                <div class="flex items-center gap-3">
                  <input v-model="selectedAddons" :value="addon.id" type="checkbox" class="rounded text-orange-600 focus:ring-orange-500">
                  <span class="font-medium text-gray-900">{{ addon.name }}</span>
                </div>
                <span class="font-semibold text-orange-600">+ Rs {{ addon.price }}</span>
              </label>
            </div>
          </div>

          <!-- Quantity -->
          <div class="mb-6">
            <h3 class="font-semibold text-gray-900 mb-3">Quantity</h3>
            <div class="flex items-center gap-4">
              <button @click="quantity > 1 && quantity--" class="w-10 h-10 rounded-full border-2 border-gray-300 flex items-center justify-center hover:border-orange-500 transition">
                <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="M20 12H4"/>
                </svg>
              </button>
              <span class="text-xl font-semibold w-12 text-center">{{ quantity }}</span>
              <button @click="quantity++" class="w-10 h-10 rounded-full border-2 border-gray-300 flex items-center justify-center hover:border-orange-500 transition">
                <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 4v16m8-8H4"/>
                </svg>
              </button>
            </div>
          </div>

          <!-- Total Price -->
          <div class="flex items-center justify-between mb-6 p-4 bg-gray-50 rounded-lg">
            <span class="text-lg font-semibold text-gray-900">Total Price</span>
            <span class="text-2xl font-bold text-orange-600">Rs {{ totalPrice }}</span>
          </div>

          <!-- Add to Cart Button -->
          <button @click="addToCart" class="w-full bg-gradient-to-r from-orange-500 to-orange-600 text-white py-4 rounded-lg font-semibold text-lg hover:shadow-lg transition">
            Add to Cart
          </button>
        </div>
      </div>
    </div>

    <!-- Cart Float Button -->
    <button v-if="cartCount > 0" @click="goToCart" class="fixed bottom-6 right-6 bg-gradient-to-r from-orange-500 to-orange-600 text-white px-6 py-4 rounded-full shadow-lg hover:shadow-xl transition flex items-center gap-3">
      <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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/>
      </svg>
      <span class="font-semibold">{{ cartCount }} items</span>
    </button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const restaurantId = route.params.id;

const restaurant = ref(null);
const categories = ref([]);
const products = ref([]);
const selectedCategory = ref(null);
const loading = ref(true);
const showModal = ref(false);
const selectedProduct = ref(null);
const variants = ref([]);
const addons = ref([]);
const selectedVariant = ref(null);
const selectedAddons = ref([]);
const quantity = ref(1);
const cartCount = ref(0);

const filteredProducts = computed(() => {
  if (!selectedCategory.value) return products.value;
  return products.value.filter(p => p.category_id === selectedCategory.value);
});

const totalPrice = computed(() => {
  let price = 0;
  
  if (selectedProduct.value?.has_variants && selectedVariant.value) {
    const variant = variants.value.find(v => v.id === selectedVariant.value);
    price = variant ? variant.price : selectedProduct.value.base_price;
  } else {
    price = selectedProduct.value?.base_price || 0;
  }
  
  selectedAddons.value.forEach(addonId => {
    const addon = addons.value.find(a => a.id === addonId);
    if (addon) price += addon.price;
  });
  
  return price * quantity.value;
});

const fetchData = async () => {
  loading.value = true;
  try {
    const [restaurantRes, categoriesRes, productsRes] = await Promise.all([
      axios.get(`/api/restaurants/${restaurantId}`),
      axios.get(`/api/restaurants/${restaurantId}/categories`),
      axios.get(`/api/restaurants/${restaurantId}/products`)
    ]);
    
    restaurant.value = restaurantRes.data.data;
    categories.value = categoriesRes.data.data;
    products.value = productsRes.data.data;
    
    if (categories.value.length) {
      selectedCategory.value = categories.value[0].id;
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const openProductModal = async (product) => {
  selectedProduct.value = product;
  selectedVariant.value = null;
  selectedAddons.value = [];
  quantity.value = 1;
  
  try {
    if (product.has_variants) {
      const { data } = await axios.get(`/api/products/${product.id}/variants`);
      variants.value = data.data;
      const defaultVariant = variants.value.find(v => v.is_default);
      if (defaultVariant) selectedVariant.value = defaultVariant.id;
    }
    
    const { data } = await axios.get(`/api/products/${product.id}/addons`);
    addons.value = data.data;
  } catch (error) {
    console.error(error);
  }
  
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  selectedProduct.value = null;
  variants.value = [];
  addons.value = [];
};

const addToCart = async () => {
  if (selectedProduct.value.has_variants && !selectedVariant.value) {
    alert('Please select a size');
    return;
  }
  
  try {
    await axios.post('/api/cart', {
      product_id: selectedProduct.value.id,
      variant_id: selectedVariant.value,
      addon_ids: selectedAddons.value,
      quantity: quantity.value
    });
    
    cartCount.value += quantity.value;
    closeModal();
  } catch (error) {
    console.error(error);
    alert('Failed to add to cart');
  }
};

const goToCart = () => {
  router.push('/cart');
};

onMounted(fetchData);
</script>
