<script setup lang="ts">
import MediaShowcase from '@/components/MediaShowcase.vue'
import type { Records, View } from '@/jfapi'
import { onBeforeMount, ref } from 'vue'
import jfapi from '@/jfapi'
import { useRoute } from 'vue-router'

const views = ref<View[]>()
onBeforeMount(async () => {
  const viewlist = ref<Records<View> | null>()
  const userid = localStorage.getItem('jf_userid')
  const host = localStorage.getItem('jf_host')
  const viewstring = localStorage.getItem('jf_views')
  if (viewstring !== null && viewstring !== 'undefined' && viewstring !== '') {
    console.log('viewstring is valid')
    views.value = JSON.parse(viewstring)
  } else {
    viewlist.value = await jfapi.LoadViews(userid ? userid : '')
    if (viewlist.value === null) {
      // error
    } else {
      views.value = viewlist.value.Items
      localStorage.setItem('jf_views', JSON.stringify(viewlist.value ? viewlist.value.Items : ''))
    }
  }
  console.log('Host =>', host)
  if (window.location.pathname.toLowerCase() !== '/login') {
    if (host === null) {
      window.location.href = '/login'
    } else if (viewlist.value === null) {
      window.location.href = '/login'
    }
  }
  console.log(views.value)
})

const route = useRoute()
const homeIsActive = () => {
  return route.path === '/home'
}
const viewIsActive = (id: string) => {
  return route.path.split('/')[2] === id
}
</script>

<template>
  <main>
    <MediaShowcase />
    <div class="home-nav">
      <RouterLink
        to="/home"
        class="home-nav-item"
        :class="homeIsActive() ? 'active' : ''"
        key="home"
        >Home</RouterLink
      >
      <RouterLink
        class="home-nav-item"
        v-for="view in views"
        :to="`/view/${view.Id}`"
        :key="view.Id"
        :class="viewIsActive(view.Id) ? 'active' : ''"
        >{{ view.Name }}</RouterLink
      >
    </div>
    <div class="media">
      <RouterView v-slot="{ Component, route }"
        ><component :is="Component" :key="route.path"
      /></RouterView>
    </div>
    <div class="footer"></div>
  </main>
</template>

<style scoped>
a {
  color: var(--color-text);
  text-decoration: none;
}
.home-nav {
  display: flex;
  justify-content: center;
  margin-top: 1.5em;
  gap: 3em;
  align-items: center;
}
.home-nav-item:hover {
  cursor: pointer;
  color: var(--color-text-faded);
}
.home-nav-item.active {
  padding: 0.4em 1.5em;
  background-color: var(--color-text);
  border-radius: 15px;
  color: var(--color-text-dark);
  font-weight: 600;
}
.home-nav-item.active:hover {
  background-color: var(--color-text-faded);
}
.media {
  margin: 0 10%;
}
.footer {
  height: 100px;
}
</style>
