<!-- src/pages/Index.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Welcome Header with Greeting -->
      <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
        <div>
          <h1 class="text-3xl md:text-4xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
            Welcome back, {{ employee.employee_first_name }}!
          </h1>
          <p class="text-base-content/60 mt-1">Here's what's happening today</p>
        </div>
        <div class="flex items-center gap-2">
          <div class="badge badge-lg badge-primary gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4">
              <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />
            </svg>
            {{ formattedDate }}
          </div>
        </div>
      </div>

      <!-- Oil Price Ticker -->
      <OilPriceTicker :prices="oilPriceStore.prices" />

      <!-- Main Dashboard Grid -->
      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 animate-fade-in">

        <!-- Left Column: Stats & Chart -->
        <div class="lg:col-span-8 space-y-6">

          <!-- Stats Row: Quick Glance Cards -->
          <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Today's Deliveries -->
            <div class="stat-card group">
              <div class="flex items-center justify-between mb-2">
                <span class="text-xs uppercase tracking-wider text-base-content/50 font-semibold">Today</span>
                <div class="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center group-hover:scale-110 transition-transform">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4 text-primary">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h1.125c.621 0 1.129-.504 1.09-1.124a17.902 17.902 0 00-3.213-9.193 2.056 2.056 0 00-1.58-.86H14.25M16.5 18.75h-2.25m0-11.177v-.958c0-.568-.422-1.048-.987-1.106a48.554 48.554 0 00-10.026 0 1.106 1.106 0 00-.987 1.106v7.635m12-6.677v6.677m0 4.5v-4.5m0 0h-12" />
                  </svg>
                </div>
              </div>
              <div class="text-3xl font-bold">{{ delivery_count }}</div>
              <div class="flex items-center gap-1 mt-1">
                <span class="text-success text-sm font-medium">{{ delivery_count_delivered }}</span>
                <span class="text-base-content/50 text-xs">delivered</span>
              </div>
              <progress class="progress progress-primary w-full h-2 mt-2" :value="delivery_count_delivered" :max="delivery_count || 1"></progress>
            </div>

            <!-- Week Gallons -->
            <div class="stat-card group">
              <div class="flex items-center justify-between mb-2">
                <span class="text-xs uppercase tracking-wider text-base-content/50 font-semibold">This Week</span>
                <div class="w-8 h-8 rounded-lg bg-success/10 flex items-center justify-center group-hover:scale-110 transition-transform">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4 text-success">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 0v3.75m-16.5-3.75v3.75m16.5 0v3.75C20.25 16.153 16.556 18 12 18s-8.25-1.847-8.25-4.125v-3.75m16.5 0c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125" />
                  </svg>
                </div>
              </div>
              <div class="text-3xl font-bold">{{ formatNumber(total_gallons_past_week) }}</div>
              <div class="text-base-content/50 text-xs mt-1">gallons delivered</div>
            </div>

            <!-- Week Deliveries -->
            <div class="stat-card group">
              <div class="flex items-center justify-between mb-2">
                <span class="text-xs uppercase tracking-wider text-base-content/50 font-semibold">Deliveries</span>
                <div class="w-8 h-8 rounded-lg bg-info/10 flex items-center justify-center group-hover:scale-110 transition-transform">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4 text-info">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
                  </svg>
                </div>
              </div>
              <div class="text-3xl font-bold">{{ total_deliveries }}</div>
              <div class="text-base-content/50 text-xs mt-1">this week</div>
            </div>

            <!-- Tomorrow's Deliveries -->
            <div class="stat-card group">
              <div class="flex items-center justify-between mb-2">
                <span class="text-xs uppercase tracking-wider text-base-content/50 font-semibold">Tomorrow</span>
                <div class="w-8 h-8 rounded-lg bg-warning/10 flex items-center justify-center group-hover:scale-110 transition-transform">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4 text-warning">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5m-9-6h.008v.008H12v-.008zM12 15h.008v.008H12V15zm0 2.25h.008v.008H12v-.008zM9.75 15h.008v.008H9.75V15zm0 2.25h.008v.008H9.75v-.008zM7.5 15h.008v.008H7.5V15zm0 2.25h.008v.008H7.5v-.008zm6.75-4.5h.008v.008h-.008v-.008zm0 2.25h.008v.008h-.008V15zm0 2.25h.008v.008h-.008v-.008zm2.25-4.5h.008v.008H16.5v-.008zm0 2.25h.008v.008H16.5V15z" />
                  </svg>
                </div>
              </div>
              <div class="text-3xl font-bold">{{ countsStore.tomorrow }}</div>
              <div class="text-base-content/50 text-xs mt-1">deliveries scheduled</div>
            </div>
          </div>

          <!-- Weekly Trend Chart -->
          <div class="card-glass p-6">
            <div class="flex items-center justify-between mb-4">
              <div>
                <h3 class="text-lg font-semibold">Weekly Delivery Trend</h3>
                <p class="text-sm text-base-content/50">Gallons delivered over the past 4 months (weekly)</p>
              </div>
              <router-link :to="{ name: 'stats' }" class="btn btn-ghost btn-sm gap-1">
                View Stats
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                </svg>
              </router-link>
            </div>
            <div class="h-64">
              <Line
                v-if="chartData"
                :data="chartData as any"
                :options="chartOptions as any"
              />
              <div v-else class="flex items-center justify-center h-full">
                <span class="loading loading-spinner loading-lg"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- Right Column: Map & Quick Actions -->
        <div class="lg:col-span-4 space-y-6">

          <!-- Mini Delivery Map -->
          <div class="card-glass p-4 overflow-hidden">
            <div class="flex items-center justify-between mb-3">
              <h3 class="font-semibold flex items-center gap-2">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5 text-primary">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
                </svg>
                Today's Routes
              </h3>
              <router-link :to="{ name: 'deliveryMap' }" class="btn btn-xs btn-ghost">
                Full Map
              </router-link>
            </div>

            <!-- Map Stats -->
            <div class="flex gap-2 mb-3">
              <span class="badge badge-sm badge-primary">{{ mapDeliveries.length }} stops</span>
              <span class="badge badge-sm badge-secondary">{{ uniqueTowns.length }} towns</span>
            </div>

            <!-- Map Container -->
            <div class="rounded-lg overflow-hidden h-64 bg-base-300">
              <l-map
                v-if="mapDeliveries.length > 0"
                ref="map"
                :zoom="mapZoom"
                :center="mapCenter"
                :use-global-leaflet="false"
                class="h-full w-full"
              >
                <l-tile-layer
                  url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                  layer-type="base"
                  name="OpenStreetMap"
                ></l-tile-layer>
                <l-marker
                  v-for="delivery in mappedDeliveries"
                  :key="delivery.id"
                  :lat-lng="[parseFloat(delivery.latitude!), parseFloat(delivery.longitude!)]"
                >
                  <l-popup>
                    <div class="text-sm">
                      <p class="font-bold">{{ delivery.customerName }}</p>
                      <p>{{ delivery.town }}</p>
                    </div>
                  </l-popup>
                </l-marker>
              </l-map>
              <div v-else class="flex flex-col items-center justify-center h-full text-base-content/50">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-12 h-12 mb-2">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498l4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 00-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0z" />
                </svg>
                <p class="text-sm">No deliveries mapped</p>
              </div>
            </div>
          </div>

          <!-- Quick Actions -->
          <div class="card-glass p-4">
            <h3 class="font-semibold mb-3 flex items-center gap-2">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5 text-accent">
                <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
              </svg>
              Quick Actions
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
              <router-link :to="{ name: 'customerCreate' }" class="quick-action-btn">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M19 7.5v3m0 0v3m0-3h3m-3 0h-3m-2.25-4.125a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zM4 19.235v-.11a6.375 6.375 0 0112.75 0v.109A12.318 12.318 0 0110.374 21c-2.331 0-4.512-.645-6.374-1.766z" />
                </svg>
                <span>New Customer</span>
              </router-link>
              <router-link :to="{ name: 'delivery' }" class="quick-action-btn">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                </svg>
                <span>Deliveries</span>
              </router-link>
              <router-link :to="{ name: 'deliveryOutForDelivery' }" class="quick-action-btn">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h1.125c.621 0 1.129-.504 1.09-1.124a17.902 17.902 0 00-3.213-9.193 2.056 2.056 0 00-1.58-.86H14.25M16.5 18.75h-2.25m0-11.177v-.958c0-.568-.422-1.048-.987-1.106a48.554 48.554 0 00-10.026 0 1.106 1.106 0 00-.987 1.106v7.635m12-6.677v6.677m0 4.5v-4.5m0 0h-12" />
                </svg>
                <span>Today's Run</span>
              </router-link>
              <router-link :to="{ name: 'ServiceCalendar' }" class="quick-action-btn">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />
                </svg>
                <span>Service Calendar</span>
              </router-link>
            </div>
          </div>

          <!-- Recent Activity / Town Distribution -->
          <div class="card-glass p-4">
            <h3 class="font-semibold mb-3 flex items-center gap-2">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-5 h-5 text-info">
                <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 21h19.5m-18-18v18m10.5-18v18m6-13.5V21M6.75 6.75h.75m-.75 3h.75m-.75 3h.75m3-6h.75m-.75 3h.75m-.75 3h.75M6.75 21v-3.375c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21M3 3h12m-.75 4.5H21m-3.75 3.75h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008zm0 3h.008v.008h-.008v-.008z" />
              </svg>
              Today by Town
            </h3>
            <div v-if="townCounts.length > 0" class="space-y-2">
              <div v-for="town in townCounts.slice(0, 5)" :key="town.name" class="flex items-center justify-between">
                <span class="text-sm truncate flex-1">{{ town.name }}</span>
                <div class="flex items-center gap-2">
                  <div class="w-24 bg-base-300 rounded-full h-2">
                    <div
                      class="bg-primary h-2 rounded-full transition-all duration-500"
                      :style="{ width: `${(town.count / townCounts[0].count) * 100}%` }"
                    ></div>
                  </div>
                  <span class="text-sm font-mono font-semibold w-6 text-right">{{ town.count }}</span>
                </div>
              </div>
            </div>
            <div v-else class="text-sm text-base-content/50 text-center py-4">
              No deliveries scheduled today
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import authHeader from '../services/auth.header'
import { deliveryService } from '../services/deliveryService'
import { useCountsStore } from '../stores/counts'
import { useOilPriceStore } from '../stores/oilPrice' // [NEW]
import OilPriceTicker from '../components/OilPriceTicker.vue' // [NEW]
import { DeliveryMapItem } from '../types/models'
import "leaflet/dist/leaflet.css"
import { LMap, LTileLayer, LMarker, LPopup } from "@vue-leaflet/vue-leaflet"
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import { Line } from 'vue-chartjs'

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

