<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[] = []

      if (this.isFollowing && follows) {
        const index = JSON.parse(follows).indexOf(username)
        if (index === -1) return
        parsedFollows = parsedFollows.splice(index, 1)
        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-white text-sm font-bold p-2 py-1 rounded-md bg-purple-600"
  >
    <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>
