<!-- src/pages/delivery/viewstatus/todaysdeliveries.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'delivery' }">Delivery</router-link></li>
          <li>Today's Deliveries</li>
        </ul>
      </div>

      <!-- Page Header with Stats -->
      <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mt-4 mb-6">
        <div>
          <h1 class="text-2xl md:text-3xl font-bold flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-primary/60 flex items-center justify-center shadow-lg">
              <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-content">
                <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>
            Today's Deliveries
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">Out for delivery right now</p>
        </div>

        <!-- Quick Stats -->
        <div class="flex flex-wrap gap-3">
          <div class="stat-pill">
            <span class="stat-pill-value">{{ deliveries.length }}</span>
            <span class="stat-pill-label">Deliveries</span>
          </div>
          <div class="stat-pill stat-pill-success">
            <span class="stat-pill-value">{{ grand_total.toLocaleString() }}</span>
            <span class="stat-pill-label">Total Gallons</span>
          </div>
          <div class="stat-pill stat-pill-info">
            <span class="stat-pill-value">{{ totals.length }}</span>
            <span class="stat-pill-label">Towns</span>
          </div>
        </div>
      </div>

      <!-- Town Breakdown Bar -->
      <div v-if="totals.length > 0" class="mb-6 overflow-x-auto">
        <div class="flex gap-2 pb-2">
          <button
            v-for="total in totals"
            :key="total.town"
            @click="toggleTownFilter(total.town)"
            class="town-chip"
            :class="{ 'town-chip-active': filterTown === total.town }"
          >
            <span class="font-semibold">{{ total.town }}</span>
            <span class="town-chip-count">{{ total.gallons }}</span>
          </button>
          <button
            v-if="filterTown"
            @click="filterTown = ''"
            class="town-chip town-chip-clear"
          >
            <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 18L18 6M6 6l12 12" />
            </svg>
            Clear Filter
          </button>
        </div>
      </div>

      <!-- Search & Actions Bar -->
      <div class="flex flex-col sm:flex-row gap-3 mb-4">
        <div class="relative flex-1 max-w-md">
          <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 text-base-content/40">
              <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
            </svg>
          </div>
          <input
            type="text"
            v-model="searchQuery"
            placeholder="Search by name, address, or delivery #..."
            class="input input-bordered w-full pl-10 bg-base-200/50 focus:bg-base-100"
          />
        </div>
        <div class="flex gap-2">
          <router-link :to="{ name: 'deliveryMap' }" class="btn btn-outline btn-info 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="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>
            View Map
          </router-link>
        </div>
      </div>

      <!-- Main Table Card -->
      <div class="modern-table-card">
        <!-- Loading State -->
        <div v-if="loading" class="flex items-center justify-center py-20">
          <span class="loading loading-spinner loading-lg text-primary"></span>
        </div>

        <!-- Empty State -->
        <div v-else-if="filteredDeliveries.length === 0" class="text-center py-16">
          <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-base-200 flex items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-8 h-8 text-base-content/40">
              <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>
          <h3 class="text-lg font-semibold mb-1">No deliveries found</h3>
          <p class="text-base-content/60">{{ searchQuery || filterTown ? 'Try adjusting your search or filter' : 'No deliveries are out for delivery today' }}</p>
        </div>

        <!-- DESKTOP TABLE -->
        <div v-else class="hidden xl:block overflow-x-auto">
          <table class="modern-table">
            <thead>
              <tr>
                <th class="w-24">
                  <button @click="toggleSort('id')" class="sort-header">
                    <span>#</span>
                    <svg v-if="sortBy === 'id'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4" :class="{ 'rotate-180': sortDir === 'asc' }">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                    </svg>
                  </button>
                </th>
                <th>Customer</th>
                <th class="w-32">Status</th>
                <th>Address</th>

                <th class="w-28">
                  <button @click="toggleSort('gallons')" class="sort-header">
                    <span>Gallons</span>
                    <svg v-if="sortBy === 'gallons'" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4" :class="{ 'rotate-180': sortDir === 'asc' }">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                    </svg>
                  </button>
                </th>
                <th class="w-72 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="oil in filteredDeliveries"
                :key="oil.id"
                class="table-row-hover"
                :class="{ 'row-urgent': oil.emergency, 'row-prime': oil.prime && !oil.emergency, 'row-sameday': oil.same_day && !oil.prime && !oil.emergency }"
              >
                <td>
                  <span class="font-mono text-sm font-semibold text-base-content/70">#{{ oil.id }}</span>
                </td>
                <td>
                  <router-link
                    v-if="oil.customer_id"
                    :to="{ name: 'customerProfile', params: { id: oil.customer_id } }"
                    class="group"
                  >
                    <div class="font-bold text-base group-hover:text-primary transition-colors">
                      {{ oil.customer_name }}
                    </div>
                    <div class="text-xs font-mono opacity-60 flex items-center gap-1">
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                      </svg>
                      #{{ oil.id }}
                    </div>
                  </router-link>
                  <div v-else>
                    <p class="font-bold text-success">{{ oil.customer_name }}</p>
                    <div class="text-xs font-mono opacity-60">#{{ oil.id }}</div>
                  </div>
                  <!-- Special Tags -->
                  <div class="flex gap-1 mt-1">
                    <span v-if="oil.emergency" class="special-tag tag-emergency">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
                        <path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                      </svg>
                      EMERGENCY
                    </span>
                    <span v-if="oil.prime" class="special-tag tag-prime">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
                        <path fill-rule="evenodd" d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z" clip-rule="evenodd" />
                      </svg>
                      PRIME
                    </span>
                    <span v-if="oil.same_day" class="special-tag tag-sameday">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm.75-13a.75.75 0 00-1.5 0v5c0 .414.336.75.75.75h4a.75.75 0 000-1.5h-3.25V5z" clip-rule="evenodd" />
                      </svg>
                      SAME DAY
                    </span>
                  </div>
                </td>
                <td>
                  <div class="status-badge" :class="getStatusClass(oil.delivery_status)">
                    <span class="status-dot"></span>
                    {{ getStatusText(oil.delivery_status) }}
                  </div>
                </td>
                <td>
                  <div class="flex flex-col">
                    <span class="font-medium text-sm">{{ oil.customer_address }}</span>
                    <div class="flex items-center gap-1">
                      <span class="text-xs opacity-70">{{ oil.customer_town }}, {{ getStateAbbr(oil.customer_state) }} {{ formatZip(oil.customer_zip) }}</span>
                      <a :href="`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(`${oil.customer_address}, ${oil.customer_town}, ${getStateAbbr(oil.customer_state)} ${formatZip(oil.customer_zip)}`)}`"
                        target="_blank"
                        class="btn btn-xs btn-circle btn-ghost text-base-content/60 hover:text-primary hover:bg-primary/10"
                        title="View on Google Maps">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                          <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>
                      </a>
                    </div>
                  </div>
                </td>
                <td>
                  <div v-if="oil.customer_asked_for_fill == 1" class="gallons-badge gallons-fill">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4">
                      <path d="M6.3 2.841A1.5 1.5 0 004 4.11V15.89a1.5 1.5 0 002.3 1.269l9.344-5.89a1.5 1.5 0 000-2.538L6.3 2.84z" />
                    </svg>
                    FILL
                  </div>
                  <div v-else class="text-success font-mono font-bold">
                    {{ oil.gallons_ordered }} gal
                  </div>
                </td>
                <td>
                  <div class="flex items-center justify-end gap-1">
                    <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-xs btn-neutral btn-outline" title="View">
                      View
                    </router-link>
                    <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-xs btn-info btn-outline" title="Edit">
                      Edit
                    </router-link>
                    <router-link v-if="oil.delivery_status != 10" :to="{ name: 'finalizeTicket', params: { id: oil.id } }" class="btn btn-xs btn-accent btn-outline" title="Finalize">
                      Finalize
                    </router-link>
                    <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-xs btn-success btn-outline" title="Print">
                      Print
                    </router-link>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- MOBILE CARDS -->
        <div class="xl:hidden space-y-3 p-4">
            <!-- Mobile Card -->
            <div
              v-for="oil in filteredDeliveries"
              :key="oil.id"
              class="mobile-card"
              :class="{ 
                'mobile-card-urgent': oil.emergency, 
                'mobile-card-prime': oil.prime && !oil.emergency,
                'mobile-card-sameday': oil.same_day && !oil.prime && !oil.emergency
              }"
            >
            <!-- Card Header -->
            <div class="flex items-start justify-between mb-3">
              <div class="flex items-center gap-3">
                <div class="avatar placeholder">
                  <div class="bg-gradient-to-br from-primary/20 to-primary/5 text-primary rounded-lg w-12 h-12">
                    <span class="text-base font-bold">{{ getInitials(oil.customer_name) }}</span>
                  </div>
                </div>
                <div>
                  <router-link
                    v-if="oil.customer_id"
                    :to="{ name: 'customerProfile', params: { id: oil.customer_id } }"
                    class="font-semibold text-lg hover:text-primary"
                  >
                    {{ oil.customer_name }}
                  </router-link>
                  <span v-else class="font-semibold text-lg">{{ oil.customer_name }}</span>
                  <p class="text-sm text-base-content/50">#{{ oil.id }}</p>
                </div>
              </div>
              <div class="status-badge" :class="getStatusClass(oil.delivery_status)">
                <span class="status-dot"></span>
                {{ getStatusText(oil.delivery_status) }}
              </div>
            </div>

            <!-- Special Tags -->
            <div v-if="oil.emergency || oil.prime || oil.same_day" class="flex gap-2 mb-3">
              <span v-if="oil.emergency" class="special-tag tag-emergency">EMERGENCY</span>
              <span v-if="oil.prime" class="special-tag tag-prime">PRIME</span>
              <span v-if="oil.same_day" class="special-tag tag-sameday">SAME DAY</span>
            </div>

            <!-- Details Grid -->
            <div class="grid grid-cols-2 gap-3 mb-4 text-sm">
              <div>
                <span class="text-base-content/50">Location</span>
                <p class="font-medium">{{ oil.customer_town }}</p>
                <p class="text-base-content/60 text-xs">{{ oil.customer_address }}</p>
              </div>
              <div>
                <span class="text-base-content/50">Gallons</span>
                <p class="font-bold text-success">
                  <span v-if="oil.customer_asked_for_fill == 1" class="badge badge-info">FILL</span>
                  <span v-else>{{ oil.gallons_ordered }} gal</span>
                </p>
              </div>
            </div>

            <!-- Actions -->
            <div class="flex gap-2 pt-3 border-t border-base-content/10">
              <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-sm btn-neutral btn-outline flex-1">
                View
              </router-link>
              <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-sm btn-info btn-outline flex-1">
                Edit
              </router-link>
              <router-link v-if="oil.delivery_status != 10" :to="{ name: 'finalizeTicket', params: { id: oil.id } }" class="btn btn-sm btn-accent btn-outline flex-1">
                Finalize
              </router-link>
              <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-sm btn-success btn-outline">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0110.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0l.229 2.523a1.125 1.125 0 01-1.12 1.227H7.231c-.662 0-1.18-.568-1.12-1.227L6.34 18m11.318 0h1.091A2.25 2.25 0 0021 15.75V9.456c0-1.081-.768-2.015-1.837-2.175a48.055 48.055 0 00-1.913-.247M6.34 18H5.25A2.25 2.25 0 013 15.75V9.456c0-1.081.768-2.015 1.837-2.175a48.041 48.041 0 011.913-.247m10.5 0a48.536 48.536 0 00-10.5 0m10.5 0V3.375c0-.621-.504-1.125-1.125-1.125h-8.25c-.621 0-1.125.504-1.125 1.125v3.659M18 10.5h.008v.008H18V10.5zm-3 0h.008v.008H15V10.5z" />
                </svg>
              </router-link>
            </div>
          </div>
        </div>

        <!-- Pagination -->
        <div v-if="filteredDeliveries.length > 0" class="p-4 border-t border-base-content/10">
          <div class="flex items-center justify-between">
            <span class="text-sm text-base-content/60">
              Showing {{ filteredDeliveries.length }} of {{ deliveries.length }} deliveries
            </span>
            <pagination
              @paginate="getPage"
              :records="recordsLength"
              v-model="page"
              :per-page="50"
              :options="options"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, markRaw } from 'vue'