// Router
const router = useRouter()

// Stores
const countsStore = useCountsStore()
const oilPriceStore = useOilPriceStore() // [NEW]

// Reactive data
const delivery_count = ref(0)
const delivery_count_delivered = ref(0)
const total_gallons_past_week = ref(0)
const total_deliveries = ref(0)
const user = ref({
  user_id: 0,
  user_name: '',
})
const employee = ref({
  id: '',
  user_id: '',
  employee_last_name: "",
  employee_first_name: "",
  employee_town: "",
  employee_address: "",
  employee_apt: "",
  employee_zip: "",
  employee_birthday: "",
  employee_phone_number: "",
  employee_start_date: "",
  employee_end_date: "",
  employee_type: '',
  employee_state: '',
})

// Map data
const mapDeliveries = ref<DeliveryMapItem[]>([])
const mapZoom = ref(10)

// Chart data
const weeklyData = ref<{ date: string; gallons: number }[]>([])

// Computed
const formattedDate = computed(() => {
  const now = new Date()
  return now.toLocaleDateString('en-US', {
    weekday: 'short',
    month: 'short',
    day: 'numeric'
  })
})

const mappedDeliveries = computed(() =>
  mapDeliveries.value.filter(d => d.latitude && d.longitude)
)

const uniqueTowns = computed(() =>
  [...new Set(mapDeliveries.value.map(d => d.town))]
)

