<!-- headerauth.vue -->
<template>
  <div class="navbar bg-primary border-b border-gray-700 sticky top-0 z-30">
    
    <!-- Navbar Start Section -->
    <div class="navbar-start">
      <!-- Hamburger Menu Toggle for Mobile -->
      <label for="my-drawer-2" class="btn btn-ghost btn-circle drawer-button lg:hidden">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7" /></svg>
      </label>

      <!-- Logo -->
      <router-link :to="{ name: 'home' }" class="btn btn-ghost normal-case text-xl">
      Auburn Oil
      </router-link>
    </div>

    <!-- Navbar Center Section (Desktop Search Bar) -->
    <div class="navbar-center hidden lg:flex">
      <!-- 
        THIS IS THE ONLY CHANGE NEEDED ON THIS ENTIRE PAGE.
        We are adding the @input event listener to trigger the search.
      -->
      <input 
        id="customer-search-input" 
        type="text" 
        placeholder="Search customers..." 
        v-model="searchStore.searchTerm" 
        class="input input-bordered"
        @input="searchStore.debouncedSearch"
      />
    </div>

    <!-- Navbar End Section (Buttons and User Dropdown) -->
    <div class="navbar-end gap-2">
      <!-- Create Customer Button (Desktop Only) -->
      <router-link :to="{ name: 'customerCreate' }" class="btn btn-accent btn-sm hidden lg:inline-flex">
        Create Customer
      </router-link>

      <!-- User Dropdown -->
      <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>
            <router-link :to="{ name: 'employeeProfile', params: { id: user.user_id } }">
              Profile
            </router-link>
          </li>
          <li><a @click="logout">Logout</a></li>
        </ul>
      </div>
      <!-- This provides the loading indicator while we wait for the API call to finish. -->
      <div v-else class="px-4">
       {{user}}
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import { useSearchStore } from '../../stores/search' // Adjust path if needed
import { useAuthStore } from '../../stores/auth'

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


export default defineComponent({
  data() {
    return {
      // Initialize with empty objects to prevent template errors
      user: {} as User,
    }
  },

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

  created() {
    this.userStatus();
  },

  methods: {
    userStatus() {
      let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          console.log(this.user)
          if (response.data.ok) {
            this.user = response.data.user;
          } else {

            localStorage.removeItem('user');
            this.$router.push('/login');
          }
        })

    },

    logout() {
      console.log("Logging out...");
      // Clear auth data
      const authStore = useAuthStore();
      authStore.clearAuth();
      // Redirect to login
      this.$router.push({ name: 'login' });
    }
  }
});
</script>
