<script setup>
import { useFocusHub } from "jsview";
import Item from "./Item.vue";

const props = defineProps({
  style: Object,
  buttonConfig: Object,
  onButtonClick: Function,
  onBack: Function,
});

const focusHub = useFocusHub();

const maxWidth = 1280;
const listPadding = 10;
const buttonWidth = 400;
const buttonHeight = 80;
const buttonGap = 50;
let focusedItemIndex = 0;

let listLeft = 0;
const listWidth = (buttonWidth + buttonGap) * props.buttonConfig.length;

// 根据maxWidth，计算buttons的左边位置
const widthCenter = listWidth - buttonGap; // 减去最后一个元素的gap
if (widthCenter < maxWidth) {
  listLeft = Math.floor((maxWidth - widthCenter) / 2);
}

const listSize = {
  left: listLeft,
  width: listWidth,
  height: buttonHeight,
};

const onKeyDown = (ev) => {
  if (ev.keyCode === 13) {
    // Enter
    props.onButtonClick?.(focusedItemIndex);
    return true;
  } else if (ev.keyCode == 8 || ev.keyCode == 27 || ev.keyCode == 10000) {
    // 8:Backspace, 27:Escape, 10000:盒子返回键
    props.onBack?.();
    return true;
  }

  let changeFocusTo = -1;
  switch (ev.keyCode) {
    case 37: // Left
      changeFocusTo =
        (focusedItemIndex - 1 + props.buttonConfig.length) %
        props.buttonConfig.length;
      break;
    case 39: // Right
      changeFocusTo = (focusedItemIndex + 1) % props.buttonConfig.length;
      break;
    default:
      break;
  }
  if (changeFocusTo >= 0) {
    focusHub.setFocus(changeFocusTo.toString());
    focusedItemIndex = changeFocusTo;
    return true;
  }

  return false;
};
</script>

<template>
  <div :style="style">
    <jsv-focus-block
      :style="{
        left: listSize.left,
        width: listSize.width + listPadding * 2,
        height: listSize.height + listPadding * 2,
      }"
      :onKeyDown="onKeyDown"
    >
      <Item
        v-for="(item, index) in buttonConfig"
        :key="index"
        :style="{
          left: (buttonWidth + 10) * index,
          width: buttonWidth,
          height: buttonHeight,
        }"
        :name="index.toString()"
        :autoFocus="index === 0"
      >
        {{ item.name }}
      </Item>
    </jsv-focus-block>
  </div>
</template>