const townCounts = computed(() => {
  const counts: Record<string, number> = {}
  mapDeliveries.value.forEach(d => {
    const town = d.town || 'Unknown'
    counts[town] = (counts[town] || 0) + 1
  })
  return Object.entries(counts)
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count)
})

const mapCenter = computed<[number, number]>(() => {
  if (mappedDeliveries.value.length === 0) {
    return [42.0654, -71.8984] // Worcester, MA area
  }
  const lats = mappedDeliveries.value.map(d => parseFloat(d.latitude!))
  const lngs = mappedDeliveries.value.map(d => parseFloat(d.longitude!))
  const avgLat = lats.reduce((a, b) => a + b, 0) / lats.length
  const avgLng = lngs.reduce((a, b) => a + b, 0) / lngs.length
  return [avgLat, avgLng]
})

const chartData = computed(() => {
  if (weeklyData.value.length === 0) return null

  return {
    labels: weeklyData.value.map(d => {
      const date = new Date(d.date)
      return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
    }),
    datasets: [{
      label: 'Gallons',
      data: weeklyData.value.map(d => d.gallons),
      borderColor: 'rgb(59, 130, 246)',
      backgroundColor: 'rgba(59, 130, 246, 0.1)',
      tension: 0.4,
      fill: true,
      pointRadius: 4,
      pointHoverRadius: 6
    }]
  }
})

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
    tooltip: {
      callbacks: {
        label: (context: { parsed: { y: number | null } }) => {
          const value = context.parsed?.y ?? 0
          return `${value.toLocaleString()} gallons`
        }
      }
    }
  },
  scales: {
    x: {
      grid: { display: false }
    },
    y: {
      beginAtZero: true,
      ticks: {
        callback: (value: string | number) => {
          if (typeof value === 'number') {
            return value >= 1000 ? `${(value / 1000).toFixed(1)}k` : value
          }
          return value
        }
      }
    }
  }
}

