<template>
  <div class="wt-context-menu">
    <wt-popover
:visible="visible" :disabled="disabled" :pt="pt" unstyled placement="bottom-end"
      class="wt-context-menu__floating-wrapper">
      <template #activator="{ toggle, show }">
        <slot name="activator" v-bind="{ toggle, show }" />
      </template>

      <template #default="{ hide }">
        <ul
:style="`width: ${width}; min-width: ${minWidth}; max-width: ${maxWidth};`"
          class="wt-context-menu__menu typo-body-2">
          <li v-for="(option, index) of options" :key="index" class="wt-context-menu__option-wrapper">
            <a
:class="[{ 'wt-context-menu__option--disabled': option.disabled }]" class="wt-context-menu__option"
              href="#" @click.prevent="handleOptionClick({ option, index, hide })">
              <slot name="option" v-bind="option">
                {{ option.text || option }}
              </slot>
            </a>
          </li>
        </ul>
      </template>
    </wt-popover>
  </div>
</template>

<script setup>
const props = defineProps({
	options: {
		type: Array,
		required: true,
		description: '[{ text, disabled, ... anything you need }]',
	},
	visible: {
		type: Boolean,
		default: false,
	},
	width: {
		type: [
			String,
		],
		default: 'auto',
	},
	minWidth: {
		type: [
			String,
		],
		default: '160px',
	},
	maxWidth: {
		type: [
			String,
		],
		default: '300px',
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	pt: {
		type: Object,
		default: () => null,
	},
	tooltipTriggers: {
		type: Array,
		default: () => [
			'click',
			'touch',
		],
	},
});

const emit = defineEmits([
	'click',
	'update:visible',
]);

function handleOptionClick({ option, index, hide }) {
	emit('click', {
		option,
		index,
	});
	hide();
}
</script>

<style scoped>
.wt-context-menu {
  line-height: 0;
}

.wt-context-menu.wt-tooltip :deep(.wt-context-menu__floating-wrapper) {
  padding: 0;
}

.wt-context-menu__menu {
  z-index: 1;
  transition: var(--transition);
  box-shadow: var(--box-shadow);
  border-radius: var(--border-radius);
  background-color: var(--wt-context-menu-background-color);
}

.wt-context-menu__option-wrapper:first-of-type {
  border-radius: var(--border-radius) var(--border-radius) 0 0;
}

.wt-context-menu__option-wrapper:last-of-type {
  border-radius: 0 0 var(--border-radius) var(--border-radius);
}

.wt-context-menu__option-wrapper:only-of-type {
  border-radius: var(--border-radius);
}

.wt-context-menu__option {
  display: block;
  transition: var(--transition);
  cursor: pointer;
  padding: var(--wt-context-menu-option-padding);
  color: var(--wt-context-menu-option-text-color);
}

.wt-context-menu__option:hover {
  background-color: var(--wt-context-menu-option-background-hover-color);
}

.wt-context-menu__option--disabled {
  background-color: var(--wt-context-menu-option-background-disabled-color);
  pointer-events: none;
  color: var(--wt-context-menu-option-text-disabled-color);
}
</style>
