<script setup>
  import { PerfectScrollbar } from 'vue3-perfect-scrollbar'
  import {
    VList,
    VListItem,
  } from 'vuetify/components/VList'

  const props = defineProps({
    isDialogVisible: {
      type: Boolean,
      required: true,
    },
    searchResults: {
      type: Array,
      required: true,
    },
  })

  const emit = defineEmits([
    'update:isDialogVisible',
    'search',
  ])


  // 👉 Hotkey

  // eslint-disable-next-line camelcase
  const { ctrl_k, meta_k } = useMagicKeys({
    passive: false,
    onEventFired(e) {
      if (e.ctrlKey && e.key === 'k' && e.type === 'keydown')
        e.preventDefault()
    },
  })

  const refSearchList = ref()
  const refSearchInput = ref()
  const searchQueryLocal = ref('')

  // 👉 watching control + / to open dialog

  /* eslint-disable camelcase */
  watch([
    ctrl_k,
    meta_k,
  ], () => {
    emit('update:isDialogVisible', true)
  })

  /* eslint-enable */

  // 👉 clear search result and close the dialog
  const clearSearchAndCloseDialog = () => {
    searchQueryLocal.value = ''
    emit('update:isDialogVisible', false)
  }

  const getFocusOnSearchList = e => {
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      refSearchList.value?.focus('next')
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      refSearchList.value?.focus('prev')
    }
  }

  const dialogModelValueUpdate = val => {
    searchQueryLocal.value = ''
    emit('update:isDialogVisible', val)
  }

  watch(() => props.isDialogVisible, () => {
    searchQueryLocal.value = ''
  })

  const menuVisible = ref(false)
  //Watch para o searchQueryLocal, para exibir o menu de resultados
  watch(() => searchQueryLocal.value, () => {
    if (searchQueryLocal.value.length > 0) {
      menuVisible.value = true
    } else {
      menuVisible.value = false
    }
  })

  watch(() => menuVisible.value, (newValue) => {
    if (!newValue) {
      searchQueryLocal.value = ''
    }
  })

  const windowsWidth = window.innerWidth
  const isMobile = ref(false)

  if (windowsWidth < 768) {
    isMobile.value = true
  }

  const ph = ref('Pesquise por vagas...');
  const phs = ['vagas...', 'produtos...', 'eventos...'];
  let phIndex = 0;

  const typeEffect = async () => {
    const staticText = 'Pesquise por '; // Texto fixo
    const dots = '...'; // Pontos ao final
    const currentWord = phs[phIndex];

    // Apagar o texto dinâmico (apenas "vagas", "produtos", "eventos" + os "...")
    for (let i = currentWord.length + dots.length; i >= 0; i--) {
      ph.value = staticText + currentWord.substring(0, i);
      await delay(100); // Velocidade do apagar (100ms por caractere)
    }

    // Atualizar para o próximo texto
    phIndex = (phIndex + 1) % phs.length;
    const newWord = phs[phIndex];

    // Escrever o novo texto dinâmico
    for (let i = 0; i <= newWord.length + dots.length; i++) {
      ph.value = staticText + newWord.substring(0, i);
      await delay(100); // Velocidade do escrever (100ms por caractere)
    }

    // Repetir o processo
    setTimeout(typeEffect, 2000); // Pausa de 2 segundos antes de reiniciar
  };

  // Função utilitária para criar delay
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  // Iniciar o efeito ao montar o componente
  typeEffect();

</script>

<template>

  <VCardText :class="isMobile ? 'w-100' : ''"
    :style="isMobile ? 'padding-left: 6px !important;' : 'padding: 0px 6px; max-width: 400px;'">
    <!-- 👉 Search Input -->
    <VTextField ref="refSearchInput" id="refSearchInput" v-model="searchQueryLocal"
      @keyup.esc="clearSearchAndCloseDialog" @keydown="getFocusOnSearchList"
      @update:model-value="$emit('search', searchQueryLocal)" variant="solo-filled" :placeholder="ph"
      style="border: var(--color-akkiperto) 1px solid; border-radius: 7px;">

      <!-- 👉 Append Inner -->
      <template #append-inner v-if="searchQueryLocal.length > 0">
        <div class="d-flex align-start">
          <IconBtn size="22" @click="clearSearchAndCloseDialog">
            <VIcon icon="tabler-x" size="20" />
          </IconBtn>
        </div>
      </template>

    </VTextField>
  </VCardText>

  <!-- 👉 Perfect Scrollbar -->
  <VMenu v-model="menuVisible" activator="#refSearchInput" location="bottom center" max-height="400" offset-y
    close-delay="10000" :close-on-content-click="true" :persistent="false" class="menu-search">
    <PerfectScrollbar :options="{ wheelPropagation: false, suppressScrollX: true }" class="h-100">
      <!-- 👉 Search List -->
      <VList v-show="searchQueryLocal.length && !!props.searchResults.length" ref="refSearchList" density="compact"
        class="app-bar-search-list">
        <!-- 👉 list Item /List Sub header -->
        <slot name="searchResult" />
      </VList>

      <!-- 👉 No Data found -->
      <div v-show="!props.searchResults.length && searchQueryLocal.length" class="h-100">
        <slot name="noData">
          <VCard>
            <VCardText class="h-100">
              <div
                class="app-bar-search-suggestions d-flex flex-column align-center justify-center text-high-emphasis h-100">
                <div class="d-flex align-center flex-wrap justify-center gap-2 text-h6 my-3">
                  <VIcon size="20" icon="tabler-file-x" />
                  <span>Não encontramos nenhum resultado para </span>
                  <span>"{{ searchQueryLocal }}"</span>
                </div>
                <slot name="noDataSuggestion" />
              </div>
            </VCardText>
          </VCard>
        </slot>
      </div>
    </PerfectScrollbar>
  </VMenu>
</template>

<style lang="scss">
  .app-bar-search-suggestions {
    .app-bar-search-suggestion {
      &:hover {
        color: rgb(var(--v-theme-primary));
      }
    }
  }

  .app-bar-search-dialog {
    .v-overlay__scrim {
      backdrop-filter: blur(4px);
    }

    .v-list-item-title {
      font-size: 0.875rem !important;
    }

    .v-input {
      .v-field {
        .v-field__field {
          input {
            padding-block-start: 1rem !important;
          }
        }
      }
    }

    .app-bar-search-list {

      .v-list-item,
      .v-list-subheader {
        font-size: 0.75rem;
        padding-inline: 1.5rem !important;
      }

      .v-list-item {
        .v-list-item__append {
          .enter-icon {
            visibility: hidden;
          }
        }

        &:hover,
        &:active,
        &:focus {
          .v-list-item__append {
            .enter-icon {
              visibility: visible;
            }
          }
        }
      }

      .v-list-subheader {
        line-height: 1;
        min-block-size: auto;
        padding-block: 0.6875rem 0.3125rem;
        text-transform: uppercase;
      }
    }
  }
</style>

<style lang="scss"
       scoped>
        .card-list {
          --v-card-list-gap: 16px;
        }
      </style>