// Helper functions
const formatNumber = (num: number) => {
  if (num >= 1000) {
    return num.toLocaleString()
  }
  return num.toString()
}

// Lifecycle
onMounted(() => {
  userStatus()
  today_delivery_count()
  today_delivery_delivered()
  totalgallonsweek()
  totaldeliveriesweek()
  countsStore.fetchSidebarCounts()
  fetchMapDeliveries()
  fetchWeeklyChartData()
  oilPriceStore.startPolling()
})

onUnmounted(() => {
  oilPriceStore.stopPolling()
})

// API Functions
const userStatus = () => {
  const path = import.meta.env.VITE_BASE_URL + '/auth/whoami'
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      if (response.data.ok) {
        user.value = response.data.user
        employeeStatus()
      } else {
        localStorage.removeItem('user')
        router.push('/login')
      }
    })
}

const employeeStatus = () => {
  const path = import.meta.env.VITE_BASE_URL + '/employee/userid/' + user.value.user_id
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      employee.value = response.data?.employee || response.data
    })
}

const today_delivery_count = () => {
  const path = import.meta.env.VITE_BASE_URL + '/stats/delivery/count/today'
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      delivery_count.value = response.data.data
    })
}

const today_delivery_delivered = () => {
  const path = import.meta.env.VITE_BASE_URL + '/stats/delivery/count/delivered/today'
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      delivery_count_delivered.value = response.data.data
    })
}

const totalgallonsweek = () => {
  const path = import.meta.env.VITE_BASE_URL + '/stats/gallons/week'
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      total_gallons_past_week.value = response.data.total
    })
}

const totaldeliveriesweek = () => {
  const path = import.meta.env.VITE_BASE_URL + '/stats/delivery/count/week'
  axios({
    method: "get",
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      total_deliveries.value = response.data.data || response.data.total || 0
    })
    .catch(() => {
      // Fallback: use the money endpoint but only extract deliveries count
      const fallbackPath = import.meta.env.VITE_BASE_URL + '/money/profit/week'
      axios({
        method: "get",
        url: fallbackPath,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          total_deliveries.value = response.data.total_deliveries || 0
        })
    })
}

