<template>
  <div class="site-selector-container">
    <div
      class="site-selector"
      :class="{ rotate: showSitesDropdown }"
      @click="handleClick"
    >
      <IconText icon="arrow-right" size="xs" direction="row reverse">
        <p>{{ currentSite.title }}</p>
      </IconText>
    </div>

    <div v-if="showSitesDropdown" class="dropdown">
      <div
        v-for="(site, index) in sites.filter(
          site => site.uuid !== currentSite.uuid
        )"
        :key="index"
        class="dropdown-item"
      >
        <p @click="attributeSite(site)">{{ site.title }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import SitesMixin from '~instanceCustom/mixins/sites'
import { storage } from '@inside-library/helpers/Storage'
import { IconText } from 'inside-collection/atoms'

export default {
  name: 'site-selector',
  components: { IconText },
  mixins: [SitesMixin],
  data() {
    return {
      sites: [],
      currentSite: {},
      showSitesDropdown: false
    }
  },
  async mounted() {
    this.sites = await this.$_fetchUserSites()
    this.currentSite = storage.get('site')
  },
  methods: {
    handleClick() {
      if (this.sites.length > 1) {
        this.showSitesDropdown = !this.showSitesDropdown
      }
    },
    attributeSite(site) {
      /*
       * Save in local storage
       */
      this.currentSite = site
      this.setStoreAction('setUserInformation', {
        key: 'site',
        value: this.currentSite
      })

      /*
       * Reload and remove hash in URL
       */
      window.location.href = '/'
    }
  }
}
</script>

<style lang="scss">
.site-selector-container {
  position: relative;
  width: 160px;
  height: 2rem;

  p {
    color: var(--color-primary);
    font-size: var(--font-size-labor);
  }

  .site-selector {
    cursor: pointer;
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 160px;
    background-color: var(--color-light);
    transition: all 0.3s ease;
    z-index: 10;
    border-bottom: 2px solid var(--color-primary);
    padding-bottom: var(--spacing-xs);

    svg {
      fill: var(--color-primary-300);

      @include transition(all 0.3s);
    }

    .ds-icon-text-container {
      justify-content: space-between;
      width: 100%;
    }
  }

  .site-selector.rotate svg {
    transform: rotate(90deg) !important;
  }

  .dropdown {
    width: 100%;
    padding: var(--spacing-m);
    margin-top: var(--spacing-l);
    background-color: var(--color-light);
    overflow: hidden;
  }

  .dropdown-item {
    text-align: left;
    margin-bottom: var(--spacing-xs);

    p {
      cursor: pointer;
      color: var(--color-primary-300);

      @include transition(color 0.3s);

      &:hover {
        color: var(--color-primary);
      }
    }
  }
}
</style>
