<script setup>

import { computed, useTemplateRef,ref } from 'vue';
import { Menu, Button, ButtonGroup } from '@cloudron/pankow';

const props = defineProps({
  actions: {
    type: Array,
    default: () => [],
  },
});

const quickActions = computed(() => {
  const visibleActions = props.actions.filter(a => !(typeof a.visible !== 'undefined' && !a.visible) && !a.separator);
  if (visibleActions.length <= 2) return visibleActions;

  return visibleActions.filter(a => a.quickAction);
});

const visibleActionCount = computed(() => {
  return props.actions.filter(a => !(typeof a.visible !== 'undefined' && !a.visible) && !a.separator).length;
});

const isMenuOpen = ref(false);

const menuElement = useTemplateRef('menuElement');
function onMenu(event) {
  isMenuOpen.value = true;
  menuElement.value.open(event, event.currentTarget);
}

</script>

<template>
  <div class="action-bar" :class="{ 'is-menu-open': isMenuOpen }">
    <Menu ref="menuElement" :model="actions" @close="isMenuOpen = false" />
    <ButtonGroup class="quick-action-group">
      <Button tool v-for="quickAction in quickActions" :key="quickAction" :icon="quickAction.icon" @click="quickAction.action()" :href="quickAction.href || null" :target="quickAction.target || null" v-tooltip.top="quickAction.label"/>
      <Button tool @click.capture="onMenu($event)" icon="fa-solid fa-ellipsis" v-if="visibleActionCount > 0 && visibleActionCount !== quickActions.length"/>
    </ButtonGroup>
    <Button tool :plain="isMenuOpen ? null : true" secondary @click.capture="onMenu($event)" icon="fa-solid fa-ellipsis" v-if="visibleActionCount > 0 && visibleActionCount !== quickActions.length" class="menu-action" />
  </div>
</template>

<style scoped>

.action-bar {
  display: flex;
  gap: 5px;
  justify-content: end;
  min-height: 31px;
  align-items: center;
  min-width: 55px;
}

.menu-action {
  display: block;
}

.quick-action-group {
  display: block;
}

.action-bar .quick-action-group .pankow-button {
  background-color: white;
  color: var(--pankow-color-text);
  border: 1px solid transparent;
}

.action-bar .quick-action-group .pankow-button:hover {
  color: var(--pankow-color-primary);
}

@media (prefers-color-scheme: dark) {
  .action-bar .quick-action-group .pankow-button {
    background: var(--pankow-color-background);
    color: var(--pankow-color-text);
  }
}

@media (hover: hover) {
  tr:hover .menu-action {
    display: none;
  }

  .quick-action-group {
    display: none;
  }

  tr:hover .quick-action-group {
    display: block;
  }
}

</style>