<!-- headerauth.vue -->
<template>
  <!-- Main header container, contains both rows -->
  <header class="sticky top-0 z-50 bg-base-200 shadow-sm">

    <!-- Row 1: The primary navbar -->
    <div class="navbar px-4">

      <!-- Navbar Start: Logo & Mobile Menu Toggle -->
      <div class="navbar-start">
        <label for="my-drawer-2" class="btn btn-ghost btn-circle drawer-button lg:hidden">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
            <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
          </svg>
        </label>

        <!-- Oil Price Dropdown (replaces date display) -->
        <div class="dropdown dropdown-hover hidden xl:block">
          <label tabindex="0" class="btn btn-ghost gap-2 hover:bg-warning/10 transition-colors">
            <div class="flex items-center gap-2">
              <div class="w-10 h-10 rounded-full bg-gradient-to-br from-warning to-warning/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-warning-content">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div class="flex flex-col items-start">
                <span class="text-xs text-base-content/60 font-medium">Oil Price</span>
                <span class="text-xl font-bold text-warning" v-if="oilPrice.price_for_customer !== null">
                  ${{ formatPrice(oilPrice.price_for_customer) }}<span class="text-xs font-normal text-base-content/60">/gal</span>
                </span>
                <span v-else class="loading loading-dots loading-xs"></span>
              </div>
              <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-base-content/40">
                <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
              </svg>
            </div>
          </label>
          <div tabindex="0" class="dropdown-content z-[60] mt-2 p-0 shadow-2xl bg-base-100 rounded-xl w-80 border border-base-300">
            <!-- Header with date -->
            <div class="bg-gradient-to-r from-warning/20 to-warning/5 p-4 rounded-t-xl border-b border-base-300">
              <div class="flex items-center justify-between">
                <div>
                  <p class="text-xs text-base-content/60 uppercase tracking-wider font-medium">Today's Pricing</p>
                  <p class="text-sm font-semibold">{{ dayOfWeek }}, {{ currentDate }}</p>
                </div>
                <div class="badge badge-warning badge-sm">Live</div>
              </div>
            </div>

            <!-- Oil Pricing Section -->
            <div class="p-4">
              <h4 class="text-xs uppercase tracking-wider text-base-content/50 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="1.5" stroke="currentColor" class="w-4 h-4">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48z" />
                </svg>
                Oil Delivery
              </h4>
              <div class="space-y-2">
                <div class="flex justify-between items-center p-2 rounded-lg bg-base-200/50 hover:bg-base-200 transition-colors">
                  <span class="text-sm font-medium">Regular Delivery</span>
                  <span class="font-mono font-bold text-lg text-success">${{ formatPrice(oilPrice.price_for_customer) }}</span>
                </div>
                <!-- Delivery Service Pricing in a compact table -->
                <div class="mt-3">
                  <div class="overflow-x-auto">
                    <table class="table table-xs w-full">
                      <thead>
                        <tr>
                          <th class="px-1 py-1 text-xs opacity-60">Type</th>
                          <th class="px-1 py-1 text-center text-xs opacity-60">1</th>
                          <th class="px-1 py-1 text-center text-xs opacity-60">2</th>
                          <th class="px-1 py-1 text-center text-xs opacity-60">3</th>
                          <th class="px-1 py-1 text-center text-xs opacity-60">4</th>
                          <th class="px-1 py-1 text-center text-xs opacity-60">5</th>
                        </tr>
                      </thead>
                      <tbody>
                        <!-- Same Day-->
                        <tr class="hover">
                          <td class="px-1 py-1 font-semibold text-xs whitespace-nowrap">Same Day</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_same_day_tier1 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_same_day_tier2 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_same_day_tier3 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_same_day_tier4 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_same_day_tier5 || 0) }}</td>
                        </tr>
                         <!-- Prime-->
                        <tr class="hover">
                          <td class="px-1 py-1 font-semibold text-xs whitespace-nowrap">Prime</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_prime_tier1 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_prime_tier2 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_prime_tier3 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_prime_tier4 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_prime_tier5 || 0) }}</td>
                        </tr>
                        <!-- Emergency -->
                        <tr class="hover text-error">
                          <td class="px-1 py-1 font-semibold text-xs whitespace-nowrap">Emergency</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_emergency_tier1 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_emergency_tier2 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_emergency_tier3 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_emergency_tier4 || 0) }}</td>
                          <td class="px-1 py-1 text-center text-xs font-mono">${{ Math.round(oilPrice.price_emergency_tier5 || 0) }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>

            <div class="divider my-0 px-4"></div>

            <!-- Service Pricing Section -->
            <div class="p-4">
              <h4 class="text-xs uppercase tracking-wider text-base-content/50 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="1.5" stroke="currentColor" class="w-4 h-4">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M11.42 15.17L17.25 21A2.652 2.652 0 0021 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 11-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 004.486-6.336l-3.276 3.277a3.004 3.004 0 01-2.25-2.25l3.276-3.276a4.5 4.5 0 00-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437l1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008z" />
                </svg>
                Service Calls
              </h4>
              <div class="space-y-2">
                <div class="flex justify-between items-center p-2 rounded-lg bg-base-200/50 hover:bg-base-200 transition-colors">
                  <span class="text-sm font-medium">Per Hour</span>
                  <span class="font-mono font-bold text-lg text-info">$125</span>
                </div>
                <div class="flex justify-between items-center p-2 rounded-lg hover:bg-base-200/50 transition-colors">
                  <span class="text-sm text-base-content/70">Emergency</span>
                  <span class="font-mono font-semibold text-error">$200</span>
                </div>
              </div>
            </div>

            <!-- Footer with supplier cost (admin only) -->
            <div v-if="user.user_admin === 0 && oilPrice.price_from_supplier" class="bg-base-200/30 p-3 rounded-b-xl border-t border-base-300">
              <div class="flex justify-between items-center text-xs text-base-content/50">
                <span>Supplier Cost</span>
                <span class="font-mono">${{ formatPrice(oilPrice.price_from_supplier) }}/gal</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Navbar Center: Search Bar (tablet+) -->
      <div class="navbar-center hidden md:flex min-w-[24rem]">
         <div class="relative w-full max-w-xl">
            <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/50">
                <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
              id="customer-search-input-desktop"
              type="text"
              placeholder="Search customers..."
              v-model="searchStore.searchTerm"
              class="input input-bordered w-full pl-10"
              @input="searchStore.debouncedSearch"
            />
          </div>
      </div>

      <!-- Navbar End: Action Buttons -->
      <div class="navbar-end gap-2">

        <!-- Action Buttons Wrapper -->
        <!-- This group is set to not shrink, keeping it always visible. -->
        <div class="flex-shrink-0 flex items-center gap-2">
          
          <!-- VOIP Routing Dropdown (visible tablet+) -->
          <div class="dropdown dropdown-end hidden xl:flex">
            <label tabindex="0" class="btn btn-ghost gap-2">
               <svg xmlns="http://www.w.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 text-success">
                <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 002.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 01-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 00-1.091-.852H4.5A2.25 2.25 0 002.25 6.75z" />
              </svg>
              <span class="font-semibold whitespace-nowrap">{{ currentPhone || 'Routing' }}</span>
            </label>
            <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52 mt-4">
              <li v-for="option in routingOptions" :key="option.value">
                <a @click.prevent="showConfirmRoute(option)" href="#">
                  <span class="font-mono">{{ option.label }}</span>
                </a>
              </li>
            </ul>
          </div>
        
          <!-- Create Customer Button (visible tablet+) -->
          <router-link :to="{ name: 'customerCreate' }" class="btn btn-success btn-sm hidden md:inline-flex">
            New Customer
          </router-link>

          <!-- User Dropdown (Always visible) -->
          <div v-if="user.user_id" class="dropdown dropdown-end">
            <label tabindex="0" class="btn btn-ghost btn-circle avatar">
              <div class="w-10 rounded-full bg-neutral text-neutral-content flex items-center justify-center">
                <span class="text-lg font-bold">{{ userInitials }}</span>
              </div>
            </label>
            <ul tabindex="0" class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52">
              <li class="p-2 font-semibold">{{ user.user_name }}</li>
              <div class="divider my-0"></div>
              <li v-if="user && user.user_id"><router-link :to="{ name: 'employeeProfile', params: { id: user.user_id } }">Profile</router-link></li>
              <li><router-link :to="{ name: 'changePassword' }">Change Password</router-link></li>
              <div class="divider my-0"></div>
              <li class="menu-title text-xs opacity-60">Theme</li>
              <li v-for="theme in AVAILABLE_THEMES" :key="theme.name">
                <a @click="themeStore.setTheme(theme.name)" :class="{ 'bg-base-200': themeStore.currentTheme === theme.name }">
                  <span class="w-4 h-4 rounded-full border border-base-content/20" :style="{ background: theme.preview }"></span>
                  {{ theme.label }}
                </a>
              </li>
              <div class="divider my-0"></div>
              <li><a @click="logout">Logout</a></li>
            </ul>
          </div>
          <div v-else class="skeleton w-10 h-10 rounded-full"></div>
        </div>
      </div>
    </div>

    <!-- Row 2: MOBILE SEARCH BAR -->
    <!-- This full-width search bar only appears on screens smaller than md -->
    <div class="w-full px-4 pb-3 md:hidden">
      <div class="relative w-full">
        <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/50">
            <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
          id="customer-search-input-mobile"
          type="text"
          placeholder="Search customers..."
          v-model="searchStore.searchTerm"
          class="input input-bordered w-full pl-10"
          @input="searchStore.debouncedSearch"
        />
      </div>
    </div>
    <!-- Row 3: Stock Ticker -->
    <div v-if="settingsStore.settings.show_ticker" class="w-full bg-base-300/50 border-b border-base-200 py-1 overflow-hidden">
       <GlobalMarketTicker />
    </div>

  </header>
  
  <!-- MODAL SECTION REMAINS UNCHANGED -->
  <!-- ... (paste your existing modals here) ... -->
  
  <div class="modal" :class="{ 'modal-open': isRouteModalVisible }">
    <div class="modal-box">
      <div v-if="routeModalMode === 'confirm'">
        <h3 class="font-bold text-lg">Confirm Routing Change</h3>
        <p class="py-4">FROM: {{ currentPhone }} → TO: {{ selectedOption?.label }}</p>
        <div class="modal-action">
          <button @click="proceedRoute" class="btn btn-success">Confirm</button>
          <button @click="closeRouteModal" class="btn btn-error">Cancel</button>
        </div>
      </div>
      <div v-else-if="routeModalMode === 'loading'">
        <h3 class="font-bold text-lg">Switching Route</h3>
        <div class="py-4 text-center">
          <p class="text-lg mb-3">Switching phone routing from {{ currentPhone }} to {{ selectedOption?.label }}...</p>
          <div class="loading loading-spinner loading-lg text-primary mb-3"></div>
          <p class="text-sm text-gray-600">Please wait while we update the routing.</p>
        </div>
      </div>
      <div v-else-if="routeModalMode === 'result'">
        <h3 class="font-bold text-lg">Route Change Result</h3>
        <div class="py-4">
          <div v-if="routeResponse && !routeResponse.error" class="alert alert-success mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>Routing change completed successfully.</span>
          </div>
          <div v-else-if="routeResponse && routeResponse.error" class="alert alert-error mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>Error occurred during routing change.</span>
          </div>
          <div v-if="routeResponse.message || routeResponse.status" class="bg-base-200 p-3 rounded">
            <p>{{ routeResponse.message || routeResponse.status }}</p>
          </div>
          <div v-else class="bg-base-200 p-3 rounded">
            <p>Response received successfully.</p>
          </div>
        </div>
        <div class="modal-action">
          <button @click="closeRouteModal" class="btn">Close</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal" :class="{ 'modal-open': isTestModalVisible }">
    <div class="modal-box">
      <h3 class="font-bold text-lg">DID Test Result</h3>
      <div class="py-4">
        <div v-if="isTestLoading" class="text-center">
          <span class="text-lg mb-3">Testing DID connection...</span>
          <div class="loading loading-spinner loading-lg text-primary mb-3"></div>
          <p class="text-sm text-gray-600">Please wait while we fetch DID information.</p>
        </div>
        <div v-else-if="testResponse">
          <div v-if="testResponse.status === 'success' && testResponse.dids && testResponse.dids.length > 0" class="space-y-4">
            <div class="alert alert-success">
              <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>DID Test Successful! Connection is working.</span>
            </div>
            <div v-for="did in testResponse.dids" :key="did.did" class="border rounded-lg p-3 bg-base-100">
              <h4 class="font-semibold mb-2">DID: {{ did.did }}</h4>
              <div class="grid grid-cols-2 gap-2 text-sm">
                <div><strong>Description:</strong> {{ did.description }}</div>
                <div><strong>Routing:</strong> {{ did.routing }}</div>
                <div><strong>Call Recording:</strong> {{ did.record_calls === '1' ? 'Enabled' : 'Disabled' }}</div>
                <div><strong>Voicemail:</strong> {{ did.voicemail === '1' ? 'Enabled' : 'Disabled' }}</div>
              </div>
            </div>
          </div>
          <div v-else-if="testResponse.error" class="text-center text-error">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6 mx-auto mb-2" fill="none" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p class="font-semibold">API Error</p>
            <p>{{ testResponse.error }}</p>
          </div>
          <div v-else class="bg-base-200 p-3 rounded text-sm overflow-auto max-h-40">
            <pre>{{ JSON.stringify(testResponse, null, 2) }}</pre>
          </div>
        </div>
        <div v-else class="text-center">
          <p>No response received.</p>
        </div>
      </div>
      <div class="modal-action" v-if="!isTestLoading">
        <button @click="isTestModalVisible = false; testResponse = null;" class="btn">Close</button>
      </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 { useSearchStore } from '../../stores/search' // Adjust path if needed
import { useAuthStore } from '../../stores/auth'
import { useThemeStore, AVAILABLE_THEMES } from '../../stores/theme'
import { useSettingsStore } from '../../stores/settings'
import GlobalMarketTicker from '../../components/GlobalMarketTicker.vue'

// Define the shape of your data for internal type safety
interface User {
  user_name: string;
  user_id: number;
  user_admin?: number;
}

interface RoutingOption {
  value: string;
  label: string;
}

// Router
const router = useRouter()

// Oil price interface
interface OilPrice {
  price_from_supplier: number | null;
  price_for_customer: number | null;
  price_for_employee: number | null;
  
  // Same Day Tiers
  price_same_day_tier1: number | null;
  price_same_day_tier2: number | null;
  price_same_day_tier3: number | null;
  price_same_day_tier4: number | null;
  price_same_day_tier5: number | null;

  // Prime Tiers
  price_prime_tier1: number | null;
  price_prime_tier2: number | null;
  price_prime_tier3: number | null;
  price_prime_tier4: number | null;
  price_prime_tier5: number | null;

  // Emergency Tiers
  price_emergency_tier1: number | null;
  price_emergency_tier2: number | null;
  price_emergency_tier3: number | null;
  price_emergency_tier4: number | null;
  price_emergency_tier5: number | null;
}

// Reactive data
const user = ref({} as User)
const currentPhone = ref('')
const oilPrice = ref<OilPrice>({
  price_from_supplier: null,
  price_for_customer: null,
  price_for_employee: null,
  
  price_same_day_tier1: null,
  price_same_day_tier2: null,
  price_same_day_tier3: null,
  price_same_day_tier4: null,
  price_same_day_tier5: null,

  price_prime_tier1: null,
  price_prime_tier2: null,
  price_prime_tier3: null,
  price_prime_tier4: null,
  price_prime_tier5: null,

  price_emergency_tier1: null,
  price_emergency_tier2: null,
  price_emergency_tier3: null,
  price_emergency_tier4: null,
  price_emergency_tier5: null,
})
let oilPriceIntervalId: number | null = null
const routingOptions = ref([
  { value: 'main', label: '407323' },
  { value: 'sip', label: '407323_auburnoil' },
  { value: 'cellphone1', label: 'Ed Cell' },
  { value: 'cellphone2', label: 'Aneta Cell' },
  { value: 'test_did', label: 'Test DID' }
] as RoutingOption[])
const selectedOption = ref<RoutingOption | null>(null)
const isRouteModalVisible = ref(false)
const routeModalMode = ref('confirm')
const routeResponse = ref(null as any)
const isTestModalVisible = ref(false)
const isTestLoading = ref(false)
const testResponse = ref(null as any)

// Stores
const themeStore = useThemeStore()
const settingsStore = useSettingsStore()

// Computed properties
const searchStore = computed(() => useSearchStore())

const userInitials = computed((): string => {
  if (!user.value || !user.value.user_name) return '';
  const parts = user.value.user_name.split(' ');
  return parts.length > 1
    ? `${parts[0][0]}${parts[1][0]}`.toUpperCase()
    : user.value.user_name.substring(0, 2).toUpperCase();
})

const currentDate = computed((): string => {
  const now = new Date();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const year = now.getFullYear().toString().slice(-2);
  return `${month}/${day}/${year}`;
})

const dayOfWeek = computed((): string => {
  const now = new Date();
  return now.toLocaleDateString('en-US', { weekday: 'long' });
})

// Format price safely (handles null, string, and number)
const formatPrice = (price: number | string | null): string => {
  if (price === null || price === undefined) return '—';
  const numPrice = typeof price === 'string' ? parseFloat(price) : price;
  if (isNaN(numPrice)) return '—';
  return numPrice.toFixed(2);
}

// Lifecycle
onMounted(() => {
  userStatus()
  updatestatus()
  fetchOilPrice()
  // Refresh oil price every 1 minute
  oilPriceIntervalId = window.setInterval(fetchOilPrice, 1 * 60 * 1000)
})

onUnmounted(() => {
  if (oilPriceIntervalId) {
    clearInterval(oilPriceIntervalId)
  }
})

// Fetch oil pricing
const fetchOilPrice = () => {
  const path = import.meta.env.VITE_BASE_URL + '/info/price/oil';
  axios({
    method: 'get',
    url: path,
    withCredentials: true,
    headers: authHeader(),
  })
    .then((response: any) => {
      oilPrice.value = {
        price_from_supplier: response.data.price_from_supplier,
        price_for_customer: response.data.price_for_customer,
        price_for_employee: response.data.price_for_employee,
        
        price_same_day_tier1: response.data.price_same_day_tier1,
        price_same_day_tier2: response.data.price_same_day_tier2,
        price_same_day_tier3: response.data.price_same_day_tier3,
        price_same_day_tier4: response.data.price_same_day_tier4,
        price_same_day_tier5: response.data.price_same_day_tier5,

        price_prime_tier1: response.data.price_prime_tier1,
        price_prime_tier2: response.data.price_prime_tier2,
        price_prime_tier3: response.data.price_prime_tier3,
        price_prime_tier4: response.data.price_prime_tier4,
        price_prime_tier5: response.data.price_prime_tier5,

        price_emergency_tier1: response.data.price_emergency_tier1,
        price_emergency_tier2: response.data.price_emergency_tier2,
        price_emergency_tier3: response.data.price_emergency_tier3,
        price_emergency_tier4: response.data.price_emergency_tier4,
        price_emergency_tier5: response.data.price_emergency_tier5,
      };
    })
    .catch((error: any) => {
      console.error('Failed to fetch oil pricing:', error);
    });
}

// Functions
const userStatus = async () => {
  let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
  try {
    const response = await axios({
      method: "get",
      url: path,
      withCredentials: true,
      headers: authHeader(),
    });
    if (response.data.ok) {
      user.value = response.data.user;
      // Only fetch voip routing for admin users
      if (user.value.user_admin === 0) {
        fetchCurrentPhone();
      }
    } else {
      localStorage.removeItem('user');
      router.push('/login');
    }
  } catch (error) {
    console.error('Failed to get user status:', error);
  }
}

const updatestatus = () => {
  let path = import.meta.env.VITE_BASE_URL + '/delivery/updatestatus';
  axios({
    method: 'get',
    url: path,
    headers: authHeader(),
  }).then((response: any) => {
    if (response.data.update)
      console.log("Updated Status of Deliveries")
  })
}

const logout = () => {
  // Clear auth data
  const authStore = useAuthStore();
  authStore.clearAuth();
  // Redirect to login
  router.push({ name: 'login' });
}

const fetchCurrentPhone = () => {
  const path = import.meta.env.VITE_BASE_URL + '/admin/voip_routing';
  axios({
    method: 'get',
    url: path,
    headers: authHeader(),
     withCredentials: true,
  })
    .then((response: any) => {
      if (response.data.current_phone) {
        currentPhone.value = response.data.current_phone;
      }
    })
    .catch((error: any) => {
      // Silently ignore 403 - user may not have admin permissions on backend
      if (error.response?.status !== 403) {
        console.error('Failed to fetch current routing:', error);
      }
    });
}

const routeTo = (route: string): Promise<any> => {
  const path = `${import.meta.env.VITE_VOIPMS_URL}/route/${route}`;
  return axios({
    method: 'post',
    url: path,
  withCredentials: true, headers: authHeader()
  })
    .then((response: any) => {
      routeResponse.value = response.data;
      // Find the corresponding label
      const option = routingOptions.value.find(opt => opt.value === route);
      if (option) {
        currentPhone.value = option.label;
      }
      return response.data;
    });
}

const showConfirmRoute = (option: RoutingOption) => {
  selectedOption.value = option;
  if (option.value === 'test_did') {
    testDid();
  } else {
    isRouteModalVisible.value = true;
    routeModalMode.value = 'confirm';
  }
}

const proceedRoute = () => {
  if (selectedOption.value && selectedOption.value.value !== 'test_did') {
    routeModalMode.value = 'loading';
    routeTo(selectedOption.value.value)
      .then(() => {
        routeModalMode.value = 'result';
      })
      .catch((error: any) => {
        routeResponse.value = { error: error.message };
        routeModalMode.value = 'result';
      });
  }
}

const closeRouteModal = () => {
  isRouteModalVisible.value = false;
  routeModalMode.value = 'confirm';
  routeResponse.value = null;
  selectedOption.value = null;
}

const testDid = () => {
  isTestModalVisible.value = true;
  isTestLoading.value = true;
  const path = `${import.meta.env.VITE_VOIPMS_URL}/test/did`;
  axios({
    method: 'get',
    url: path,
   withCredentials: true, headers: authHeader()
  })
    .then((response: any) => {
      testResponse.value = response.data;
      isTestLoading.value = false;
    })
    .catch((error: any) => {
      testResponse.value = { status: 'error', message: error.message };
      isTestLoading.value = false;
    });
}
</script>
