<template>
  <div class="wrapper">
    <div class="toolbar">
      <div class="tools">
        <button :class="{ active: activeTool === 'move' }" @click="activeTool = 'move'">
          <img src="/assets/icons/zoneEditor/move.svg" alt="Eraser tool" />
        </button>
        <div class="divider"></div>
        <button :class="{ active: activeTool === 'tiles' }" @click="activeTool = 'tiles'">
          <img src="/assets/icons/zoneEditor/tiles.svg" alt="Eraser tool" />
        </button>
        <div class="divider"></div>
        <button :class="{ active: activeTool === 'eraser' }" @click="activeTool = 'eraser'">
          <img src="/assets/icons/zoneEditor/eraser.svg" alt="Eraser tool" />
        </button>
      </div>
      <div class="buttons">
        <button class="btn-cyan">Save</button>
        <button class="btn-cyan">Load</button>
        <button class="btn-cyan">Clear</button>
        <button class="btn-cyan" @click="() => zoneEditorStore.toggleActive()">Exit</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { useScene } from 'phavuer'
import { getTile, tileToWorldXY } from '@/services/zone'
import config from '@/config'
import { useZoneStore } from '@/stores/zone'
import { useZoneEditorStore } from '@/stores/zoneEditor'

const zoneEditorStore = useZoneEditorStore()

const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer
})
const scene = useScene()
const activeTool = ref('move')
const emit = defineEmits(['erase', 'move', 'tile'])

function onPointerClick(pointer: Phaser.Input.Pointer) {
  const px = scene.cameras.main.worldView.x + pointer.x
  const py = scene.cameras.main.worldView.y + pointer.y

  const pointer_tile = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile
  if (!pointer_tile) {
    return
  }

  if (activeTool.value === 'eraser') {
    emit('erase', pointer_tile)
  }
}

scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerClick)

onBeforeUnmount(() => {
  scene.input.off(Phaser.Input.Events.POINTER_UP, onPointerClick)
})
</script>

<style scoped lang="scss">
@import '@/assets/scss/main';

.wrapper {
  display: flex;
  justify-content: center;
  margin: 10px;
}

.toolbar {
  position: fixed;
  top: 20px;
  border-radius: 5px;
  opacity: 0.8;
  display: flex;
  background: $dark-gray;
  border: 2px solid $cyan;
  color: $light-gray;
  padding: 5px;
  min-width: 90%;
  height: 40px;

  .tools {
    display: flex;
    gap: 10px;

    .divider {
      width: 1px;
      background: $cyan;
    }

    // vertical center
    button {
      display: flex;
      justify-content: center;
      align-items: center;

      &.active {
        border-bottom: 3px solid $light-cyan;
      }
    }

    img {
      filter: invert(1);
      width: 20px;
      height: 20px;
    }
  }

  .buttons {
    display: flex;
    gap: 10px;
    margin-left: auto;

    button {
      padding-left: 15px;
      padding-right: 15px;
    }
  }
}
</style>
