<script lang="ts">
import { inject } from 'vue'
export interface Stream {
  tags: string[]
  title: string
  topic: string
  startedAt: number
  viewers: number
  preview: string
  streamer: {
    pfp: string
    name: string
  }
}

export default {
  props: {
    stream: {},
    name: {
      type: String
    }
  },
  async setup(props) {
    const protocol = inject('protocol')

    let streamData: Stream | null = null
    if (!props.stream && props.name) {
      const streamDataFetch = await fetch(
        `${protocol}${import.meta.env.VITE_BACKEND_DOMAIN}/api/users/${props.name}`
      )
      const data = (await streamDataFetch.json()).data

      if (data.stream) {
        data.stream.streamer = { name: props.name, pfp: data.pfp }
        streamData = data.stream
      }
    } else {
      streamData = props.stream as Stream
    }

    const frontend_url = protocol + import.meta.env.VITE_INSTANCE_DOMAIN

    return {
      frontend_url,
      streamData,
      protocol
    }
  },
  methods: {
    abbreviate(text: number) {
      return Intl.NumberFormat('en-US', {
        //@ts-ignore
        notation: 'compact',
        maximumFractionDigits: 1
      }).format(text)
    }
  }
}
</script>

<template>
  <div v-if="streamData">
    <div class="bg-ctp-crust rounded-lg w-[23rem] md:w-[27rem]">
      <RouterLink :to="'/' + streamData.streamer.name">
        <img :src="streamData.preview" class="rounded-lg rounded-b-none" />
      </RouterLink>
      <div class="text-white p-2 inline-flex space-x-2 w-full h-16">
        <div class="inline-flex">
          <div class="inline-flex">
            <img :src="streamData.streamer.pfp" class="rounded-full mr-2" />
            <div class="w-full">
              <p class="font-bold w-[18rem] md:w-[22.9rem] truncate">{{ streamData.title }}</p>
              <div class="inline-flex w-full justify-between">
                <p class="text-gray-300">{{ streamData.streamer.name }}</p>
                <p class="self-end float-right">
                  <v-icon name="io-person"></v-icon> {{ abbreviate(streamData.viewers) }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
