import { computed, reactive } from 'vue'
import { RECIPROCAL, STAGE_WIDTH, STAGE_HEIGHT } from '../level/def'
import type { Item, ItemQuality } from '../level/items'

export interface InventoryItem extends Item {
  amount: number
  quality: ItemQuality | null
}

export interface Player extends Moveable {
  inventory: InventoryItem[]
}

const player = reactive<Player>({
  x: Math.round((STAGE_WIDTH + 2) / 2),
  y: Math.round((STAGE_HEIGHT + 2) / 2),
  lastDir: 0,
  vx: 0,
  vy: 1, // always falling, because of gravity
  inventory: [], // not yet in use
})

const pocket = (newItem: InventoryItem) => {
  const existing = player.inventory.find(item => item.name === newItem.name)

  if (existing) existing.amount += 1
  else player.inventory.push({
    quality: null,
    amount: 1,
    ...newItem
  })
}

export default function usePlayer() {
  const dx = computed(() => player.vx * RECIPROCAL)
  const dy = computed(() => player.vy * RECIPROCAL)
  const direction = computed(() => (player.lastDir < 0 ? 'left' : 'right'))

  return { player, direction, dx, dy, pocket }
}
