<template>
  <div class="dropdown-button" ref="focusElement">
    <div class="wrapper dropdown-wrapper no-outline" tabindex="1">
      <SpaceButton class="primary" tabindex="1" @click="toggleActive()">
        <div class="icon fill-blue">
          <SpIcon v-if="active" name="sp-chevron-up" />

          <SpIcon v-else name="sp-chevron-down" />
        </div>
        <span>{{ title }}</span>
        <span></span>
      </SpaceButton>
      <div class="dropdown h600" v-if="active" @click="setActive(false)">
        <slot />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useFocusOut } from "@/hooks";
export default defineComponent({
  props: {
    title: {
      type: String,
      default: "Button Title",
    },
  },
  setup({ title }) {
    const { focusOutElement, active, focusElement } = useFocusOut();
    focusOutElement.value = ".wrapper";

    const setActive = (status: boolean): void => {
      active.value = status;
    };

    const toggleActive = (): void => {
      active.value = !active.value;
    };

    return {
      title,
      active,
      toggleActive,
      setActive,
      focusElement,
    };
  },
});
</script>

<style lang="scss">
.dropdown-button {
  .wrapper {
    position: relative;
  }

  .dropdown {
    position: absolute;
    width: 100%;
    top: calc(100% + 8px);
    border-radius: var(--form-border-radius);
    overflow: hidden;
    background-color: var(--background-primary);
    box-shadow: 0 4px 16px rgba(0, 162, 183, 0.2);
    z-index: 5;

    ul {
      --padding-y: 16px;
      --padding-x: 24px;
      --padding-extra: 8px;
      --margin-icon: 16px;

      li {
        padding: var(--padding-y) var(--padding-x);
        background-color: var(--background-primary);
        transition: background 0.3s ease;
        display: flex;
        align-items: center;
        cursor: pointer;

        .icon {
          margin-right: var(--margin-icon);

          svg path {
            fill: var(--blue);
          }
        }

        &:first-child {
          padding-top: calc(var(--padding-y) + var(--padding-extra));
        }

        &:last-child {
          padding-bottom: calc(var(--padding-y) + var(--padding-extra));
        }

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