<template>
  <div
    ref="rootElement"
    :class="{
      'tw:flex': showComponentHandle,
    }"
    data-draggable
  >
    <div v-if="showComponentHandle" ref="handleElement">
      <v-icon class="tw:cursor-grab" icon="mdi-drag"></v-icon>
    </div>

    <slot />
  </div>
</template>

<script setup lang="ts">
import useDragAndDrop, {
  type DraggableConfig,
} from "@racletteOrchestrator/composables/useDragAndDrop"
import { computed, nextTick, onMounted, useTemplateRef } from "vue"

const props = withDefaults(
  defineProps<{
    handle?: boolean
    draggableConfig?: DraggableConfig
  }>(),
  {
    draggableConfig: () => ({}) as DraggableConfig,
  },
)

const rootElement = useTemplateRef("rootElement")
const handleElement = useTemplateRef("handleElement")

const { makeDraggable } = useDragAndDrop()

const showComponentHandle = computed(
  () => props.handle && !props.draggableConfig.handleElement,
)

onMounted(async () => {
  await nextTick()
  // extend config with the handleElement, if configured
  const draggableConfig: DraggableConfig = {
    ...(showComponentHandle.value
      ? { handleElement: handleElement.value! }
      : {}),
    ...props.draggableConfig,
  }

  makeDraggable(rootElement.value!, draggableConfig)
})
</script>

<style lang="scss">
@keyframes wiggle {
  0%,
  100% {
    transform: rotate(-3deg);
  }
  50% {
    transform: rotate(3deg);
  }
}

@keyframes wiggle-sm {
  0%,
  100% {
    transform: rotate(-0.25deg);
  }
  50% {
    transform: rotate(0.25deg);
  }
}

.wiggle {
  animation: wiggle 0.3s ease-in-out infinite;
  will-change: transform;
}

.wiggle-sm {
  animation: wiggle-sm 0.3s ease-in-out infinite;
  will-change: transform;
}
</style>
