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

export default {
  props: {
    username: {
      type: String,
      default() {
        return ''
      }
    }
  },
  setup() {
    return {
      isFollowing: ref(false)
    }
  },
  methods: {
    followStreamer() {
      const username = this.$props.username
      const follows = localStorage.getItem('following') || "[]"

      let parsedFollows: string[] = JSON.parse(follows)

      if (follows?.includes(username)) {
        const index = parsedFollows.indexOf(username)
        console.log(index)
        if (index === -1) return
        parsedFollows = parsedFollows.splice(index, 1)
        console.log(parsedFollows)
        this.isFollowing = false
      } else {
        if (follows) parsedFollows = JSON.parse(follows)
        parsedFollows.push(username)
        this.isFollowing = true
      }

      localStorage.setItem('following', JSON.stringify(parsedFollows))
    }
  },
  mounted() {
    let followerData = localStorage.getItem('following')
    if (!followerData) return

    let following: string[] = JSON.parse(followerData)
    const isFollower = following.includes(this.$props.username)

    if (isFollower) {
      this.isFollowing = true
    }
  }
}
</script>

<template>
  <button
    ref="followButton"
    @click="followStreamer"
    class="text-contrast text-sm font-bold p-2 py-1 rounded-md bg-purple"
  >
    <v-icon name="bi-heart-fill" scale="0.85"></v-icon>
    <span v-if="isFollowing"> {{ $t('streamer.unfollow') }} </span>
    <span v-else> {{ $t('streamer.follow') }} </span>
  </button>
</template>
