<template>
  <div class="container wrapper">
    <form @submit.prevent="search" class="search-container">
      <div class="categorias-wrapper">
        <select v-model="selectedCategory" class="categorias">
          <option selected value="">Todas las categorías</option>
          <option
            v-for="(category, key) in categories"
            :key="key"
            :value="category"
          >
            {{ category }}
          </option>
        </select>
      </div>
      <input
        id="searchbox"
        @focus="focused"
        @blur="focusedOut"
        v-model="searchText"
        class="search-text"
        type="text"
        autocomplete="off"
        placeholder=""
      />
      <div class="search-link">
        <img
          class="search-icon"
          src="@/assets/img/latienda-search.svg"
          alt="latienda.coop-search"
          @click="search"
        />
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'SearchHeader',
  data() {
    return {
      searchText: '',

      typing: null,

      selectedCategory: '',

      categories: [
        'Alimentación, bebida y tabaco',
        'Arte y ocio',
        'Bebés y niños pequeños',
        'Bricolaje',
        'Cámaras y ópticas',
        'Casa y jardín',
        'Economía e industria',
        'Electrónica',
        'Elementos religiosos y ceremoniales',
        'Equipamiento deportivo',
        'Juegos y juguetes',
        'Maletas y bolsos de viaje',
        'Material de oficina',
        'Mobiliario',
        'Multimedia',
        'Productos para adultos',
        'Productos para mascotas y animales',
        'Ropa y accesorios',
        'Salud y belleza',
        'Software',
        'Vehículos y recambios',
      ],
    }
  },

  mounted() {
    this.startTyping()
  },

  beforeDestroy() {
    this.stopTyping()
  },

  methods: {
    focused() {
      this.stopTyping()
      document.querySelector('#searchbox').setAttribute('placeholder', '')
    },
    focusedOut() {
      document.querySelector('#searchbox').setAttribute('placeholder', '')
    },
    sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms))
    },
    startTyping() {
      let current = ''
      let i = 0
      let word = 0
      let step = 0
      let input = document.querySelector('#searchbox')
      let placeholderTexts = [
        'Jabón sólido',
        'Huertos de libertad',
        'Hierbabuena',
        'Energía eléctrica',
      ]
      this.typing = setInterval(() => {
        if (current === placeholderTexts[word]) {
          step++
          if (step === 10) {
            current = ''
            i = 0
            word++
            input.setAttribute('placeholder', current)
            step = 0
            if (word === placeholderTexts.length) {
              word = 0
            }
          }
        } else {
          current += placeholderTexts[word].charAt(i)
          input.setAttribute('placeholder', current)
          i++
        }
      }, 100)
    },
    stopTyping() {
      clearInterval(this.typing)
    },
    search() {
      if (this.searchText) {
        if (this.selectedCategory !== '') {
          return this.$router.push({
            name: 'busqueda',
            query: {
              q: this.searchText,
              category: this.selectedCategory,
            },
          })
        } else {
          return this.$router.push({
            name: 'busqueda',
            query: { q: this.searchText },
          })
        }
      }
    },
    clearSearchText() {
      this.searchText = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.search-container {
  background-color: $color-light;
  height: 60px;
  border-radius: 40px;
  overflow: hidden;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0 50px;
  -webkit-box-shadow: 0px 0px 20px 0px #d1d1d1; /* Android 2.3+, iOS 4.0.2-4.2, Safari 3-4 */
  box-shadow: 0px 0px 20px 0px #d1d1d1;
  @include mobile {
    height: 40px;
    margin: 1rem auto;
  }
  @include tablet {
    width: 70%;
  }
}

.search-link {
  @include mobile {
    width: 40px;
    height: 40px;
    padding: 0.6rem;
    float: right;
    display: flex;
    justify-content: center;
    align-items: center;
    text-decoration: none;
    transition: 0.4s;
  }
  @include tablet {
    width: 4rem;
    margin-right: 1.5rem;
  }
}

.categorias-wrapper {
  height: 100%;
  background: linear-gradient(90deg, #1aceb8, #0bbfba);
  padding: 0.4em 0.5em 0.4em 1.2em;

  @include mobile {
    display: none;
  }
}

.categorias {
  cursor: pointer;
  outline: none;
  background: transparent;
  color: $color-light;
  height: 100%;
  width: 18rem;
  -moz-appearance: none;
  text-align: center;

  @include mobile {
    display: none;
  }
  @include tablet {
    width: 14rem;
  }
}

.search-icon {
  cursor: pointer;
  @include mobile {
    margin-left: 0;
    width: 100%;
  }
  @include tablet {
    float: right;
    height: 70%;
  }
}

.search-text {
  outline: none;
  width: 100%;

  ::-webkit-input-placeholder {
    display: inline-block;
    opacity: 0.2;
    transition: all 0.3s ease-in-out;
    padding-right: 0.15em;
    white-space: nowrap;
  }

  input:focus::-webkit-input-placeholder {
    -webkit-transform: translateY(-125%);
    transform: translateY(-125%);
    font-size: 75%;
    opacity: 0.05;
  }

  input.imitatefocus::-webkit-input-placeholder {
    -webkit-transform: translateY(-125%);
    transform: translateY(-125%);
    opacity: 0.05;
  }

  @include mobile {
    border: none;
    background: none;
    outline: none;
    float: left;
    color: $color-greytext;
    font-size: 16px;
    transition: 0.4s;
    line-height: 2.5rem;
    width: 0rem;
  }
  @include tablet {
    padding: 0 2rem;
  }
}

select {
  -webkit-appearance: auto;
}

.categorias option {
  color: $color-grey-darker;
  font-family: $font-primary, Arial;
}

@include mobile {
  .search-container:matches(:hover, :focus-within) > .search-text {
    width: 12rem;
    padding: 0 1rem;
  }

  .search-text:hover > .search-link {
    align-self: right;
  }
}
</style>
