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

const { onRender } = useScreen();

const SAMPLES = 60;
let average = { deltaTime: 0, realDeltaTime: 0 };
const lastFrames: (typeof average)[] = [];

onRender((ctx, deltaTime, realDeltaTime) => {
  lastFrames.push({ deltaTime, realDeltaTime });

  if (lastFrames.length > SAMPLES) {
    lastFrames.shift();
  }

  if (lastFrames.length > 0) {
    average = {
      deltaTime:
        lastFrames.reduce((acc, v) => acc + v.deltaTime, 0) / lastFrames.length,
      realDeltaTime:
        lastFrames.reduce((acc, v) => acc + v.realDeltaTime, 0) /
        lastFrames.length,
    };
  }

  const LINE_COUNT = 5;
  const LINE_HEIGHT = 12;

  ctx.fillStyle = "red";
  ctx.fillRect(props.x - 2, props.y, 120, LINE_COUNT * LINE_HEIGHT + 3);

  let textY = props.y;

  ctx.fillStyle = "black";
  ctx.fillText(`[avg on ${SAMPLES} frames]`, props.x, (textY += LINE_HEIGHT));
  ctx.fillText(
    `fps=${(1000 / average.deltaTime).toFixed()}`,
    props.x,
    (textY += LINE_HEIGHT),
  );
  ctx.fillText(
    `frame_time=${average.deltaTime.toFixed(2)}ms`,
    props.x,
    (textY += LINE_HEIGHT),
  );
  ctx.fillText(
    `real_fps=${(1000 / average.realDeltaTime).toFixed()}`,
    props.x,
    (textY += LINE_HEIGHT),
  );
  ctx.fillText(
    `real_frame_time=${average.realDeltaTime.toFixed(2)}ms`,
    props.x,
    (textY += LINE_HEIGHT),
  );
});

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