import { deliveryService } from '../../../services/deliveryService'
import authService from '../../../services/authService'
import { Delivery } from '../../../types/models'
import PaginationComp from '../../../components/pagination.vue'
import { notify } from "@kyvg/vue3-notification"

interface TownTotal {
  town: string;
  gallons: number;
}

// Reactive data
const user = ref(null)
const deliveries = ref<Delivery[]>([])
const totals = ref<TownTotal[]>([])
const grand_total = ref(0)
const page = ref(1)
const perPage = ref(50)
const recordsLength = ref(0)
const loading = ref(true)
const searchQuery = ref('')
const filterTown = ref('')
const sortBy = ref<'id' | 'gallons'>('id')
const sortDir = ref<'asc' | 'desc'>('desc')
const options = ref({
  edgeNavigation: false,
  format: false,
  template: markRaw(PaginationComp)
})

// Computed
const filteredDeliveries = computed(() => {
  let result = [...deliveries.value]

  // Filter by town
  if (filterTown.value) {
    result = result.filter(d => d.customer_town === filterTown.value)
  }

  // Filter by search
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(d =>
      d.customer_name?.toLowerCase().includes(query) ||
      d.customer_address?.toLowerCase().includes(query) ||
      d.customer_town?.toLowerCase().includes(query) ||
      d.id?.toString().includes(query)
    )
  }

  // Sort
  result.sort((a, b) => {
    let aVal: number, bVal: number
    if (sortBy.value === 'id') {
      aVal = a.id
      bVal = b.id
    } else {
      aVal = a.customer_asked_for_fill ? 9999 : (a.gallons_ordered || 0)
      bVal = b.customer_asked_for_fill ? 9999 : (b.gallons_ordered || 0)
    }
    return sortDir.value === 'desc' ? bVal - aVal : aVal - bVal
  })

  return result
})