const fetchMapDeliveries = async () => {
  try {
    const today = new Date().toISOString().split('T')[0]
    const response = await deliveryService.getForMap(today)
    if (response.data.ok) {
      mapDeliveries.value = response.data.deliveries || []
    }
  } catch (err) {
    console.error('Error fetching map deliveries:', err)
  }
}

const fetchWeeklyChartData = async () => {
  try {
    const end = new Date()
    const start = new Date()
    start.setMonth(start.getMonth() - 4)

    const toLocalDateStr = (d: Date) =>
      `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`

    // Collect all daily points into a map keyed by date string.
    // The backend replaces the year in start/end with the requested year, so we must
    // never pass a cross-year range — split at Dec 31 / Jan 1 if needed.
    const dailyMap = new Map<string, number>()

    const fetchRange = async (rangeStart: Date, rangeEnd: Date) => {
      const yr = rangeStart.getFullYear()
      const params = new URLSearchParams({
        start_date: toLocalDateStr(rangeStart),
        end_date: toLocalDateStr(rangeEnd),
        years: yr.toString()
      })
      const resp = await axios({
        method: 'get',
        url: import.meta.env.VITE_BASE_URL + `/stats/gallons/daily?${params}`,
        withCredentials: true,
        headers: authHeader(),
      })
      if (resp.data.ok && resp.data.years?.length > 0) {
        for (const pt of resp.data.years[0].data as { date: string; gallons: number }[]) {
          dailyMap.set(pt.date, (dailyMap.get(pt.date) || 0) + pt.gallons)
        }
      }
    }

    if (start.getFullYear() === end.getFullYear()) {
      await fetchRange(start, end)
    } else {
      // Split at year boundary to keep each call within a single year
      await Promise.all([
        fetchRange(start, new Date(start.getFullYear(), 11, 31)),
        fetchRange(new Date(end.getFullYear(), 0, 1), end),
      ])
    }

    // Aggregate daily data into weekly buckets, each keyed by its Saturday
    const weekMap = new Map<string, number>()
    for (const [dateStr, gallons] of dailyMap.entries()) {
      const d = new Date(dateStr + 'T12:00:00') // noon avoids DST/timezone edge cases
      const daysToSat = (6 - d.getDay() + 7) % 7
      const sat = new Date(d)
      sat.setDate(d.getDate() + daysToSat)
      const satKey = toLocalDateStr(sat)
      weekMap.set(satKey, (weekMap.get(satKey) || 0) + gallons)
    }

    // Generate every Saturday in the 4-month window
    const saturdays: string[] = []
    const cur = new Date(start)
    cur.setHours(12, 0, 0, 0)
    cur.setDate(cur.getDate() + (6 - cur.getDay() + 7) % 7)
    const endNoon = new Date(end)
    endNoon.setHours(12, 0, 0, 0)
    while (cur <= endNoon) {
      saturdays.push(toLocalDateStr(cur))
      cur.setDate(cur.getDate() + 7)
    }

    weeklyData.value = saturdays.map(sat => ({
      date: sat,
      gallons: weekMap.get(sat) || 0
    }))
  } catch (err) {
    console.error('Error fetching chart data:', err)
  }
}
</script>

<style scoped>
.animate-fade-in {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  @apply bg-gradient-to-br from-neutral to-neutral/80 rounded-xl p-4 shadow-md hover:shadow-lg transition-all duration-300;
}

.card-glass {
  @apply bg-gradient-to-br from-neutral/90 to-neutral/70 backdrop-blur-sm rounded-xl shadow-lg border border-base-content/5;
}

.quick-action-btn {
  @apply flex flex-row items-center gap-2 p-3 rounded-lg bg-base-200/50 hover:bg-primary/10 hover:text-primary transition-all duration-200 text-sm font-medium;
}

@media (min-width: 768px) {
  .quick-action-btn {
    @apply flex-col justify-center gap-1 text-xs;
  }
}

/* Leaflet fixes */
:deep(.leaflet-container) {
  z-index: 0;
  background: hsl(var(--b3));
}

:deep(.leaflet-popup-content-wrapper) {
  background: hsl(var(--b1));
  color: hsl(var(--bc));
}

:deep(.leaflet-popup-tip) {
  background: hsl(var(--b1));
}
</style>
