<template>
    <button
      id="user-menu-button"
      @click="openModal"
      type="button"
      class="inline-flex h-8 items-center rounded-lg bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700 dark:focus:ring-gray-700"
    >
      <span class="sr-only" data-i18n="nav.open_user_menu">{{ props.sr || 'Open user menu' }}</span>
      <span style="pointer-events: none;" class="inline-flex items-center justify-center">
        <svg class="h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 17 14">
          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 1h15M1 7h15M1 13h15"></path>
        </svg>
      </span>
    </button>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
const props = defineProps<{ target?: string, pos?: string, sr?:string}>();

const allowedPositions = ['tr', 'tl', 'br', 'bl'];

const safePos = computed(() => {
  if (props.pos && allowedPositions.includes(props.pos)) {
    return props.pos;
  }
  return 'br';
});

onMounted(() => {
  if (props.target) {
    const elem = document.getElementById(props.target);
    if (elem) {
      elem.style.position = 'absolute';
      elem.style.left = `-9999px`;
      elem.setAttribute('isopen', 'false');
    }
  }
});

const openModal = (event: MouseEvent) => {
  event.stopPropagation();
  if (props.target) {
    const elem = document.getElementById(props.target);
    if (elem) {
      if (elem.getAttribute('isopen') === 'false') {
        const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
        const myRect = elem.getBoundingClientRect();
        
        if(safePos.value.includes('b')) {
          elem.style.top = `${rect.bottom - 4}px`;
        }else {
          elem.style.top = `${rect.top - myRect.height}px`;
        }
        if(safePos.value.includes('r')) {
          elem.style.left = `${rect.right - myRect.width + 2}px`;
        }else { 
          elem.style.left = `${rect.left}px`;
        }
        elem.setAttribute('isopen', 'true' );
      }else {
        elem.style.left = `-9999px`
        elem.setAttribute('isopen', 'false');
      }
      
   }
  }
};
</script>
