<script setup lang="ts">
import { useDocumentStore } from '@/stores/documents'
import { ref, nextTick } from 'vue'

const documentStore = useDocumentStore()
const showSearchInput = ref<boolean>(false)
const search = ref<HTMLInputElement | null>()
const searchButton = ref<HTMLButtonElement | null>()

const toggleSearchInput = () => {
  showSearchInput.value = !showSearchInput.value
  nextTick(() => {
    const input = search.value
    if (input) input.focus()
    else if (searchButton.value) searchButton.value.blur()
    executeSearch()
  })
}

const executeSearch = () => {
  documentStore.setFilter(search.value?.value ?? '')
}

defineExpose({
  toggleSearchInput
})
</script>

<template>
  <nav>
    <div class="buttons">
      <UploadButton />
      <SvgButton
        name="create-folder"
        data-tooltip="New folder"
        @click="() => documentStore.fileExplorer.newFolder()"
      />
      <slot></slot>
      <div class="spacer"></div>
      <template v-if="showSearchInput">
        <input
          ref="search"
          type="search"
          class="margin-input"
          @keyup.esc="toggleSearchInput"
          @input="executeSearch"
        />
      </template>
      <SvgButton ref="searchButton" name="find" @click="toggleSearchInput" />
      <SvgButton name="cog" @click="console.log('settings menu')" />
    </div>
  </nav>
</template>

<style scoped>
.buttons {
  padding: 0;
  display: flex;
  align-items: center;
  height: 3.5rem;
  z-index: 10;
}
.buttons > * {
  flex-shrink: 1;
}
.spacer {
  flex-grow: 1;
}
input[type='search'] {
  background: var(--primary-background);
  color: var(--primary-color);
  border: 0;
  border-radius: 0.1rem;
  padding: 0.5rem;
  outline: none;
  font-size: 1.5rem;
  max-width: 30vw;
}
</style>
