import { create2DArray, useRefresh } from '@/utils';
import { useLocalStorage } from '@vueuse/core';
import { defineStore } from 'pinia';
import { watch } from 'vue';
export interface Tile {
  id: number;
  number: number;
  removed: boolean;
  fromOthers: boolean;
}
export const useGame2048Store = defineStore('2048', () => {
  const { key: gameKey, refresh: refreshGame } = useRefresh();
  function create() {
    return create2DArray(height.value, width.value, () => []);
  }
  function $reset() {
    rawTileGrid.value = create();
    isInitial.value = true;
    refreshGame();
  }
  const width = useLocalStorage('2048-width', 4);
  const height = useLocalStorage('2048-height', 4);
  watch([width, height], $reset, { flush: 'sync' });
  const rawTileGrid = useLocalStorage<Pick<Tile, 'number' | 'removed'>[][][]>(
    '2048-tile-grid',
    create()
  );
  watch(
    rawTileGrid,
    () => {
      isInitial.value = false;
    },
    { flush: 'sync' }
  );
  const isInitial = useLocalStorage('2048-is-initial', true);
  return { width, height, rawTileGrid, isInitial, gameKey, $reset };
});
