<script setup lang="ts">
import Buttons from "./Buttons.vue";

const { onRender } = useScreen();

const { assets } = useAssets();
const confirmationModal = useConfirmationModal();

const BG_WIDTH = assets.images.common.confirmationModal.rect.width;
const BG_HEIGHT = assets.images.common.confirmationModal.rect.height;
const BG_X = Math.floor((LOGICAL_WIDTH - BG_WIDTH) / 2);
const BG_Y = Math.floor((LOGICAL_HEIGHT - BG_HEIGHT) / 2);

const LINE_HEIGHT = 15;
const MAX_LINES = 3;

const BOTTOM_BAR_HEIGHT = 24;
const CLIP_HEIGHT = LOGICAL_HEIGHT - BOTTOM_BAR_HEIGHT;

const handleActivateA = () => {
  confirmationModal.onConfirm?.();
  confirmationModal.close("confirm");
};

const handleActivateB = () => {
  confirmationModal.onCancel?.();
  confirmationModal.close("cancel");
};

onRender((ctx) => {
  if (!confirmationModal.isVisible) return;

  ctx.beginPath();
  ctx.rect(0, 0, LOGICAL_WIDTH, CLIP_HEIGHT);
  ctx.clip();

  ctx.translate(0, confirmationModal.offsetY);

  assets.images.common.confirmationModal.draw(ctx, BG_X, BG_Y);

  ctx.font = "16px Pokemon DP Pro";
  ctx.textBaseline = "top";
  ctx.fillStyle = "#ffffff";

  const lines = confirmationModal.text.split("\n").slice(0, MAX_LINES);
  const totalTextHeight = lines.length * LINE_HEIGHT;
  const textStartY = BG_Y + Math.floor((BG_HEIGHT - totalTextHeight) / 2) - 2;

  for (let i = 0; i < lines.length; i++) {
    fillTextHCentered(
      ctx,
      lines[i]!,
      BG_X,
      textStartY + i * LINE_HEIGHT,
      BG_WIDTH,
    );
  }
}, 100);

onUnmounted(() => {
  confirmationModal.close("cancel");
});
</script>

<template>
  <Buttons
    v-if="
      confirmationModal.onCancel ||
      confirmationModal.onConfirm ||
      confirmationModal.bLabel ||
      confirmationModal.aLabel
    "
    :y-offset="confirmationModal.modalButtonsYOffset"
    :b-label="confirmationModal.bLabel ?? $t('common.cancel')"
    :a-label="confirmationModal.aLabel ?? $t('common.confirm')"
    @activate-a="handleActivateA"
    @activate-b="handleActivateB"
  />
</template>
