<template>
  <div
    v-if="isDeveloper && !isProd"
    :class="environmentHeaderColor + ' environment-bar'"
  ></div>

  <div
    v-if="offline"
    class="q-pt-xs bg-red-10 text-white text-h4 offline-bar"
    style="vertical-align: middle"
  >
    OFFLINE: No network connection -
    <a class="offline-link text-cyan-2" href="/v1/offline/">
      Go to Offline Product Search
    </a>
  </div>

  <div
    v-if="
      $rootScope.isHQ()
        ? !isNerveCenter() && !isShowRegistration
        : showNewTheme && !isNerveCenter() && !isShowRegistration
    "
    @mouseleave="globalStore.hideMegaMenu"
    :class="{
      'new-header': true,
      'print-hide': true,
      hideHeader: !$rootScope?.globalCtrl?.hidePrint,
      stuck: customerInfo?.ttUserSettings?.brezWaypoint === '1',
    }"
    ref="header"
  >
    <div class="row items-center q-pa-sm bg-dark text-white">
      <div class="productSearchDiv col row items-center">
        <div
          class="row items-center q-pr-sm"
          @mouseover="showMegaMenu = true"
          @click="showMegaMenu = !showMegaMenu"
        >
          <div
            id="shoppingOptions"
            :class="
              $rootScope?.isHQ()
                ? 'shoppingOptions col-auto q-pl-xs q-pr-sm'
                : 'shoppingOptions col-auto hide-1000 q-pl-xs'
            "
          >
            <a
              :href="$rootScope?.isHQ() ? '/' : 'javascript:void(0);'"
              class="text-white gt-xs"
            >
              PRODUCTS
            </a>
            <q-btn
              class="xs"
              round
              dense
              color="dark"
              text-color="white"
              icon="home"
              aria-label="products"
            />
          </div>
          <div v-if="!$rootScope?.isHQ()" class="col-auto">
            <q-icon
              name="expand_more"
              size="30px"
              color="primary"
              class="cursor-pointer"
            ></q-icon>
          </div>
        </div>

        <!-- Search bars -->

        <div class="search-bar col relative-position">
          <q-select
            v-model="data.searchTerm"
            placeholder="What are you searching for today?"
            color="primary"
            bg-color="white"
            hide-dropdown-icon
            hide-selected
            outlined
            dense
            :autofocus="autofocusSearch"
            use-input
            fill-input
            :options="data.autocompleteResults"
            @filter="autocomplete"
            @blur="clearAutocomplete"
            @input-value="changeSearchInput"
            @keydown.enter="runSearch"
            @update:model-value="runSearch"
            class="search-input q-mr-md hide-575 q-mb-none"
          >
            <template v-slot:prepend class="hide-751">
              <div style="font-size: 14px" class="text-bold q-mr-sm hide-751">
                {{ currentSearchCategory }}
              </div>
              <q-btn
                round
                dense
                flat
                icon="search"
                aria-label="search"
                color="black"
                @click="runSearch"
              />
            </template>
          </q-select>

          <q-btn
            class="show-575 q-pr-md q-mr-md"
            no-caps
            dense
            label="Search"
            color="white"
            text-color="black"
            icon="search"
            @click="showSearchDialog = true"
          />

          <q-dialog
            class="show-575"
            v-model="showSearchDialog"
            ref="mobileSearchDialog"
          >
            <q-card class="dialog-width">
              <q-bar>
                <div>Product Search</div>
                <q-space />
                <q-btn dense flat icon="close" label="Close" v-close-popup />
              </q-bar>
              <q-card-section>
                <q-select
                  v-model="data.searchTerm"
                  ref="mobileSearchInput"
                  :placeholder="currentSearchCategory"
                  color="primary"
                  bg-color="white"
                  hide-dropdown-icon
                  hide-selected
                  outlined
                  dense
                  autofocus
                  use-input
                  fill-input
                  behavior="menu"
                  :options="data.autocompleteResults"
                  @filter="autocomplete"
                  @blur="clearAutocomplete"
                  @keydown.enter="runSearch"
                  @update:model-value="runSearch"
                  class="search-input col q-mr-xs q-mb-none"
                >
                  <template v-slot:append>
                    <q-btn
                      round
                      dense
                      flat
                      icon="search"
                      aria-label="search"
                      color="black"
                      @click="runSearch"
                    />
                  </template>
                </q-select>
              </q-card-section>
            </q-card>
          </q-dialog>

          <!-- Autocomplete results -->
          <div
            v-if="false"
            v-show="data.autocompleteResults.length > 0"
            class="auto-complete rounded-borders bg-white text-black shadow-8"
          >
            <q-list bordered dense padding class="rounded-borders">
              <q-item
                v-for="(item, index) in data.autocompleteResults"
                :key="index"
                clickable
                @click="gotoAutocomplete(item)"
                v-ripple
                class="items-center"
              >
                {{ item }}
              </q-item>
            </q-list>
          </div>
        </div>

        <q-btn
          class="mobile-only q-mr-sm"
          dense
          flat
          icon="qr_code_scanner"
          @click="showBarcodeScanner = true"
        />
        <q-dialog
          class="mobile-only"
          v-model="showBarcodeScanner"
          @hide="html5QrcodeScanner.clear()"
        >
          <barcode-scanner @scan-success="scanSuccess" />
        </q-dialog>

        <q-btn
          icon="filter_alt"
          dense
          flat
          class="show-1280 q-mr-md"
          @click="showSearchBarOptions = !showSearchBarOptions"
        />
        <q-dialog v-model="showSearchBarOptions">
          <q-card class="row no-wrap q-pa-md">
            <div class="column">
              <q-checkbox
                v-if="!$rootScope?.isHQ()"
                v-model="searchWithinResults"
                label="Within Results"
              >
                <q-tooltip style="font-size: 1em">
                  Limit search to previous results
                </q-tooltip>
              </q-checkbox>
              <q-checkbox
                v-if="!$rootScope?.isHQ()"
                v-model="searchMfgPartNumber"
                label="Mfg Part #"
              >
              </q-checkbox>
            </div>
          </q-card>
        </q-dialog>

        <q-checkbox
          v-if="!$rootScope?.isHQ()"
          dark
          v-model="searchWithinResults"
          label="Within Results"
          class="hide-1280"
          @click="loaded = true"
        >
          <q-tooltip style="font-size: 1em">
            Limit search to previous results
          </q-tooltip></q-checkbox
        >
        <q-checkbox
          v-if="!$rootScope?.isHQ()"
          dark
          v-model="searchMfgPartNumber"
          label="Mfg Part #"
          class="q-ml-sm q-mr-xl hide-1280"
        ></q-checkbox>
      </div>

      <div class="col-auto row items-center">
        <div
          class="col-auto q-mr-lg hide-751 pointer"
          @click="openCustomerInfo()"
        >
          <!-- @click="showCustomerInfo = !showCustomerInfo" -->
          <div class="text-grey-5">Welcome</div>
          <div>
            {{ customerInfo?.cust_name }}
          </div>
          <q-tooltip style="font-size: 1em">
            {{
              customerInfo?.cust_phone?.trim()
                ? customerInfo?.cust_phone?.trim()
                : 'No phone number on record'
            }}
          </q-tooltip>
        </div>

        <div class="col-auto q-mr-lg hide-1000">
          <div class="text-grey-5">Customer Since</div>
          <div>
            {{ new Date(customerInfo?.accountCreateDate)?.getFullYear() }}
          </div>
          <q-tooltip style="font-size: 1em">
            {{ customerInfo?.accountCreateDate }}
          </q-tooltip>
        </div>

        <span
          v-if="customerInfo.site_code === 'BRS'"
          :class="
            donationClass + ' q-mr-lg hide-1000 self-center cursor-pointer'
          "
          @click="getDonations"
        >
          <img
            src="/graphics/conservation.png"
            alt="Conservation logo"
            style="width: 60px !important"
          />
          {{ donationTotal }}
        </span>

        <div
          class="col-auto linkChangeCust cursor-pointer"
          @mouseover="showAccountMenu = true"
          @click="toggleAccountMenu()"
        >
          <div class="row col-auto q-mr-sm">
            <div class="col-auto q-mr-sm">
              <div class="text-primary text-bold">Account</div>
              <div class="text-bold">
                {{ customerInfo?.cust_num }}
              </div>
            </div>
            <q-icon
              name="expand_more"
              size="30px"
              color="primary"
              class="col-auto self-center"
            ></q-icon>
          </div>

          <!-- <span class="q-mr-xs text-grey-5 hide-1280">Account:</span>
          <span class="q-mr-xs hide-401">
            {{ customerInfo?.cust_num }}
          </span> -->
        </div>
      </div>
    </div>

    <mega-menu v-show="showMegaMenu"></mega-menu>
    <account-menu
      v-show="showAccountMenu"
      @mouseleave="showAccountMenu = false"
    ></account-menu>
    <subheader-bar></subheader-bar>

    <carton-detail-lookup-dialog />
    <wish-list-dialog />
    <sales-summary-report />
  </div>

  <add-to-wish-list-dialog />
  <!-- TODO: rewrite -->
  <!-- <q-dialog v-model="showCustomerInfo" style="height: 90%; width: 90%">
    <customer-info></customer-info>
  </q-dialog> -->
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import SubheaderBar from './SubheaderBar.vue';
import MegaMenu from './MegaMenu.vue';
import AccountMenu from './AccountMenu.vue';
// import CustomerInfo from './CustomerInfo.vue';
import BarcodeScanner from './BarcodeScanner.vue';
import CartonDetailLookupDialog from './CartonDetailLookupDialog.vue';
import WishListDialog from './WishListDialog.vue';
import AddToWishListDialog from './AddToWishListDialog.vue';
import SalesSummaryReport from './SalesSummaryReport.vue';

