<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Navbar -->
    <Navbar />

    <!-- Search & Filters -->
    <div class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 py-6">
        <!-- Search Bar -->
        <div class="relative max-w-2xl mx-auto mb-6">
          <svg class="w-6 h-6 absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
          </svg>
          <input v-model="searchQuery" type="text" placeholder="Search restaurants, cuisines, or dishes..." class="w-full pl-14 pr-4 py-4 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent shadow-sm">
        </div>

        <!-- Filters -->
        <div class="flex flex-wrap gap-3 items-center">
          <button @click="selectedCategory = ''" :class="selectedCategory === '' ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-700'" class="px-4 py-2 rounded-lg font-medium hover:bg-orange-400 hover:text-white transition">
            All
          </button>
          <button v-for="category in categories" :key="category.id" @click="selectedCategory = category.id" :class="selectedCategory === category.id ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-700'" class="px-4 py-2 rounded-lg font-medium hover:bg-orange-400 hover:text-white transition">
            {{ category.name }}
          </button>

          <div class="ml-auto flex gap-2">
            <select v-model="sortBy" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
              <option value="popular">Most Popular</option>
              <option value="rating">Highest Rated</option>
              <option value="delivery_time">Fastest Delivery</option>
              <option value="distance">Nearest</option>
            </select>
          </div>
        </div>
      </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- Results Header -->
      <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-800">
          {{ selectedCategory ? getCategoryName(selectedCategory) : 'All Restaurants' }}
        </h2>
        <p class="text-gray-600">{{ filteredRestaurants.length }} restaurants found</p>
      </div>

      <!-- Loading State -->
      <div v-if="loading" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <div v-for="i in 8" :key="i" class="bg-white rounded-xl shadow-sm overflow-hidden animate-pulse">
          <div class="h-48 bg-gray-200"></div>
          <div class="p-4">
            <div class="h-4 bg-gray-200 rounded mb-2"></div>
            <div class="h-3 bg-gray-200 rounded w-2/3"></div>
          </div>
        </div>
      </div>

      <!-- No Results -->
      <div v-else-if="filteredRestaurants.length === 0" class="text-center py-16">
        <div class="text-6xl mb-4">🔍</div>
        <h3 class="text-xl font-bold text-gray-800 mb-2">No restaurants found</h3>
        <p class="text-gray-600 mb-6">Try adjusting your search or filters</p>
        <button @click="clearFilters" class="bg-orange-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-orange-700 transition">
          Clear Filters
        </button>
      </div>

      <!-- Restaurants Grid -->
      <div v-else class="grid grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <div v-for="restaurant in filteredRestaurants" :key="restaurant.id" @click="goToRestaurant(restaurant.id)" class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-xl transition cursor-pointer group">
          <!-- Restaurant Image -->
          <div class="relative h-48 bg-gray-200 overflow-hidden">
            <img v-if="restaurant.image" :src="restaurant.image" :alt="restaurant.name" class="w-full h-full object-cover group-hover:scale-110 transition duration-300">
            <div v-else class="w-full h-full flex items-center justify-center bg-gradient-to-br from-orange-400 to-orange-600">
              <span class="text-6xl">🍽️</span>
            </div>

            <!-- Badges -->
            <div class="absolute top-3 left-3 flex flex-col gap-2">
              <span v-if="restaurant.is_featured" class="bg-yellow-500 text-white px-3 py-1 rounded-full text-xs font-bold shadow-lg">
                ⭐ Featured
              </span>
            </div>

            <!-- Rating -->
            <div class="absolute top-3 right-3 bg-white px-3 py-1 rounded-full text-sm font-semibold flex items-center gap-1 shadow-lg">
              <svg class="w-4 h-4 text-yellow-500" fill="currentColor" viewBox="0 0 20 20">
                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
              </svg>
              {{ restaurant.rating }}
            </div>

            <!-- Status Badge -->
            <div class="absolute bottom-3 left-3">
              <span :class="restaurant.is_open ? 'bg-green-500' : 'bg-red-500'" class="text-white px-3 py-1 rounded-full text-xs font-bold shadow-lg">
                {{ restaurant.is_open ? '● Open Now' : '● Closed' }}
              </span>
            </div>
          </div>

          <!-- Restaurant Info -->
          <div class="p-4">
            <h3 class="font-bold text-lg mb-1 group-hover:text-orange-600 transition">{{ restaurant.name }}</h3>
            <p class="text-sm text-gray-600 mb-3 line-clamp-2">{{ restaurant.description || 'Delicious food delivered to your door' }}</p>

            <!-- Details -->
            <div class="flex items-center justify-between text-sm text-gray-500">
              <span class="flex items-center gap-1">
                <svg class="w-4 h-4" 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>
                {{ restaurant.delivery_time }} min
              </span>
              <span class="flex items-center gap-1">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                </svg>
                {{ restaurant.delivery_radius }} km
              </span>
              <span class="flex items-center gap-1 font-semibold text-orange-600">
                Rs {{ restaurant.delivery_fee }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import api from '../../services/api';
import Navbar from '../../components/Navbar.vue';

const router = useRouter();
const loading = ref(true);
const restaurants = ref([]);
const categories = ref([]);
const searchQuery = ref('');
const selectedCategory = ref('');
const sortBy = ref('popular');

const filteredRestaurants = computed(() => {
  let filtered = restaurants.value;

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(r =>
      r.name.toLowerCase().includes(query) ||
      r.description?.toLowerCase().includes(query) ||
      r.tags?.some(tag => tag.toLowerCase().includes(query))
    );
  }

  // Sort
  if (sortBy.value === 'rating') {
    filtered = [...filtered].sort((a, b) => (b.rating || 0) - (a.rating || 0));
  } else if (sortBy.value === 'delivery_time') {
    filtered = [...filtered].sort((a, b) => (a.delivery_time || 30) - (b.delivery_time || 30));
  } else if (sortBy.value === 'distance') {
    filtered = [...filtered].sort((a, b) => (a.distance || 5) - (b.distance || 5));
  }

  return filtered;
});

const loadRestaurants = async () => {
  try {
    loading.value = true;
    const params = {};
    if (selectedCategory.value) {
      params.category_id = selectedCategory.value;
    }
    const response = await api.get('/restaurants', { params });
    restaurants.value = response.data.data || response.data || [];
  } catch (error) {
    console.error('Error loading restaurants:', error);
    restaurants.value = [];
  } finally {
    loading.value = false;
  }
};

const loadCategories = async () => {
  try {
    const response = await api.get('/categories');
    categories.value = response.data.data || [];
  } catch (error) {
    console.error('Error loading categories:', error);
    categories.value = [];
  }
};

const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId);
  return category ? category.name : 'Category';
};

const clearFilters = () => {
  searchQuery.value = '';
  selectedCategory.value = '';
  sortBy.value = 'popular';
};

const goToRestaurant = (id) => {
  router.push(`/restaurants/${id}`);
};

onMounted(() => {
  loadRestaurants();
  loadCategories();
});

watch(selectedCategory, () => {
  loadRestaurants();
});
</script>
