<template>
  <div class="super-admin-layout">
    <!-- Desktop Sidebar -->
    <aside class="sidebar">
      <div class="sidebar-header">
        <h2>🍔 FoodHub</h2>
        <p>Super Admin</p>
      </div>
      <nav class="sidebar-nav">
        <router-link v-for="item in menuItems" :key="item.to" :to="item.to" class="nav-link">
          <span>{{ item.icon }}</span>
          <span>{{ item.title }}</span>
        </router-link>
      </nav>
      <button class="logout-btn" @click="handleLogout">
        <span>🚪</span>
        <span>Logout</span>
      </button>
    </aside>

    <!-- Mobile Header -->
    <header class="mobile-header">
      <button @click="showMenu = !showMenu">☰</button>
      <h1>🎯 Dashboard</h1>
      <button @click="loadDashboard">🔄</button>
    </header>

    <!-- Mobile Menu -->
    <div v-if="showMenu" class="mobile-overlay" @click="showMenu = false">
      <nav class="mobile-menu" @click.stop>
        <div class="menu-header">
          <h2>🍔 FoodHub</h2>
          <button @click="showMenu = false">✕</button>
        </div>
        <router-link v-for="item in menuItems" :key="item.to" :to="item.to" @click="showMenu = false">
          {{ item.icon }} {{ item.title }}
        </router-link>
        <button class="logout-btn" @click="handleLogout">🚪 Logout</button>
      </nav>
    </div>

    <!-- Main Content -->
    <main class="main-content">
      <router-view v-if="$route.path !== '/super-admin'" />
      
      <div v-else>
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <p>Loading...</p>
        </div>

        <div v-else class="dashboard">
          <!-- Stats -->
          <div class="stats-grid">
            <div class="stat-card">
              <span class="stat-icon">💰</span>
              <div>
                <h3>Revenue</h3>
                <p class="stat-value">${{ formatNumber(stats.total_revenue?.value) }}</p>
              </div>
            </div>
            <div class="stat-card">
              <span class="stat-icon">📦</span>
              <div>
                <h3>Orders</h3>
                <p class="stat-value">{{ formatNumber(stats.total_orders?.value) }}</p>
              </div>
            </div>
            <div class="stat-card">
              <span class="stat-icon">🏪</span>
              <div>
                <h3>Restaurants</h3>
                <p class="stat-value">{{ formatNumber(stats.total_restaurants?.value) }}</p>
              </div>
            </div>
            <div class="stat-card">
              <span class="stat-icon">👥</span>
              <div>
                <h3>Users</h3>
                <p class="stat-value">{{ formatNumber(stats.total_users?.value) }}</p>
              </div>
            </div>
          </div>

          <!-- Top Restaurants -->
          <div class="section">
            <h2>🏆 Top Restaurants</h2>
            <div class="list">
              <div v-for="(restaurant, index) in topPerformers.restaurants" :key="restaurant.id" class="list-item">
                <span class="rank">{{ index + 1 }}</span>
                <div class="list-info">
                  <h4>{{ restaurant.name }}</h4>
                  <p>${{ formatNumber(restaurant.revenue) }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- Charts -->
          <div class="section">
            <h2>📊 Revenue Chart</h2>
            <canvas ref="revenueChart" style="max-height: 250px;"></canvas>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

export default {
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const showMenu = ref(false)
    const stats = ref({})
    const charts = ref({})
    const topPerformers = ref({ restaurants: [], products: [], delivery_boys: [] })
    const revenueChart = ref(null)
    let chartInstance = null

    const menuItems = [
      { icon: '🎯', title: 'Dashboard', to: '/super-admin' },
      { icon: '🏪', title: 'Restaurants', to: '/super-admin/restaurants' },
      { icon: '📦', title: 'Orders', to: '/super-admin/orders' },
      { icon: '💳', title: 'Payments', to: '/super-admin/payments' },
      { icon: '🚴', title: 'Delivery Boys', to: '/super-admin/delivery-boys' },
      { icon: '👥', title: 'Users', to: '/super-admin/users' },
      { icon: '⚙️', title: 'Settings', to: '/super-admin/settings' }
    ]

    const loadDashboard = async () => {
      loading.value = true
      try {
        const { data } = await axios.get('http://localhost:8000/api/admin/dashboard')
        stats.value = data.data.stats
        charts.value = data.data.charts
        topPerformers.value = data.data.top_performers
        await nextTick()
        renderChart()
      } catch (error) {
        console.error('Failed to load dashboard:', error)
      } finally {
        loading.value = false
      }
    }

    const renderChart = () => {
      if (chartInstance) chartInstance.destroy()
      if (revenueChart.value) {
        const ctx = revenueChart.value.getContext('2d')
        chartInstance = new Chart(ctx, {
          type: 'line',
          data: {
            labels: charts.value.revenue?.map(d => d.date) || [],
            datasets: [{
              label: 'Revenue',
              data: charts.value.revenue?.map(d => d.amount) || [],
              borderColor: '#ff6b35',
              backgroundColor: 'rgba(255, 107, 53, 0.1)',
              tension: 0.4,
              fill: true
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false
          }
        })
      }
    }

    const formatNumber = (num) => new Intl.NumberFormat().format(num || 0)

    const handleLogout = () => {
      localStorage.removeItem('token')
      router.push('/login')
    }

    onMounted(loadDashboard)

    return { loading, showMenu, stats, charts, topPerformers, revenueChart, menuItems, loadDashboard, formatNumber, handleLogout }
  }
}
</script>

<style scoped>
.super-admin-layout { display: flex; min-height: 100vh; background: #f8fafc; }

/* Sidebar */
.sidebar {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  width: 260px;
  background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
  padding: 2rem 0;
  display: none;
  flex-direction: column;
  z-index: 1000;
}

.sidebar-header { padding: 0 1.5rem 2rem; border-bottom: 1px solid rgba(255, 107, 53, 0.2); margin-bottom: 2rem; }
.sidebar-header h2 { margin: 0; font-size: 1.5rem; color: white; font-weight: 700; }
.sidebar-header p { margin: 0.5rem 0 0; font-size: 0.875rem; color: #94a3b8; }

.sidebar-nav { flex: 1; padding: 0 1rem; overflow-y: auto; }

.nav-link {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.25rem;
  margin: 0.5rem 0;
  border-radius: 12px;
  text-decoration: none;
  color: #cbd5e1;
  font-weight: 500;
  transition: all 0.3s;
}

.nav-link:hover { background: rgba(255, 107, 53, 0.1); color: white; }
.nav-link.router-link-active { background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; }

.logout-btn {
  margin: 1.5rem 1rem;
  padding: 1rem;
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.3s;
}

.logout-btn:hover { transform: translateY(-2px); }

/* Mobile */
.mobile-header {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.mobile-header h1 { margin: 0; font-size: 1.25rem; color: white; font-weight: 700; }
.mobile-header button { background: rgba(255,255,255,0.2); border: none; padding: 0.5rem; border-radius: 8px; color: white; cursor: pointer; }

.mobile-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.6);
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.mobile-menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 280px;
  background: linear-gradient(180deg, #1e293b, #0f172a);
  padding: 1.5rem;
  overflow-y: auto;
}

.menu-header { display: flex; justify-content: space-between; margin-bottom: 2rem; padding-bottom: 1.5rem; border-bottom: 2px solid rgba(255,107,53,0.3); }
.menu-header h2 { margin: 0; color: white; }
.menu-header button { background: rgba(255,255,255,0.1); border: none; color: white; padding: 0.5rem; border-radius: 8px; cursor: pointer; }

.mobile-menu a {
  display: block;
  padding: 1rem;
  margin: 0.5rem 0;
  border-radius: 12px;
  text-decoration: none;
  color: #cbd5e1;
  transition: all 0.3s;
}

.mobile-menu a:hover, .mobile-menu a.router-link-active { background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; }

/* Main Content */
.main-content { flex: 1; margin-left: 0; overflow-y: auto; height: 100vh; }

@media (min-width: 1024px) {
  .sidebar { display: flex; }
  .main-content { margin-left: 260px; }
  .mobile-header { display: none; }
}

.loading { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 50vh; }
.spinner { width: 50px; height: 50px; border: 4px solid #e5e7eb; border-top-color: #ff6b35; border-radius: 50%; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }

.dashboard { padding: 2rem; }

.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 16px;
  display: flex;
  gap: 1rem;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.3s;
}

.stat-card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
.stat-icon { font-size: 2.5rem; }
.stat-card h3 { margin: 0 0 0.5rem; font-size: 0.875rem; color: #6b7280; }
.stat-value { margin: 0; font-size: 1.5rem; font-weight: 700; color: #1f2937; }

.section { background: white; padding: 1.5rem; border-radius: 16px; margin-bottom: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.section h2 { margin: 0 0 1rem; font-size: 1.125rem; color: #1f2937; }

.action-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; }

.action-btn {
  padding: 1rem;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  text-decoration: none;
  border-radius: 12px;
  text-align: center;
  font-weight: 600;
  transition: all 0.3s;
}

.action-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255,107,53,0.3); }

.list { display: flex; flex-direction: column; gap: 0.75rem; }
.list-item { display: flex; align-items: center; gap: 1rem; padding: 0.75rem; background: #f9fafb; border-radius: 8px; }
.rank { font-size: 1.25rem; font-weight: 700; color: #f59e0b; min-width: 2rem; }
.list-info { flex: 1; }
.list-info h4 { margin: 0 0 0.25rem; font-size: 0.875rem; color: #1f2937; }
.list-info p { margin: 0; font-size: 0.875rem; color: #10b981; font-weight: 600; }
</style>