const showBarcodeScanner = ref(false);
const showSearchBarOptions = ref(false);
const showSearchDialog = ref(false);
const mobileSearchDialog = ref(null);
const mobileSearchInput = ref(null);
const autofocusSearch = ref(
  location.pathname.includes('/ws/ps') || location.pathname === '/'
    ? true
    : false
);
const data = reactive({
  searchTerm: '',
  autocompleteResults: [],
});
const globalStore = window.PiniaStores.useGlobalStore();
const { toCurrency, isNerveCenter, isShowRegistration, updateNetworkStatus } =
  globalStore;
const {
  loaded,
  offline,
  $rootScope,
  customerInfo,
  currentSearchCategory,
  searchWithinResults,
  searchMfgPartNumber,
  showMegaMenu,
  showNewTheme,
  showAccountMenu,
  html5QrcodeScanner,
  isDeveloper,
  isProd,
  searchTerm,
} = window.Pinia.storeToRefs(globalStore);
const productStore = window.PiniaStores.useProductStore();
const userStore = window.PiniaStores.useUserStore();

const donationTotal = computed(() =>
  toCurrency(customerInfo.value?.conservDonations)
);
const donationClass = computed(() =>
  customerInfo.value?.conservDonations > 0
    ? 'text-light-green-11'
    : 'text-red-11'
);
const getDonations = $rootScope.value?.getDonations;