// Functions
const getInitials = (name: string) => {
  if (!name) return '?'
  const parts = name.split(' ')
  return parts.length > 1
    ? `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase()
    : name.substring(0, 2).toUpperCase()
}

const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-waiting'
    case 1: return 'status-cancelled'
    case 2: return 'status-outfordelivery'
    case 5: return 'status-issue'
    case 10: return 'status-finalized'
    default: return 'status-default'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0: return 'Waiting'
    case 1: return 'Cancelled'
    case 2: return 'Out for Delivery'
    case 3: return 'Tomorrow'
    case 4: return 'Partial'
    case 5: return 'Issue'
    case 10: return 'Finalized'
    default: return 'Unknown'
  }
}

const toggleSort = (field: 'id' | 'gallons') => {
  if (sortBy.value === field) {
    sortDir.value = sortDir.value === 'desc' ? 'asc' : 'desc'
  } else {
    sortBy.value = field
    sortDir.value = 'desc'
  }
}

const toggleTownFilter = (town: string) => {
  filterTown.value = filterTown.value === town ? '' : town
}

const getPage = (pageVal: number) => {
  deliveries.value = []
  loading.value = true
  get_oil_orders(pageVal)
}

const userStatus = async () => {
  try {
    const response = await authService.whoami()
    if (response.data.ok) {
      user.value = response.data.user
    }
  } catch (error) {
    user.value = null
  }
}

const get_oil_orders = async (pageVal: number) => {
  try {
    const response = await deliveryService.getOutForDelivery(pageVal)
    const data = response.data?.deliveries || []
    deliveries.value = Array.isArray(data) ? data : []
  } catch (error) {
    console.error('Error fetching out for delivery:', error)
    deliveries.value = []
  } finally {
    loading.value = false
  }
}

const get_totals = async () => {
  try {
    const response = await deliveryService.getTodayTotals()
    totals.value = response.data.totals || []
    grand_total.value = response.data.grand_total || 0
  } catch (error) {
    console.error('Error fetching totals:', error)
    totals.value = []
    grand_total.value = 0
  }
}

// State abbreviation mapping
const STATE_ABBR_MAP: { [key: number]: string } = {
  0: 'MA', 1: 'RI', 2: 'NH', 3: 'ME', 4: 'VT', 5: 'CT', 6: 'NY', 7: 'NJ',
  8: 'PA', 9: 'DE', 10: 'MD', 11: 'DC', 12: 'VA', 13: 'WV', 14: 'NC',
  15: 'SC', 16: 'GA', 17: 'FL', 18: 'AL', 19: 'MS', 20: 'TN', 21: 'KY',
  22: 'OH', 23: 'IN', 24: 'MI', 25: 'IL', 26: 'WI', 27: 'MN', 28: 'IA',
  29: 'MO', 30: 'AR', 31: 'LA', 32: 'TX', 33: 'OK', 34: 'KS', 35: 'NE',
  36: 'SD', 37: 'ND', 38: 'MT', 39: 'WY', 40: 'CO', 41: 'NM', 42: 'AZ',
  43: 'UT', 44: 'NV', 45: 'ID', 46: 'WA', 47: 'OR', 48: 'CA', 49: 'AK', 50: 'HI'
}

const getStateAbbr = (stateId: number | string): string => {
  const id = typeof stateId === 'string' ? parseInt(stateId) : stateId;
  return STATE_ABBR_MAP[id] || 'MA';
}

const formatZip = (zip: string | number): string => String(zip || '').trim().padStart(5, '0');

// Lifecycle
onMounted(() => {
  userStatus()
  getPage(page.value)
  get_totals()
})
</script>

<style scoped>
/* Stat Pills */
.stat-pill {
  @apply flex items-center gap-2 px-4 py-2 rounded-xl bg-base-200/80 border border-base-content/5;
}
.stat-pill-value {
  @apply text-xl font-bold;
}
.stat-pill-label {
  @apply text-xs text-base-content/60 uppercase tracking-wider;
}
.stat-pill-success {
  @apply bg-success/10 border-success/20;
}
.stat-pill-success .stat-pill-value {
  @apply text-success;
}
.stat-pill-info {
  @apply bg-info/10 border-info/20;
}
.stat-pill-info .stat-pill-value {
  @apply text-info;
}

/* Town Chips */
.town-chip {
  @apply flex items-center gap-2 px-3 py-1.5 rounded-full bg-base-200 hover:bg-base-300 transition-all text-sm whitespace-nowrap cursor-pointer;
}
.town-chip-count {
  @apply px-2 py-0.5 rounded-full bg-base-content/10 text-xs font-mono;
}
.town-chip-active {
  @apply bg-primary text-primary-content;
}
.town-chip-active .town-chip-count {
  @apply bg-primary-content/20;
}
.town-chip-clear {
  @apply bg-error/10 text-error hover:bg-error/20;
}

/* Modern Table Card */
.modern-table-card {
  @apply bg-gradient-to-br from-neutral to-neutral/80 rounded-2xl shadow-xl border border-base-content/5 overflow-hidden;
}

/* Modern Table */
.modern-table {
  @apply w-full;
}
.modern-table thead {
  @apply bg-base-content/5;
}
.modern-table th {
  @apply px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-base-content/60;
}
.modern-table td {
  @apply px-4 py-4;
}
.modern-table tbody tr {
  @apply border-t border-base-content/5;
}

/* Sort Header */
.sort-header {
  @apply flex items-center gap-1 hover:text-primary transition-colors cursor-pointer;
}

/* Table Row Hover */
.table-row-hover {
  @apply transition-all duration-200;
}
.table-row-hover:hover {
  @apply bg-primary/5;
}

/* Row urgency highlighting */
.row-urgent {
  @apply bg-error/5 border-l-4 border-l-error;
}
.row-urgent:hover {
  @apply bg-error/10;
}
.row-prime {
  @apply bg-warning/5 border-l-4 border-l-warning;
}
.row-prime:hover {
  @apply bg-warning/10;
}
.row-sameday {
  @apply bg-info/5 border-l-4 border-l-info;
}
.row-sameday:hover {
  @apply bg-info/10;
}

/* Status Badge */
.status-badge {
  @apply inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium;
}
.status-dot {
  @apply w-1.5 h-1.5 rounded-full;
}
.status-waiting {
  @apply bg-warning/10 text-warning;
}
.status-waiting .status-dot {
  @apply bg-warning animate-pulse;
}
.status-outfordelivery {
  @apply bg-info/10 text-info;
}
.status-outfordelivery .status-dot {
  @apply bg-info animate-pulse;
}
.status-finalized {
  @apply bg-success/10 text-success;
}
.status-finalized .status-dot {
  @apply bg-success;
}
.status-cancelled, .status-issue {
  @apply bg-error/10 text-error;
}
.status-cancelled .status-dot, .status-issue .status-dot {
  @apply bg-error;
}
.status-default {
  @apply bg-base-content/10 text-base-content/60;
}
.status-default .status-dot {
  @apply bg-base-content/40;
}

/* Special Tags */
.special-tag {
  @apply inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide;
}
.tag-emergency {
  @apply bg-error text-error-content animate-pulse;
}
.tag-prime {
  @apply bg-warning text-warning-content;
}
.tag-sameday {
  @apply bg-info text-info-content;
}

/* Gallons Badge */
.gallons-badge {
  @apply text-success font-mono font-bold;
}
.gallons-fill {
  @apply bg-info/10 text-info border-info/20;
}

/* Action Buttons */
.action-btn {
  @apply p-2 rounded-lg hover:bg-base-content/10 transition-colors text-base-content/60 hover:text-base-content;
}
.action-btn-secondary {
  @apply hover:bg-secondary/20 hover:text-secondary;
}
.action-btn-accent {
  @apply hover:bg-accent/20 hover:text-accent;
}
.action-btn-success {
  @apply hover:bg-success/20 hover:text-success;
}

/* Mobile Cards */
.mobile-card {
  @apply bg-base-100/50 backdrop-blur-sm rounded-xl p-4 shadow-sm border border-base-content/5;
}
.mobile-card-urgent {
  @apply border-l-4 border-l-error bg-error/5;
}
.mobile-card-prime {
  @apply border-l-4 border-l-warning bg-warning/5;
}
.mobile-card-sameday {
  @apply border-l-4 border-l-info bg-info/5;
}
</style>
