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

const cornerImage = useTemplateRef("cornerImage");

const ANIMATION_SPEED = 0.25;

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

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 * ANIMATION_SPEED;
    currentY += dy * ANIMATION_SPEED;
    currentWidth += dw * ANIMATION_SPEED;
    currentHeight += dh * ANIMATION_SPEED;
  }

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

  ctx.globalAlpha = props.opacity;

  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>
