<script setup lang="ts">
const props = defineProps<{
  x: number;
  y: number;
  width: number;
  height: number;
}>();

const cornerImage = useTemplateRef("cornerImage");

let currentX = props.x;
let currentY = props.y;
let currentWidth = props.width;
let currentHeight = props.height;

const animationSpeed = 0.25;

useRender((ctx) => {
  if (!cornerImage.value) return;

  const dx = props.x - currentX;
  const dy = props.y - currentY;
  const dw = props.width - currentWidth;
  const dh = props.height - currentHeight;

  if (
    Math.abs(dx) < 0.5 &&
    Math.abs(dy) < 0.5 &&
    Math.abs(dw) < 0.5 &&
    Math.abs(dh) < 0.5
  ) {
    currentX = props.x;
    currentY = props.y;
    currentWidth = props.width;
    currentHeight = props.height;
  } else {
    currentX += dx * animationSpeed;
    currentY += dy * animationSpeed;
    currentWidth += dw * animationSpeed;
    currentHeight += dh * animationSpeed;
  }

  const x = Math.floor(currentX);
  const y = Math.floor(currentY);
  const w = Math.floor(currentWidth);
  const h = Math.floor(currentHeight);

  ctx.drawImage(cornerImage.value, x, y);

  ctx.save();
  ctx.scale(-1, 1);
  ctx.drawImage(cornerImage.value, -(x + w), y);
  ctx.restore();

  ctx.save();
  ctx.scale(1, -1);
  ctx.drawImage(cornerImage.value, x, -(y + h));
  ctx.restore();

  ctx.save();
  ctx.scale(-1, -1);
  ctx.drawImage(cornerImage.value, -(x + w), -(y + h));
  ctx.restore();
});
</script>

<template>
  <img
    ref="cornerImage"
    src="/assets/images/home/bottom-screen/buttons/corner.png"
    hidden
  />
</template>