// TODO: remove duplicate params
const runSearch = () => {
  if (!data.searchTerm) return;

  if (data.searchTerm.length > 128) {
    globalStore.notifyFailed(
      'Search phrase over 128-character limit',
      'Please try again.'
    );
    return;
  }

  let searchVal = data.searchTerm.toLowerCase();
  searchVal = searchVal.replace(/%/g, '');
  searchVal = searchVal.replace(/&/g, '%2526');
  searchVal = searchVal.replace('#', '');
  searchVal = searchVal.replace('=', '-');
  let addTerms = '';
  let nVal = '';
  if (searchWithinResults.value) {
    let extraSearch = location.search.split('&');
    for (let i = 0; i < extraSearch.length; i++) {
      if (extraSearch[i].match('Ntt')) {
        let splitTerms = extraSearch[i].split('=');
        addTerms = '+' + splitTerms[1];
      }
      if (extraSearch[i].match('N=')) {
        nVal = extraSearch[i] + '&';
        nVal = nVal.replace(/\?/g, '');
      }
    }
  }

  // need to build a special parameter for running a part search.
  if (searchMfgPartNumber.value) {
    nVal.match('&') ? (nVal += '&Ntk=p_sku&') : (nVal += 'Ntk=p_sku&');
  }

  let baseurl = window.new_url?.split('?')?.[1];
  baseurl = baseurl ? '?' + baseurl + '&' : '?';
  let newUrl = '';

  if (location.hash.match('newDsType')) {
    let newfilter = location.hash.replace(/\?/g, '');
    let newfilters = newfilter.split('&');
    let newloc = '';
    for (let i = 0; i < newfilters.length; i++) {
      if (!newfilters[i].match('Ntt') && !newfilters[i].match('search=true')) {
        newloc = newloc + '&' + newfilters[i];
      }
    }
    newUrl =
      baseurl +
      'search=true&' +
      nVal +
      'Ntt=' +
      searchVal.replace(/ /g, '+') +
      addTerms +
      newloc;
  } else {
    newUrl =
      baseurl +
      'search=true&' +
      nVal +
      'Ntt=' +
      searchVal.replace(/ /g, '+') +
      addTerms;
  }
  window.setCookie('withinResults', searchWithinResults);
  newUrl = newUrl + '&' + location.hash.replace('#/', '').replace('#', '');
  newUrl = productStore.removeDuplicateParamsExceptLast(newUrl);
  window.location.href = '/ws/ps/' + newUrl;
};

