<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(() => {
  if (window.innerWidth <= 576) return [];

  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 && 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" class="menu-action" :class="{ 'hide-on-touch': visibleActionCount === quickActions.length }"/>
  </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: none;
}

.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);
  }
}

.hide-on-touch {
  display: none;
}

@media (hover: hover) {
  .hide-on-touch {
    display: block;
  }

  .menu-action {
    display: block;
  }

  /* cover tables and backupsite view for now */
  div:hover  > div > div > .menu-action,
  tr:hover .menu-action {
    display: none;
  }

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

  /* cover tables and backupsite view for now */
  div:hover  > div > div > .quick-action-group,
  tr:hover .quick-action-group {
    display: block;
  }
}

</style>