<template>
  <div>
    <Title tag="h4">{{ folder.title }}</Title>

    <div v-show="subFolders.length" class="pt-l">
      <ul>
        <li
          v-for="subFolder in subFolders"
          :key="subFolder.uuid"
          class="subfolder-link mb-s"
          @click="goToFolder(subFolder.slug[0])"
        >
          <Icon
            :icon="
              subFolder.icon && JSON.parse(subFolder.icon).name
                ? JSON.parse(subFolder.icon).name
                : 'arrow-right'
            "
            :color="brandColor"
            class="mr-m"
          />

          {{ subFolder.title }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { Title, Icon } from 'inside-collection/atoms'

import { http } from '@inside-library/helpers/Http'
import { formatHref } from '@inside-library/helpers/Langs'
import { storage } from '@inside-library/helpers/Storage'

export default {
  name: 'FolderBlockItem',
  components: { Title, Icon },
  props: {
    folder: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      subFolders: []
    }
  },
  computed: {
    brandColor() {
      return storage.get('brand')?.primary_color
    }
  },
  async beforeMount() {
    this.subFolders = await this.fetchSubfolders()
  },
  methods: {
    async fetchSubfolders() {
      try {
        const { data } = await http.get('content/folders', {
          fields: [
            'uuid',
            'title',
            'slug',
            'admin',
            'content_type',
            'icon',
            { pid: ['uuid', 'title', 'slug'] }
          ],
          filters: { 'pid:eq': this.folder.uuid, sort: 'weight:asc' }
        })

        return data
      } catch (err) {
        throw new Error(err)
      }
    },
    goToFolder(slug) {
      this.$router.push(
        formatHref(
          {
            name: 'GedPageCustom',
            params: {
              folder: this.folder.slug[0],
              subFolder: slug
            }
          },
          this.$_currentLang
        )
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.subfolder-link {
  display: flex;
  align-items: center;
  color: var(--color-text);
  font-size: var(--font-size-h5);
  font-family: var(--font-primary);
  cursor: pointer;
}
</style>
