       0        0
  5   %ˆl–Ãa¾”ªi?u8 ¸Û71hß�þC+$YÇÌc!@AŒ_ÏÐƒu÷ÜÏÄÌ <    %<!-- Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/ -->

<script setup lang="ts">
import { ignorableWatch } from '@vueuse/shared'
import { debounce } from 'lodash-es'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useRecentSearches } from '#shared/composables/useRecentSearches.ts'
import { useStickyHeader } from '#shared/composables/useStickyHeader.ts'
import { EnumSearchableModels } from '#shared/graphql/types.ts'
import { QueryHandler } from '#shared/server/apollo/handler/index.ts'

import CommonButtonGroup from '#mobile/components/CommonButtonGroup/CommonButtonGroup.vue'
import type { CommonButtonOption } from '#mobile/components/CommonButtonGroup/types.ts'
import CommonInputSearch from '#mobile/components/CommonInputSearch/CommonInputSearch.vue'
import type { CommonInputSearchExpose } from '#mobile/components/CommonInputSearch/CommonInputSearch.vue'
import CommonSectionMenu from '#mobile/components/CommonSectionMenu/CommonSectionMenu.vue'
import type { MenuItem } from '#mobile/components/CommonSectionMenu/index.ts'

import SearchResults from '../components/SearchResults.vue'
import { useSearchLazyQuery } from '../graphql/queries/searchOverview.api.ts'
import { useSearchPlugins } from '../plugins/index.ts'

import type { LocationQueryRaw } from 'vue-router'

interface SearchTypeItem extends MenuItem {
  value: string
}

const props = defineProps<{ type?: string }>()

const route = useRoute()
const router = useRouter()

const searchPlugins = useSearchPlugins()

const search = ref(String(route.query.search || ''))
// we need a separate debounced value to not trigger query
const filter = ref(search.value)

const canSearch = computed(() => filter.value.length >= 1)

const found = reactive({} as Record<string, Record<string, unknown>[]>)

const { recentSearches, addSearch } = useRecentSearches(5)

const model = computed(() => {
  return props.type ? searchPlugins[props.type]?.model : EnumSearchableModels.Ticket // default passed by router
})

const searchQuery = new QueryHandler(
  useSearchLazyQuery(
    () => ({
      search: filter.value,
      onlyIn: model.value,
    }),
    () => ({ enabled: canSearch.value }),
  ),
)

const loading = searchQuery.loadingWithoutCachedResult()

searchQuery.watchOnResult((data) => {
  if (!props.type) return
  if (!data.search) return

  found[props.type] = data.search.items
})

const replaceQuery = (query: LocationQueryRaw) => {
  return router.replace({
    query: {
      ...route.query,
      ...query,
    },
  })
}

const searchInput = ref<CommonInputSearchExpose>()
const focusSearch = () => searchInput.value?.focus()

const selectType = async (selectedType: string) => {
  await router.replace({ params: { type: selectedType } })

  // focus on tab that was selected
  // it's useful when user selected type from the main screen (without tab controls)
  // and after that we focus on tab controls, so user can easily change current type
  const tabOption = document.querySelector(`[data-value="${selectedType}"]`) as HTMLElement | null
  tabOption?.focus()
}

onMounted(() => {
  focusSearch()
})

const loadByFilter = async (filterQuery: string) => {
  filter.value = filterQuery
  replaceQuery({ search: filterQuery })

  if (!canSearch.value || !props.type) {
    return
  }

  addSearch(filterQuery)

  if (searchQuery.isFirstRun()) {
    searchQuery.load()
  }
}

// load data after a few ms to not overload the api
const debouncedLoad = debounce(loadByFilter, 600)

const { ignoreUpdates } = ignorableWatch(search, async (search) => {
  if (!search || !props.type) {
    await loadByFilter(search)
    return
  }

  await debouncedLoad(search)
})

// load data immidiately when type changes or when recent search selected
watch(
  () => props.type,
  () => loadByFilter(search.value),
  { immediate: true },
)

const selectRecentSearch = async (recentSearch: string) => {
  ignoreUpdates(() => {
    search.value