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

const { onRender } = useScreen();

const { assets } = useAssets();

const ANIMATION_SPEED = 15;

let [currentX, currentY, currentWidth, currentHeight] = props.rect;

onRender((ctx, deltaTime) => {
  const [targetX, targetY, targetWidth, targetHeight] = props.rect;
  const dx = targetX - currentX;
  const dy = targetY - currentY;
  const dw = targetWidth - currentWidth;
  const dh = targetHeight - currentHeight;

  if (
    Math.abs(dx) < 0.5 &&
    Math.abs(dy) < 0.5 &&
    Math.abs(dw) < 0.5 &&
    Math.abs(dh) < 0.5
  ) {
    [currentX, currentY, currentWidth, currentHeight] = props.rect;
  } else {
    const speed = (ANIMATION_SPEED * deltaTime) / 1000;
    currentX += dx * speed;
    currentY += dy * speed;
    currentWidth += dw * speed;
    currentHeight += dh * 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;

  // top-left corner
  assets.images.common.selectorCornersSheet.draw(ctx, x, y, { colored: true });

  // top-right corner
  ctx.save();
  ctx.scale(-1, 1);
  assets.images.common.selectorCornersSheet.draw(ctx, -(x + w), y, {
    colored: true,
  });
  ctx.restore();

  // bottom-left corner
  ctx.save();
  ctx.scale(1, -1);
  assets.images.common.selectorCornersSheet.draw(ctx, x, -(y + h), {
    colored: true,
  });
  ctx.restore();

  // bottom-right corner
  ctx.save();
  ctx.scale(-1, -1);
  assets.images.common.selectorCornersSheet.draw(ctx, -(x + w), -(y + h), {
    colored: true,
  });
  ctx.restore();
}, 40);

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