const gotoAutocomplete = (item) => {
  data.searchTerm = item;
  data.autocompleteResults = [];
  runSearch();
};

const clearAutocomplete = () =>
  setTimeout(() => (data.autocompleteResults = []), 1000);

const environmentHeaderColor = computed(() =>
  window.AppEnvironment === 'develop'
    ? location.hostname === 'localhost'
      ? 'bg-lime-14'
      : 'bg-indigo-14'
    : 'bg-pink'
);

const toggleAccountMenu = () => {
  showAccountMenu.value = !showAccountMenu.value;
};

const openCustomerInfo = () => {
  if (
    globalStore.hasGroupPermission(['-Menu-ChangeAccount', '-Menu-Setup']) &&
    !userStore.isCustomer()
  )
    window.location.href = '/ws/brs/brsCustomerInfo/';
};

const changeSearchInput = (val) => (val ? (data.searchTerm = val) : null);

const autocomplete = (val, update, abort) => {
  if (val?.length < 2 || val?.length > 128) {
    abort();
    return;
  }

  data.searchTerm = val;

  update(() => {
    $rootScope.value.TypeaheadCtrl.getLocation(val).then((results) => {
      if (!results || !results?.length) {
        data.autocompleteResults = [];
        return;
      }
      data.autocompleteResults = results;
    });
  });
};

const scanSuccess = (text) => {
  data.searchTerm = text;
  showBarcodeScanner.value = false;
  const searchInput = document.querySelector('.search-input input');
  setTimeout(() => {
    searchInput?.['focus']?.();
    runSearch();
  }, 500);
};

watch(showNewTheme, () => {
  $rootScope.value.refreshCartTotals();
});

watch(
  () => $rootScope.value.brsCustomerInfo,
  () =>
    $rootScope.value.brsCustomerInfo.getCustomerInfo(
      $rootScope.value.customerInfo.cust_num
    )
);

window.addEventListener('online', updateNetworkStatus);
window.addEventListener('offline', updateNetworkStatus);

const onMountedHandler = () => {
  calculateStickyHeaderOffset();
  updateNetworkStatus();
};

