<script setup lang="ts">
const props = defineProps<{
  yOffset: number;
  opacity?: number;
  bLabel: string;
  aLabel: string;
}>();

const emit = defineEmits<{
  activateA: [];
  activateB: [];
}>();

const { onRender, onClick } = useScreen();

const { assets } = useAssets();

const BUTTON_WIDTH = assets.images.common.button.rect.width;
const BUTTON_HEIGHT = assets.images.common.button.rect.height;
const LETTER_WIDTH = assets.images.common.B.rect.width;

const B_BUTTON: Rect = [31, 172, BUTTON_WIDTH, BUTTON_HEIGHT];
const A_BUTTON: Rect = [144, 172, BUTTON_WIDTH, BUTTON_HEIGHT];

onRender((ctx) => {
  ctx.globalAlpha = props.opacity ?? 1;
  ctx.font = "10px NDS10";

  ctx.translate(0, props.yOffset);

  const drawButton = (
    image: {
      draw: (ctx: CanvasRenderingContext2D, x: number, y: number) => void;
    },
    text: string,
    x: number,
    offset: number,
  ) => {
    assets.images.common.button.draw(ctx, x, 172);

    const { actualBoundingBoxRight: textWidth } = ctx.measureText(text);
    const width = LETTER_WIDTH + 4 + textWidth;
    const left = Math.ceil(x + BUTTON_WIDTH / 2 - width / 2 - offset / 2);

    image.draw(ctx, left, 176);
    ctx.fillText(text, left + LETTER_WIDTH + 4, 185);
  };

  drawButton(assets.images.common.B, props.bLabel, 31, 5);
  drawButton(assets.images.common.A, props.aLabel, 144, 0);
}, 60);

onClick((x, y) => {
  if (props.yOffset !== 0) return;
  if (rectContains(B_BUTTON, [x, y])) {
    emit("activateB");
  } else if (rectContains(A_BUTTON, [x, y])) {
    emit("activateA");
  }
});

useKeyDown((key) => {
  if (props.yOffset !== 0) return;
  switch (key) {
    case "NDS_START":
    case "NDS_A":
      emit("activateA");
      break;

    case "NDS_B":
      emit("activateB");
      break;
  }
});

defineOptions({ render: () => null });
</script>
