<script lang="ts" setup>
import { LOGICAL_WIDTH, LOGICAL_HEIGHT, SCREEN_SCALE } from "~/utils/screen";

const canvas = useTemplateRef("canvas");

const renderCallbacks = new Map<RenderCallback, number>();
const screenClickCallbacks = new Set<ScreenClickCallback>();
const screenMouseWheelCallbacks = new Set<ScreenMouseWheelCallback>();

let ctx: CanvasRenderingContext2D | null = null;
let animationFrameId: number | null = null;
let lastFrameTime = 0;
let lastRealFrameTime = 0;

const registerRenderCallback = (callback: RenderCallback, zIndex = 0) => {
  renderCallbacks.set(callback, zIndex);
  return () => renderCallbacks.delete(callback);
};

const registerScreenClickCallback = (callback: ScreenClickCallback) => {
  screenClickCallbacks.add(callback);
  return () => screenClickCallbacks.delete(callback);
};

const registerScreenMouseWheelCallback = (
  callback: ScreenMouseWheelCallback,
) => {
  screenMouseWheelCallbacks.add(callback);
  return () => screenMouseWheelCallbacks.delete(callback);
};

const handleCanvasClick = (event: MouseEvent) => {
  if (!canvas.value) return;

  const rect = canvas.value.getBoundingClientRect();
  const scaleX = LOGICAL_WIDTH / rect.width;
  const scaleY = LOGICAL_HEIGHT / rect.height;

  const x = (event.clientX - rect.left) * scaleX;
  const y = (event.clientY - rect.top) * scaleY;

  for (const callback of screenClickCallbacks) {
    callback(x, y);
  }
};

const handleCanvasWheel = (event: WheelEvent) => {
  for (const callback of screenMouseWheelCallbacks) {
    callback(event.deltaY, event.deltaX);
  }
};

const renderFrame = (timestamp: number) => {
  if (!ctx) return;

  const deltaTime = timestamp - lastFrameTime;
  lastFrameTime = timestamp;

  const start = Date.now();

  // render
  ctx.save();
  ctx.scale(SCREEN_SCALE, SCREEN_SCALE);

  ctx.clearRect(0, 0, LOGICAL_WIDTH, LOGICAL_HEIGHT);

  const sortedCallbacks = Array.from(renderCallbacks.entries())
    .sort((a, b) => a[1] - b[1])
    .map(([callback]) => callback);

  for (const callback of sortedCallbacks) {
    ctx.save();

    callback(ctx, deltaTime, lastRealFrameTime);

    ctx.restore();
  }

  ctx.restore();

  lastRealFrameTime = Date.now() - start;

  animationFrameId = requestAnimationFrame(renderFrame);
};

provide("registerRenderCallback", registerRenderCallback);
provide("registerScreenClickCallback", registerScreenClickCallback);
provide("registerScreenMouseWheelCallback", registerScreenMouseWheelCallback);

onMounted(() => {
  if (!canvas.value) throw new Error("Missing canvas");

  ctx = canvas.value.getContext("2d");
  if (!ctx) throw new Error("Missing 2d context");

  ctx.imageSmoothingEnabled = false;

  canvas.value.addEventListener("click", handleCanvasClick);
  canvas.value.addEventListener("wheel", handleCanvasWheel, { passive: true });

  animationFrameId = requestAnimationFrame(renderFrame);
});

onUnmounted(() => {
  if (animationFrameId !== null) {
    cancelAnimationFrame(animationFrameId);
  }

  if (canvas.value) {
    canvas.value.removeEventListener("click", handleCanvasClick);
    canvas.value.removeEventListener("wheel", handleCanvasWheel);
  }
});

defineExpose({
  canvas,
});
</script>

<template>
  <canvas
    ref="canvas"
    :width="SCREEN_WIDTH"
    :height="SCREEN_HEIGHT"
    :style="{
      margin: '0',
      border: '1px solid red',
    }"
  />

  <slot v-if="canvas" />
</template>
