<template>
  <div
    class="dropdown"
    v-if="selectedItem"
  >
    <div
      data-cy="dropdown"
      class="dropdown__selected-item"
      @click.stop="toggle()"
    >
      <span class="dropdown__selected-item-text"> {{ selectedItem.name }}</span>
      <ChevronDown class="dropdown__dropdown-icon" :class="{'rotate-chevron': showPopover}"
      />
    </div>
    <transition name="scaleY">
      <WidgetPopover
        class="dropdown__popover"
        v-if="showPopover"
        @hide-me="showPopover = false"
      >
        <li
          :label="selectedItem.name"
          :item="selectedItem"
          data-cy="dropdown-item"
          class="popover-links__link popover-links__link--large"
          v-for="item in items"
          :key="item.id"
          @click="updateSelectedItem(item)"
        >{{ item.name }}
        </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";

  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';

  .dropdown {
    position: relative;
    cursor: pointer;
    margin-bottom: $medium-spacing;
    border-radius: $input-border-radius;


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

    &__selected-item {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border: solid $color-silver 1px;
      border-radius: $input-border-radius;
      padding: 12px;
    }

    &__selected-item-text {
      @include small-text;
      margin-right: $small-spacing;
    }

    &__dropdown-icon {
      width: $default-icon-dimension;
      height: $default-icon-dimension;
      transition: transform 0.3s ease;
      fill: $color-brand;

      &.rotate-chevron {
        transform: rotate(180deg);
      }
    }

    &__popover {
      width: 100%;
      border-radius: $default-border-radius;
      margin-top: 4px;

      .popover-links__link {
        &:hover {
          background-color: $color-silver-light;
        }
      }
    }
  }


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

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