<template>
  <div class="min-h-screen bg-gray-50">
    <nav class="bg-gradient-to-r from-orange-500 to-red-500 shadow-lg sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <router-link to="/" class="flex items-center space-x-2 group">
            <span class="text-3xl transform group-hover:scale-110 transition">🍔</span>
            <h1 class="text-2xl font-bold text-white">FoodHub</h1>
          </router-link>
          <div class="flex items-center space-x-4 md:hidden">
            <router-link to="/cart" class="relative text-white">
              <span class="text-2xl">🛒</span>
              <span v-if="cartCount > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center font-bold">{{ cartCount }}</span>
            </router-link>
            <button @click="mobileMenuOpen = !mobileMenuOpen" class="text-white text-2xl">☰</button>
          </div>
          <div class="hidden md:flex items-center space-x-6">
            <router-link to="/" class="text-white hover:text-orange-100 font-medium transition">Home</router-link>
            <router-link to="/restaurants" class="text-white hover:text-orange-100 font-medium transition">Restaurants</router-link>
            <router-link to="/customer/dashboard" class="text-white hover:text-orange-100 font-medium transition">Dashboard</router-link>
            <router-link to="/cart" class="relative text-white">
              <span class="text-2xl">🛒</span>
              <span v-if="cartCount > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center font-bold">{{ cartCount }}</span>
            </router-link>
            <button @click="logout" class="bg-white text-red-600 px-6 py-2 rounded-full font-bold hover:shadow-xl transform hover:scale-105 transition">Logout</button>
          </div>
        </div>
        <div v-if="mobileMenuOpen" class="md:hidden pb-4 space-y-2">
          <router-link to="/" @click="mobileMenuOpen = false" class="block text-white hover:text-orange-100 font-medium py-2">Home</router-link>
          <router-link to="/restaurants" @click="mobileMenuOpen = false" class="block text-white hover:text-orange-100 font-medium py-2">Restaurants</router-link>
          <router-link to="/customer/dashboard" @click="mobileMenuOpen = false" class="block text-white hover:text-orange-100 font-medium py-2">Dashboard</router-link>
          <button @click="logout" class="block w-full bg-white text-red-600 px-6 py-2 rounded-full font-bold">Logout</button>
        </div>
      </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-gradient-to-r from-orange-500 to-red-500 rounded-2xl shadow-lg p-8 text-white mb-8">
        <h2 class="text-3xl font-bold mb-2">Welcome, {{ user?.name }}! 👋</h2>
        <p class="text-orange-100">Ready to order your favorite food?</p>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-xl shadow-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="w-12 h-12 bg-orange-100 rounded-full flex items-center justify-center text-2xl">📦</div>
            <span class="text-3xl font-bold">{{ stats.totalOrders }}</span>
          </div>
          <p class="text-gray-600 font-medium">Total Orders</p>
        </div>

        <div class="bg-white rounded-xl shadow-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center text-2xl">💰</div>
            <span class="text-3xl font-bold">Rs {{ stats.totalSpent }}</span>
          </div>
          <p class="text-gray-600 font-medium">Total Spent</p>
        </div>

        <div class="bg-white rounded-xl shadow-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center text-2xl">🏪</div>
            <span class="text-3xl font-bold">{{ stats.favoriteRestaurants }}</span>
          </div>
          <p class="text-gray-600 font-medium">Favorites</p>
        </div>

        <div class="bg-white rounded-xl shadow-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center text-2xl">⭐</div>
            <span class="text-3xl font-bold">{{ stats.points }}</span>
          </div>
          <p class="text-gray-600 font-medium">Points</p>
        </div>
      </div>

      <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
        <h3 class="text-xl font-bold mb-4">Quick Actions</h3>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <router-link to="/restaurants" class="flex flex-col items-center p-6 rounded-xl bg-gradient-to-br from-orange-50 to-orange-100 hover:shadow-lg">
            <span class="text-4xl mb-2">🍕</span>
            <span class="font-medium">Order Food</span>
          </router-link>
          <router-link to="/orders" class="flex flex-col items-center p-6 rounded-xl bg-gradient-to-br from-blue-50 to-blue-100 hover:shadow-lg">
            <span class="text-4xl mb-2">📦</span>
            <span class="font-medium">Track Order</span>
          </router-link>
          <router-link to="/wallet" class="flex flex-col items-center p-6 rounded-xl bg-gradient-to-br from-green-50 to-green-100 hover:shadow-lg">
            <span class="text-4xl mb-2">💳</span>
            <span class="font-medium">Wallet</span>
          </router-link>
          <router-link to="/profile" class="flex flex-col items-center p-6 rounded-xl bg-gradient-to-br from-purple-50 to-purple-100 hover:shadow-lg">
            <span class="text-4xl mb-2">👤</span>
            <span class="font-medium">Profile</span>
          </router-link>
        </div>
      </div>

      <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-bold">Recent Orders</h3>
          <router-link to="/orders" class="text-orange-600 hover:text-orange-700 font-medium">View All →</router-link>
        </div>
        <div v-if="recentOrders.length === 0" class="text-center py-12">
          <span class="text-6xl mb-4 block">🍽️</span>
          <p class="text-gray-500 mb-4">No orders yet</p>
          <router-link to="/restaurants" class="inline-block bg-gradient-to-r from-orange-500 to-red-500 text-white px-6 py-3 rounded-lg hover:shadow-lg">
            Order Now
          </router-link>
        </div>
        <div v-else class="space-y-4">
          <div v-for="order in recentOrders" :key="order.id" class="border rounded-xl p-4 hover:shadow-md">
            <div class="flex justify-between items-start mb-3">
              <div>
                <h4 class="font-bold">{{ order.restaurant?.name }}</h4>
                <p class="text-sm text-gray-500">Order #{{ order.order_number }}</p>
              </div>
              <span :class="statusClass(order.status)" class="px-3 py-1 rounded-full text-sm font-medium">
                {{ order.status }}
              </span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-sm text-gray-600">{{ formatDate(order.created_at) }}</span>
              <div class="flex items-center gap-3">
                <span class="font-bold">Rs {{ order.total }}</span>
                <router-link :to="`/orders/${order.id}`" class="text-orange-600 hover:text-orange-700 font-medium">View</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-2xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-bold">Favorite Restaurants</h3>
          <router-link to="/restaurants" class="text-orange-600 hover:text-orange-700 font-medium">Browse All →</router-link>
        </div>
        <div v-if="favoriteRestaurants.length === 0" class="text-center py-12">
          <span class="text-6xl mb-4 block">🏪</span>
          <p class="text-gray-500 mb-4">No favorites yet</p>
          <router-link to="/restaurants" class="inline-block bg-gradient-to-r from-orange-500 to-red-500 text-white px-6 py-3 rounded-lg hover:shadow-lg">
            Explore Restaurants
          </router-link>
        </div>
        <div v-else class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div v-for="restaurant in favoriteRestaurants" :key="restaurant.id" class="border rounded-xl overflow-hidden hover:shadow-lg cursor-pointer" @click="$router.push(`/restaurants/${restaurant.id}`)">
            <div class="h-40 bg-gradient-to-br from-orange-400 to-red-400 flex items-center justify-center text-6xl">🏪</div>
            <div class="p-4">
              <h4 class="font-bold mb-1">{{ restaurant.name }}</h4>
              <p class="text-sm text-gray-500 mb-2">{{ restaurant.address }}</p>
              <div class="flex items-center justify-between">
                <span class="text-yellow-500">⭐ {{ restaurant.rating || '4.5' }}</span>
                <span class="text-sm text-gray-600">30 min</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../../stores/auth';
