var template = html`
  <div
    id="menu"
    class="navbar navbar-inverse navbar-fixed-top hidden-print ng-scope"
  >
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button
          v-if="currentUser"
          type="button"
          class="navbar-toggle collapsed"
          data-toggle="collapse"
          data-target="#bs-example-navbar-collapse-1"
          aria-expanded="false"
        >
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="/dashboard"
          >Seraph <span style="color:yellow;" v-if="isBeta"> beta site </span>
        </a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling - show skeleton while loading -->
      <div v-if="currentUser || isLoading" class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li class="divider-vertical"></li>
          <li>
            <a href="/bookings">
              <i class="fa fa-plus"></i>
              <span v-if="currentUser">Bookings</span>
              <span v-else-if="isLoading" style="color: #ccc;">Loading...</span>
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a href="/invoices">
              <i class="fa fa-money"></i>
              Till
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a href="/stock#/stock">
              <i class="fa fa-barcode"></i>
              Stock
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a href="/clients#/clients">
              <i class="fa fa-user"></i>
              Clients
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a href="/subscriptions">
              <i class="fa fa-user"></i>
              Subscriptions
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li v-if="!isLoading && (isGroups('Managers') || isGroups('Supervisors'))">
            <a href="/stats#/stats">
              <i class="fa fa-bar-chart-o"></i>
              Stats
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li v-if="!isLoading && isGroups('Accounts')" >
            <a href="/accounts">
              <i class="fa fa-credit-card"></i>
              Accounts
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li v-if="!isLoading && isPermissions('access_hr')">
            <a href="/hr/admin">
              <i class="fa fa-puzzle-piece"></i>
              HR
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li v-if="!isLoading && isGroups('Managers')"  >
            <a href="/admin">
              <i class="fa fa-cogs"></i>
              Admin
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a target="_blank" href="/changelog">
              <i class="fa fa-code-fork"></i>
              Changelog
            </a>
          </li>
          <li class="divider-vertical"></li>
          <li>
            <a target="_blank" href="https://wiki.computerassistance.uk/">
              <i class="fa fa-book"></i>
              Haniel
            </a>
          </li>
          <li class="divider-vertical"></li>
        </ul>
        
        <form
          role="search"
          class="navbar-form navbar-search navbar-right"
          :class="{ 'has-value': input && input.length > 0 }"
          style="position: relative;"
        >
          <input
            type="text"
            name="as_q"
            autocomplete="off"
            placeholder="Search"
            class="search-query form-control"
            @input="debouncedSearch()"
            @submit.prevent=""
            v-model="input"
            style="padding-right: 35px;"
          />
          <i 
            class="fa"
            :class="input ? 'fa-times' : 'fa-search'"
            @click="input && clearSearch()"
          ></i>
        </form>
      </div>
    </div>
    
    <!-- Search Results Dropdown - only show when authenticated -->
    <div v-if="currentUser && input !== '' && input.length >= 2" class="search-results-container">
      <div class="search-results-content">
        <!-- Loading Indicator -->
        <div v-if="isSearching" class="search-loading">
          <i class="fa fa-spinner fa-spin"></i>
          Searching for "{{ input }}"...
        </div>
        
        <!-- Search Results -->
        <template v-else>
          <seachPart class="search-group" v-if="searchs['clients'] && searchs['clients'].length > 0" title="Clients" :data="searchs['clients']"></seachPart>
          <seachPart class="search-group" v-if="searchs['customers'] && searchs['customers'].length > 0" title="Customers" :data="searchs['customers']"></seachPart>
          <seachPart3 class="search-group" v-if="searchs['repairs'] && searchs['repairs'].length > 0" title="Repairs" :data="searchs['repairs']"></seachPart3>
          <seachPart3 class="search-group" v-if="searchs['onsite'] && searchs['onsite'].length > 0" title="Onsite" :data="searchs['onsite']"></seachPart3>
          <seachPart3 class="search-group" v-if="searchs['support'] && searchs['support'].length > 0" title="Support" :data="searchs['support']"></seachPart3>
          <seachPart3 class="search-group" v-if="searchs['sale_leads'] && searchs['sale_leads'].length > 0" title="Sale leads" :data="searchs['sale_leads']"></seachPart3>
          <seachPart2 class="search-group" v-if="searchs['invoices'] && searchs['invoices'].length > 0" title="Invoices" :data="searchs['invoices']"></seachPart2>
          
          <!-- No Results Message -->
          <div class="no-results" v-if="!hasResults">
            No results found for "{{ input }}"
          </div>
        </template>
      </div>
    </div>
  </div>
  </div>
`;
import api from "../../api.js";
import seachPart from "./seachPart.js";
import seachPart2 from "./seachPart2.js";
import seachPart3 from "./seachPart3.js";
export default {
  data: function () {
    return {
      searchs: {},
      input: "",
      isBeta: false,
      permissions: [],
      currentUser: null,
      debounceTimer: null,
      isLoading: true,
      isSearching: false
    };
  },
  computed: {
    hasResults() {
      return Object.keys(this.searchs).some(key => this.searchs[key] && this.searchs[key].length > 0);
    },
    userAvatar() {
      if (!this.currentUser || !this.currentUser.email) {
        return 'https://www.gravatar.com/avatar/?d=mp';
      }
      const emailHash = this.md5(this.currentUser.email.toLowerCase());
      const name = encodeURIComponent(this.currentUser.name || this.currentUser.username || '');
      return `https://www.gravatar.com/avatar/${emailHash}?d=https%3A%2F%2Fui-avatars.com%2Fapi%2F/${name}/32?r=pg`;
    }
  },
  components: {
    seachPart,
    seachPart2,
    seachPart3
  },
  async created() {
    try {
      // Check authentication status first using direct fetch
      try {
        const authResponse = await fetch('/api/v1/me', {
          method: 'GET',
          credentials: 'same-origin',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        });

        if (!authResponse.ok) {
          // User is not authenticated (401, 403, etc.)
          console.warn('⚠️ User not authenticated (HTTP', authResponse.status, ')');
          this.currentUser = null;
          this.permissions = [];
          this.isBeta = false;
          this.isLoading = false;
          return;
        }

        this.currentUser = await authResponse.json();
        console.log('✅ User authenticated:', this.currentUser);
      } catch (error) {
        console.warn('⚠️ Authentication check failed:', error);
        this.currentUser = null;
        this.permissions = [];
        this.isBeta = false;
        this.isLoading = false;
        return;
      }

      // Only proceed with other API calls if user is authenticated
      if (!this.currentUser) {
        console.warn('⚠️ User not authenticated, skipping additional API calls');
        this.isLoading = false;
        return;
      }

      // Beta status check with error handling
      try {
        const betaResponse = await fetch("/beta");
        if (betaResponse.ok && betaResponse.headers.get('content-type')?.includes('application/json')) {
          const json = await betaResponse.json();
          this.isBeta = json.isBeta;
        } else {
          console.warn('⚠️ Beta endpoint returned non-JSON response, defaulting to false');
          this.isBeta = false;
        }
      } catch (error) {
        console.warn('⚠️ Beta check failed:', error);
        this.isBeta = false;
      }

      // Permissions check with error handling
      try {
        this.permissions = await api.get.permissions();
        console.log('✅ Loaded permissions:', this.permissions);
      } catch (error) {
        console.warn('⚠️ Failed to load permissions:', error);
        this.permissions = [];
      }

      this.isLoading = false;
    } catch (error) {
      console.warn('⚠️ Failed to load navbar data:', error);
      this.isBeta = false;
      this.permissions = [];
      this.currentUser = null;
      this.isLoading = false;
    }
  },
  methods: {
    clearSearch() {
      this.input = '';
      this.load(); // Clear search results
    },
    debouncedSearch() {
      // Clear existing timer
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }

      // Set new timer with 300ms delay
      this.debounceTimer = setTimeout(() => {
        this.load();
      }, 300);
    },
    async load(event) {
      if (event) event.preventDefault();

      // Clear search results if no input or less than 2 characters
      if (!this.input || this.input.length < 2) {
        this.searchs = {};
        return;
      }

      this.isSearching = true; // Start searching
      try {
        const raw = await fetch("/search?q=" + encodeURIComponent(this.input));

        // Check if response is JSON
        if (raw.ok && raw.headers.get('content-type')?.includes('application/json')) {
          const json = await raw.json();
          this.searchs = json;
        } else {
          console.warn('⚠️ Search endpoint returned non-JSON response');
          this.searchs = {};
        }
      } catch (error) {
        console.warn('⚠️ Search failed:', error);
        this.searchs = {};
      } finally {
        this.isSearching = false; // End searching
      }
    },
    capitalize(s) {
      if (typeof s !== "string") return "";
      s = s.split("_").join(" ");
      return s.charAt(0).toUpperCase() + s.slice(1);
    },
    isGroups(p) {
      const result = this.permissions.find(el => el.groups == p) != null;
      console.log(`🔍 Checking group '${p}':`, result, 'Available permissions:', this.permissions);
      return result;
    },
    isPermissions(p) {
      const result = this.permissions.find(el => el.permissions == p) != null;
      console.log(`🔍 Checking permission '${p}':`, result);
      return result;
    },
    goTo(url) {
      this.input = ''
      this.load()
      window.location = url
    },
    // Simple string hash for gravatar (not actual MD5, but sufficient for this use case)
    md5(str) {
      let hash = 0;
      if (str.length === 0) return '0';
      for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
      }
      return Math.abs(hash).toString(16);
    }
  },
  template
};
