<template>
  <main :class="{ 'cursor-wait': pending }">
    <section class="flex">
      <div class="container">
        <h1 v-if="entity" class="pb-3 text-4xl lg:pb-6 lg:text-7xl">
          {{ entity.title }}
        </h1>
        <p>{{ title }}</p>
        <form @submit.prevent>
          <SearchInput v-model="searchTerm" />
        </form>
      </div>
    </section>
    <template v-if="data && searchTerm">
      <Container>
        <ol class="mt-10">
          <SearchResult v-for="hit in data" v-bind="hit" :key="hit.id" />
        </ol>
      </Container>
    </template>
  </main>
</template>

<script lang="ts" setup>
definePageMeta({
  name: 'search',
  drupalFrontendRoute: true,
  path: '/suche',
  languageMapping: {
    fr: '/chercher',
    en: '/search',
  },
})

const searchTerm = useQueryString('text')
const language = useCurrentLanguage()
const { $textsPlural, $texts } = useEasyTexts()

const searchQuery = computed(() => {
  return {
    langcode: language.value,
    size: 16,
    text: searchTerm.value || undefined,
  }
})

const { data, pending } = await useFetch('/api/content-search', {
  query: searchQuery,
})

const { entity } = await useDrupalRouteQuery('nodePage')

const total = computed(() => 10)

const title = computed(() => {
  if (total.value === 0) {
    return $texts('search.noResults', 'Keine Suchresultate gefunden')
  }

  return $textsPlural(
    'search.resultsTitle',
    total.value,
    '1 Resultat gefunden',
    '@count Resultate gefunden',
  )
})

await renderPageDependencies()
</script>