import api from '../../services/api';

const router = useRouter();
const authStore = useAuthStore();
const user = computed(() => authStore.user);

const stats = ref({ totalOrders: 0, totalSpent: 0, favoriteRestaurants: 0, points: 0 });
const recentOrders = ref([]);
const favoriteRestaurants = ref([]);
const mobileMenuOpen = ref(false);
const cartCount = ref(0);

const fetchDashboard = async () => {
  try {
    const ordersRes = await api.get('/orders');
    recentOrders.value = (ordersRes.data.data || ordersRes.data).slice(0, 5);
    stats.value.totalOrders = recentOrders.value.length;
    stats.value.totalSpent = recentOrders.value.reduce((sum, order) => sum + parseFloat(order.total || 0), 0);
    stats.value.points = Math.floor(stats.value.totalSpent / 100);
  } catch (error) {
    console.error('Error:', error);
  }
};

const fetchFavorites = async () => {
  try {
    const res = await api.get('/restaurants');
    favoriteRestaurants.value = (res.data.data || res.data).slice(0, 3);
    stats.value.favoriteRestaurants = favoriteRestaurants.value.length;
  } catch (error) {
    console.error('Error:', error);
  }
};

const statusClass = (status) => {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800',
    accepted: 'bg-blue-100 text-blue-800',
    preparing: 'bg-purple-100 text-purple-800',
    delivered: 'bg-green-100 text-green-800',
    cancelled: 'bg-red-100 text-red-800',
  };
  return classes[status] || 'bg-gray-100 text-gray-800';
};

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
};

const logout = () => {
  authStore.logout();
  router.push('/login');
};

onMounted(() => {
  fetchDashboard();
  fetchFavorites();
});
</script>
