<template>
  <div
    class="class-selection"
    v-if="selectedItem"
  >
    <div
      data-cy="class-selection"
      class="class-selection__selected-class selected-class"
      @click.stop="toggle()"
    >
      <span class="selected-class__text"> {{ selectedItem.name }}</span>
      <ChevronDown class="selected-class__dropdown-icon" :class="{'rotate-chevron': showPopover}"
      />
    </div>
    <transition name="scaleY">
      <WidgetPopover
        :mobile="mobile"
        class="class-selection__popover"
        v-if="showPopover"
        @hide-me="showPopover = false"
      >
        <li
          :label="selectedItem.name"
          :item="selectedItem"
          data-cy="class-selection-entry"
          class="popover-links__link popover-links__link--large"
          v-for="item in items"
          :key="item.id"
          @click="updateSelectedItem(item)"
        ><span>{{ item.name }}</span>
        </li>


      </WidgetPopover>
    </transition>
  </div>
</template>

<script setup lang="ts">
  import WidgetPopover from '@/components/ui/WidgetPopover.vue';
  import {ref} from "vue";
  import ChevronDown from "@/components/icons/ChevronDown.vue";

  const props = defineProps<{
    selectedItem: Object,
    items: Object[],
  }>();

  let showPopover = ref(false)

  function toggle() {
    showPopover.value = !showPopover.value;
  }

  function updateSelectedItem(item: Object) {
    emit('update:selectedItem', item);
    showPopover.value = false;
  }

  const emit = defineEmits(['update:selectedItem']);

</script>

<style scoped lang="scss">
  @import 'styles/helpers';

  .class-selection {
    position: relative;
    cursor: pointer;
    margin-bottom: $medium-spacing;
    border-radius: 4px;
    width: 200px;

    &__popover {
      white-space: nowrap;
      top: 100%;
      left: 0;
      transform-origin: top;
    }
  }

  .selected-class {
    width: 100%;
    box-sizing: border-box;
    padding: $small-spacing 0;

    display: flex;
    align-items: center;
    justify-content: space-between;
    border: solid silver 1px;

    border-radius: 4px;
    padding: 12px;


    &__text {
      @include small-text;
      margin-right: $small-spacing;

    }

    &__dropdown-icon {
      width: 20px;
      height: 20px;
      transition: transform 0.3s ease;

      fill: #139EE0;

      &.rotate-chevron { // This class will be applied when showPopover is true
        transform: rotate(180deg);
      }
    }
  }

  .widget-popover {
    width: 100%;
    border-radius: 12px;
    margin-top: 4px;

    .popover-links__link {
      &:hover {
        background-color: #efefef;
      }
    }
  }

  .scaleY-enter-active,
  .scaleY-leave-active {
    transition: transform 0.3s;
  }

  .scaleY-enter,
  .scaleY-leave-to
  {
    transform: scaleY(0);
  }
</style>
