<script setup>
import { ref } from "vue";
import { useFocusHub } from "jsview";
const props = defineProps({
  initFlipped: Boolean,
  width: Number,
  height: Number,
  backImg: String,
  foreImg: String,
  perspective: Number,
  data: Object,
  query: Object,
  onEdge: Function,
  onAction: Object,
  name: String,
});

let flipAnim = ref("");
let flipped = ref(props.initFlipped);
let focused = ref(false);
let keyLocked = false;
let focusNode = ref(null);
let focusHub = useFocusHub();

const onFocus = () => {
  focused.value = true;
  focusHub.setFocus(props.name);
};
const onBlur = () => {
  focused.value = false;
};
const onClick = () => {};
const onFlipped = () => {
  flipped.value = !flipped.value;
  keyLocked = false;
};
const onKeyDown = (ev) => {
  if (keyLocked) {
    return true;
  } else {
    if (ev.keyCode === 13) {
      flipAnim.value = flipped.value ? "flip 1s" : "flipBack 1s";
      return true;
    }
  }
  return false;
};
props.onAction.register("onFocus", onFocus);
props.onAction.register("onBlur", onBlur);
props.onAction.register("onClick", onClick);
</script>

<template>
  <jsv-focus-block
    ref="focusNode"
    :name="name"
    :onAction="{
      onKeyDown: onKeyDown,
    }"
  >
    <div :style="{ width, height, perspective }">
      <div
        :style="{
          width,
          height,
          animation: flipAnim,
          transformStyle: 'preserve-3d',
          backgroundColor: '#FFFF00',
        }"
        @animationend="onFlipped"
      >
        <div
          :style="{
            width,
            height,
            backgroundImage: backImg,
            backfaceVisibility: 'hidden',
            transform: flipped ? '' : 'rotate3d(0,1,0,180deg)',
          }"
        ></div>
        <div
          :style="{
            width,
            height,
            backgroundImage: foreImg,
            backfaceVisibility: 'hidden',
            transform: flipped ? 'rotate3d(0,1,0,-180deg)' : '',
          }"
        ></div>
      </div>
    </div>
    <div
      v-if="focused"
      :style="{ width: 20, height: 20, backgroundColor: '#FF0000' }"
    ></div>
  </jsv-focus-block>
</template>
<style>
@keyframes flip {
  from {
    transform: rotate3d(0, 1, 0, 0deg);
    transform-origin: center center;
  }
  to {
    transform: rotate3d(0, 1, 0, 180deg);
    transform-origin: center center;
  }
}

@keyframes flipBack {
  from {
    transform: rotate3d(0, 1, 0, 0deg);
    transform-origin: center center;
  }
  to {
    transform: rotate3d(0, 1, 0, -180deg);
    transform-origin: center center;
  }
}
</style>