<template>
  <div
    v-if="user"
    class="mc-sidebar-user"
    :class="{ 'is-open': open, 'is-close': !open }"
    @click="toggle"
  >
    <button
      :aria-expanded="open && isExpanded"
      class="mc-sidebar-user__header"
      aria-controls="user-content"
    >
      <span class="mc-sidebar-user__header__picture">
        <img
          v-if="!!computedSrc"
          class="base64"
          style="display: block; width: auto; height: 48px; max-width: 48px"
          :alt="`${user.firstName} ${user.lastName}`"
          :src="computedSrc"
        />
        <MIcon
          v-else
          name="AccountProfileView24"
          color="white"
          style="width: 24px; height: 24px"
        />
      </span>
      <div v-if="open" style="display: flex; width: 100%">
        <p class="mc-sidebar-user__header__information">
          <span class="mc-sidebar-user__header__information__identity">
            {{ user?.firstName || '' }}
            {{ user?.lastName || '' }}
          </span>
          <span
            v-if="user.title"
            class="mc-sidebar-user__header__information__title"
          >
            {{ capitalizeTheFirstLetterOfEachWord(user.title) }}
          </span>
        </p>
        <span
          v-if="userFeatures?.length"
          class="mc-sidebar-user__header__information__icon"
        >
          <MIcon
            v-if="open && !isExpanded"
            name="ControlMore16"
            color="white"
            style="width: 16px; height: 16px"
          />
          <MIcon
            v-else
            name="ControlLess16"
            color="white"
            style="width: 16px; height: 16px"
          />
        </span>
      </div>
    </button>
    <ul
      v-if="userFeatures?.length"
      id="user-content"
      ref="content"
      class="mc-sidebar-user__content is-close"
    >
      <li
        v-for="(feature, i) in userFeatures"
        :key="i"
        @click.stop="featureClick(feature)"
      >
        <MSidebarFeature :feature="feature" :open="open" :selected="selected" />
      </li>
    </ul>
  </div>
</template>

<script>
import MIcon from '../icon/MIcon.vue';
import MSidebarFeature from './MSidebarFeature.vue';

export default {
  name: 'MSidebarNavigationUser',
  components: { MIcon, MSidebarFeature },
  props: {
    /**
     * Same object as the one passed to the `user` prop in the **MSidebar.vue** component.
     */
    user: {
      type: Object,
      default: () => ({}),
    },
    /**
     * Same array as the one passed to the `userFeatures` prop in the **MSidebar.vue** component.
     */
    userFeatures: {
      type: Array,
      default: () => [],
    },
    /**
     * Determines the open or closed state of the sidebar
     */
    open: {
      type: Boolean,
      default: false,
    },
    /**
     * Same object as the one passed to the `modelValue` prop in the **MSidebar.vue** component.
     */
    selected: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['code-changed', 'toggle-sidebar'],
  data() {
    return {
      isExpanded: false,
    };
  },
  computed: {
    computedSrc() {
      if (this.user.imageSrc) {
        return this.user.imageSrc;
      } else if (this.user.imageBase64) {
        return `data:image/png;base64, ${this.user.imageBase64}`;
      } else {
        return null;
      }
    },
  },
  watch: {
    open() {
      this.updateContentCSS();
    },
    isExpanded() {
      this.updateContentCSS();
    },
  },
  methods: {
    toggle() {
      if (!this.open) {
        this.$emit('toggle-sidebar', true);
        this.isExpanded = true;
      } else {
        this.isExpanded = !this.isExpanded;
      }
    },
    capitalizeTheFirstLetterOfEachWord(words) {
      let separateWord = words.toLowerCase().split(' ');
      for (let i = 0; i < separateWord.length; i++) {
        separateWord[i] =
          separateWord[i].charAt(0).toUpperCase() +
          separateWord[i].substring(1);
      }
      return separateWord.join(' ');
    },
    featureClick(feature) {
      if (!feature.disabled) {
        this.$emit('code-changed', feature.code);
      }
    },
    updateContentCSS() {
      if (this.$refs.content) {
        this.$refs.content.style.height = '';
        this.$refs.content.style.transition = 'none';
        const startHeight = window.getComputedStyle(this.$refs.content).height;

        this.$refs.content.classList.add(
          this.open && this.isExpanded ? 'is-open' : 'is-close',
        );
        this.$refs.content.classList.remove(
          this.open && this.isExpanded ? 'is-close' : 'is-open',
        );

        const height = window.getComputedStyle(this.$refs.content).height;
        this.$refs.content.style.height = startHeight;

        // wait until the next frame so that everything has time to update before starting the transition
        requestAnimationFrame(() => {
          this.$refs.content.style.transition = '';
          requestAnimationFrame(() => {
            this.$refs.content.style.height = height;
          });
        });

        // Clear the saved height values after the transition
        const handler = () => {
          this.$refs.content.style.height = '';
          this.$refs.content.removeEventListener('transitionend', handler);
        };

        this.$refs.content.addEventListener('transitionend', handler);
      }
    },
  },
};
</script>

<style scoped lang="scss">
$color-grey: #5b737d;
$selected-Link: #007f8c;

@mixin transition($transition...) {
  -moz-transition: $transition;
  -o-transition: $transition;
  -webkit-transition: $transition;
  transition: $transition;
}

.mc-sidebar-user {
  left: 0;
  right: 0;
  bottom: 0;
  position: absolute;
  background: #264653;

  &__header {
    display: flex;
    align-items: center;
    background: none;
    border: none;
    color: white;
    font-size: inherit;
    font-family: inherit;
    text-align: initial;
    margin: 0;
    width: 100%;
    overflow: hidden;
    outline: none;

    &:focus-visible,
    &:hover {
      cursor: pointer;

      .mc-sidebar-user__header__information__icon {
        background: #082435;
      }
    }

    &__picture {
      display: flex;
      align-items: center;
      justify-content: center;
      background: $color-grey;
      border-radius: 24px;
      width: 48px;
      min-width: 48px;
      height: 48px;
      overflow: hidden;

      img {
        display: block;
        object-fit: cover;
        object-position: top center;
        width: 100%;
      }
    }

    &__information {
      justify-content: space-around;
      display: flex;
      flex-direction: column;
      flex: 1;
      margin: 0;
      margin-left: 8px;
      height: 40px;

      &__icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 4px;
      }

      &__identity {
        font-size: 16px;
        font-weight: bold;
      }

      &__title,
      &__identity {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 176px;
      }
    }
  }

  &__content {
    list-style-type: none;
    padding: 0;
    overflow: hidden;
    margin: -8px 0px 24px 0px;
    @include transition(all 300ms ease-in-out);

    &.is-close {
      height: 0;
      margin: 0;
    }

    .is-open {
      height: auto;
    }
  }

  &.is-close {
    .mc-sidebar-user__header {
      @include transition(padding 300ms ease-in-out);

      padding: 12px 8px;
      margin: 8px 0;
    }
  }

  &.is-open {
    .mc-sidebar-user__header {
      @include transition(padding 300ms ease-in-out);

      padding: 12px 24px 12px 32px;
      margin: 8px 0;
    }
  }
}
</style>
