<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.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'
        }
      }
    },
    getNextCategory() {
      window.onscroll = async () => {
        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 fetch(
            `${this.protocol}${import.meta.env.SAFETWITCH_BACKEND_DOMAIN}/api/discover/?cursor=${cursor}`
          )
          if (!res.ok) {
            throw new Error('Failed to fetch data')
          }
          const resData = await res.json()

          for (let category of resData.data) {
            this.data.push(category)
          }
        }
      }
    }
  },
  async mounted() {
    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 flex-nowrap h-80 space-x-1">
        <li
          v-for="streamer in following"
          :key="streamer"
          class="inline-block hover:scale-105 transition-transform"
        >
          <stream-preview-vue :name="streamer"></stream-preview-vue>
        </li>
      </ul>
    </div>

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

      <div class="pt-5 inline-flex text-white">
        <p class="mr-2 font-bold text-white">{{ $t("home.tagDescription") }}</p>
        <form 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"
            @keyup="filterSearches(filterTags)"
            class="rounded-md p-1 pl-8 text-black bg-neutral-500 placeholder:text-white"
          />
        </form>
      </div>
    </div>

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