<template>
  <Sprite ref="sprite" texture="player" :x :y />
</template>

<script lang="ts" setup>
import { Sprite, useScene } from 'phavuer'
import { type Ref, ref } from 'vue'
import config from '@/config'
import { useSocketStore } from '@/stores/socket'

const socket = useSocketStore();

socket.socket?.emit('joinRoom', 'game');

const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer,
  player: Object
})

const scene = useScene()
const pointer_tile = ref(undefined);
const x: Ref<number> = ref(0);
const y: Ref<number> = ref(0);

if (props.player) {
  x.value = props.player.x;
  y.value = props.player.y;
}

function onPointerClick(pointer: Phaser.Input.Pointer) {
  /**
   * @TODO : Check if player was dragging, if so, don't move player
   */
  const px = scene.cameras.main.worldView.x + pointer.x;
  const py = scene.cameras.main.worldView.y + pointer.y;

  pointer_tile.value = getTile(px, py, props.layer);
  if (pointer_tile.value) {
    // Convert tile coordinates to world coordinates
    const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y);
    x.value = worldPoint.x + config.tile_size.y;
    y.value = worldPoint.y;
  }
}
scene.input.on(Phaser.Input.Events.POINTER_DOWN, onPointerClick);

function getTile (x: number, y: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAtWorldXY(x, y);

  console.log(x,y);
  console.log('tile', tile);

  if (!tile) {
    return undefined;
  }

  return tile;
}
</script>