// TODO: temp solution to fix sticky header zoom issue
const calculateStickyHeaderOffset = () => {
  const offset = (header) => {
    const sticky = document.querySelector('.stickyContainer');
    if (!sticky) return;

    const headerStyle = window.getComputedStyle(header);
    if (headerStyle.position === 'fixed') {
      const stickyToTop =
        sticky.getBoundingClientRect().top + window.pageYOffset;
      const headerToTop = header['offsetHeight'];
      if (stickyToTop < headerToTop || stickyToTop - headerToTop > 10)
        sticky['style'].marginTop = header?.['offsetHeight'] + 10 + 'px';
    } else {
      sticky['style'].marginTop = '10px';
    }
  };

  const resize = (_) => {
    setTimeout(() => {
      const header = document.querySelector('.new-header');
      const dummy = document.getElementById('dummy-container');
      if (!header || !dummy) return;
      const distanceBetweenHeaderAndContent =
        header.getBoundingClientRect().bottom -
        dummy.getBoundingClientRect().top;

      if (distanceBetweenHeaderAndContent > 0) {
        offset(header);
      } else if (distanceBetweenHeaderAndContent < -10) {
        offset(header);
      }
    }, 1000);
  };

  window.addEventListener('resize', resize);

  resize(null);
};

watch(showNewTheme, () => {
  $rootScope.value.refreshCartTotals();
});

watch(
  () => $rootScope.value.brsCustomerInfo,
  () =>
    $rootScope.value.brsCustomerInfo.getCustomerInfo(
      $rootScope.value.customerInfo.cust_num
    )
);

watch(searchTerm, () => {
  data.searchTerm = searchTerm;
  runSearch();
});

// TODO: temp solution to fix sticky header zoom issue
onMounted(onMountedHandler);
</script>

<style scoped>
.offline-bar {
  bottom: 0;
  position: fixed;
  height: 48px;
  width: 100%;
  z-index: 6999;
  text-align: center;
}
.environment-bar {
  bottom: 0;
  position: fixed;
  height: 10px;
  width: 100%;
  z-index: 7000;
}
.auto-complete {
  position: absolute;
  z-index: 10;
}

div#shoppingOptions.shoppingOptions,
div#shoppingOptions.shoppingOptions a {
  width: fit-content;
  color: white;
  display: inline-block;
  text-align: center;
  vertical-align: middle;
  padding-top: 0px;
  font-size: 24px;
  cursor: pointer;
  font-family: Roboto, -apple-system, 'Helvetica Neue', sans-serif !important;
  font-weight: bold;
}

div.search-bar {
  max-width: 600px;
}

@media only screen and (min-width: 759px) and (min-height: 500px) {
  .new-header.stuck {
    width: 100%;
    z-index: 100;
    background-color: white;
    position: fixed;
    border-bottom: lightgrey solid 1px;
    top: 0;
  }

  .stickyContainer {
    margin-top: 161px;
  }
}

@media screen and (max-width: 1280px) {
  .hide-1280 {
    display: none !important;
  }
}

@media screen and (min-width: 1281px) {
  .show-1280 {
    display: none !important;
  }
}

@media screen and (max-width: 1000px) {
  .hide-1000 {
    display: none !important;
  }
}

@media screen and (max-width: 751px) {
  .hide-751 {
    display: none !important;
  }
}

@media screen and (max-width: 575px) {
  .hide-575 {
    display: none !important;
  }
}

@media screen and (min-width: 576px) {
  .show-575 {
    display: none !important;
  }
}

@media screen and (max-width: 401px) {
  .hide-401 {
    display: none !important;
  }
}

.offline-link,
.offline-link a:link,
.offline-link a:visited {
  font-family: inherit;
  font-size: inherit;
  text-decoration: none;
  font-weight: bold;
}
</style>

<style>
div.search-bar label.search-input div.bg-white:focus-within {
  outline: 2px #ee8900 solid;
  background-color: rgb(239, 238, 201) !important;
}

.q-dialog.fullscreen.q-dialog--modal {
  z-index: 1040 !important;
}
</style>
