<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, followersStreaming } from '@/mixins'
import type { CategoryPreview as CategoryPreviewInterface } from '@/types'
import { getFollows } from '@/settingsManager'
import VueTitle from '@/components/VueTitle.vue'

export default {
  async setup() {
    const data = ref<CategoryPreviewInterface[]>()
    const status = ref<'ok' | 'error'>()
    const followingStreaming = ref<string[]>([])
    const following = ref<string[]>([])

    return {
      data,
      status,
      filterTags: '',
      following,
      followingStreaming
    }
  },
  methods: {
    filterSearches(toFilter: string) {
      const categories = this.$refs.categoryItem
      const wantedTags = toFilter
        .toLowerCase()
        .split(',')
        .map((tag) => tag.trim())
        .filter((tag) => tag)

      for (const category of categories as HTMLElement[]) {
        const tagElements = category.getElementsByTagName('span')
        const categoryTags = Array.from(tagElements, (el) => el.innerText.toLowerCase())

        const tagInputIsValid = wantedTags.length > 0
        if (tagInputIsValid && !categoryTags.some((r) => wantedTags.includes(r))) {
          category.style.display = 'none'
        } else {
          category.style.display = 'block'
        }
      }
    },
    async getNextCategory() {
      const bottomOfWindow =
        document.documentElement.scrollTop + window.innerHeight ===
        document.documentElement.offsetHeight
      if (bottomOfWindow && this.data) {
        const cursor = this.data[this.data.length - 1]?.cursor ?? null
        if (!cursor) return

        const res = await getEndpoint('api/discover?cursor=' + cursor)

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

    // get discover page
    await getEndpoint('api/discover')
      .catch(() => {
        this.status = 'error'
      })
      .then((data: CategoryPreviewInterface[]) => {
        this.data = data
      })

    this.following = await getFollows()
    this.followingStreaming = []

    // There is a max of 35 streamers per request.
    for (let i = 0; i <= Math.floor(this.following.length / 35); i++) {
      const liveStreamers = await followersStreaming(this.following, i)
      this.followingStreaming = [...this.followingStreaming, ...liveStreamers]
    }
  },
  components: {
    StreamPreviewVue,
    ErrorMessage,
    LoadingScreen,
    CategoryPreview,
    VueTitle
  }
}
</script>

<template>
  <vue-title title="Discover"></vue-title>
  <loading-screen v-show="!data && status != 'error'"></loading-screen>
  <div v-show="status === 'error'">
    <error-message></error-message>
  </div>

  <div v-show="data" class="max-w-5xl grow w-[100vw] mx-auto">
    <div v-if="following && following.length > 0" class="p-2 text-contrast mb-4">
      <h1 class="font-bold text-5xl">{{ $t('home.following') }}</h1>
      <p class="text-xl mb-2">{{ $t('home.streamersYouFollow') }}</p>
      <ul
        class="overflow-x-auto whitespace-nowrap flex grid grid-rows-2 auto-cols-min gap-2 grid-flow-col"
      >
        <li v-for="streamer in followingStreaming" :key="streamer" class="mr-2">
          <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"
            @keyup="filterSearches(filterTags)"
            class="rounded-md p-1 pl-8 text-primary"
          />
        </div>
      </div>
    </div>

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