<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 app = useAppStore();
const { assets } = useAssets();

const ANIMATION_SPEED = 0.25;
const CORNER_SIZE = 11;

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

onRender((ctx) => {
  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 {
    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;

  const spriteY = (app.color.row * 4 + app.color.col) * CORNER_SIZE;

  // Top-left corner
  ctx.drawImage(
    assets.common.selectorCornersSheet,
    0,
    spriteY,
    CORNER_SIZE,
    CORNER_SIZE,
    x,
    y,
    CORNER_SIZE,
    CORNER_SIZE,
  );

  // Top-right corner
  ctx.save();
  ctx.scale(-1, 1);
  ctx.drawImage(
    assets.common.selectorCornersSheet,
    0,
    spriteY,
    CORNER_SIZE,
    CORNER_SIZE,
    -(x + w),
    y,
    CORNER_SIZE,
    CORNER_SIZE,
  );
  ctx.restore();

  // Bottom-left corner
  ctx.save();
  ctx.scale(1, -1);
  ctx.drawImage(
    assets.common.selectorCornersSheet,
    0,
    spriteY,
    CORNER_SIZE,
    CORNER_SIZE,
    x,
    -(y + h),
    CORNER_SIZE,
    CORNER_SIZE,
  );
  ctx.restore();

  // Bottom-right corner
  ctx.save();
  ctx.scale(-1, -1);
  ctx.drawImage(
    assets.common.selectorCornersSheet,
    0,
    spriteY,
    CORNER_SIZE,
    CORNER_SIZE,
    -(x + w),
    -(y + h),
    CORNER_SIZE,
    CORNER_SIZE,
  );
  ctx.restore();
});

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