<script lang="ts">
import { ref } from 'vue'

import StreamPreviewVue from '@/components/StreamPreview.vue'
import ErrorMessage from '@/components/ErrorMessage.vue'
import LoadingScreen from '@/components/LoadingScreen.vue'
import CategoryPreview from '@/components/CategoryPreview.vue'

import { getEndpoint } from '@/mixins'
import type { CategoryPreview as CategoryPreviewInterface } from '@/types'

export default {
  inject: ['protocol'],
  async setup() {
    let data = ref<CategoryPreviewInterface[]>()
    let status = ref<'ok' | 'error'>()

    return {
      data,
      status,
      filterTags: '',
      following: ref([])
    }
  },
  methods: {
    filterSearches(toFilter: string) {
      const categories = this.$refs.categoryItem
      const wantedTags: string[] = toFilter
        .toLowerCase()
        .split(',')
        .filter((v) => v.toLowerCase())

      for (let category of categories as any) {
        let tagElements = category.getElementsByTagName('span')
        let tags = []

        for (let tag of tagElements) {
          tags.push(tag.innerText.toLowerCase())
        }

        // Create sets from the arrays
        const [set1, set2] = [new Set(wantedTags), new Set(tags)]
        const common = [...set1].filter((x) => set2.has(x))

        if (common.length === wantedTags.length) {
          category.style.display = ''
        } else if (wantedTags[0] === '') {
          category.style.display = ''
        } else {
          category.style.display = 'none'
        }
      }
    },
    async getNextCategory() {
      let bottomOfWindow =
        document.documentElement.scrollTop + window.innerHeight ===
        document.documentElement.offsetHeight
      if (bottomOfWindow && this.data) {
        const cursor = this.data[this.data.length - 1].cursor
        if (!cursor) return
        const res = await getEndpoint('api/discover?cursor=' + cursor)

        for (let category of res) {
          this.data.push(category)
        }
      }
    }
  },
  async mounted() {
    window.onscroll = this.getNextCategory

    let following = localStorage.getItem('following')
    if (following) {
      this.following = JSON.parse(following)
    } else {
      this.following = []
    }

    await getEndpoint('api/discover')
      .catch(() => {
        this.status = 'error'
      })
      .then((data: CategoryPreviewInterface[]) => {
        this.data = data
      })
  },
  components: {
    StreamPreviewVue,
    ErrorMessage,
    LoadingScreen,
    CategoryPreview
  }
}
</script>

<template>
  <loading-screen v-if="!data && status != 'error'"></loading-screen>
  <error-message v-else-if="status == 'error'"></error-message>

  <div v-else-if="data" class="max-w-5xl mx-auto">
    <div v-if="following.length > 0" class="p-2 text-white">
      <h1 class="font-bold text-5xl">Following</h1>
      <p class="text-xl">Streamers you follow</p>
      <ul class="flex overflow-x-scroll space-x-2 flex-nowrap h-[22rem] items-center">
        <li
          v-for="streamer in following"
          :key="streamer"
          class="inline-block"
        >
          <stream-preview-vue :name="streamer"></stream-preview-vue>
        </li>
      </ul>
    </div>

    <div class="p-2 text-contrast">
      <h1 class="font-bold text-5xl">{{ $t('home.discover') }}</h1>
      <p class="text-xl">{{ $t('home.discoverDescription') }}</p>

      <div class="pt-5 inline-flex">
        <p class="mr-2 font-bold">{{ $t('home.tagDescription') }}</p>
        <div class="relative">
          <label for="searchBar" class="hidden">{{ $t('main.search') }}</label>
          <v-icon name="io-search-outline" class="absolute my-auto inset-y-0 left-2"></v-icon>
          <input
            type="text"
            id="searchBar"
            name="searchBar"
            :placeholder="$t('main.search')"
            v-model="filterTags"
            @keypress="filterSearches(filterTags)"
            @keyup="filterSearches(filterTags)"
            class="rounded-md p-1 pl-8 placeholder:text-white"
          />
        </div>
      </div>
    </div>

    <ul ref="categoryList">
      <li
        v-for="category in data"
        :key="category.name"
        ref="categoryItem"
        class="inline-flex m-2 hover:scale-105 transition-transform"
      >
        <category-preview :category-data="category"></category-preview>
      </li>
    </ul>
  </div>
</template>
