import assert from 'node:assert/strict';
import test from 'node:test';

import { ScenePlayerTokensSessionStore } from './scenePlayerTokensSessionStore';

void test('ScenePlayerTokensSessionStore selection and show/hide', () => {
  const store = new ScenePlayerTokensSessionStore();
  store.dispatch({ kind: 'setSelection', playerIds: ['a', 'b', 'a'] });
  assert.deepEqual(store.getState().selectedPlayerIds, ['a', 'b']);
  assert.equal(store.getState().visible, false);

  store.dispatch({ kind: 'show', sizeN: 0.08 });
  assert.equal(store.getState().visible, true);
  assert.equal(Object.keys(store.getState().byPlayerId).length, 2);
  assert.ok(store.getState().byPlayerId.a);
  assert.equal(store.getState().byPlayerId.a?.ny, 0.88);

  store.dispatch({ kind: 'setVisible', visible: false });
  assert.equal(store.getState().visible, false);
  assert.ok(store.getState().byPlayerId.a);

  store.dispatch({ kind: 'clearPlacements' });
  assert.equal(store.getState().visible, false);
  assert.deepEqual(store.getState().byPlayerId, {});
  assert.deepEqual(store.getState().selectedPlayerIds, ['a', 'b']);
});

void test('ScenePlayerTokensSessionStore move and reset', () => {
  const store = new ScenePlayerTokensSessionStore();
  store.dispatch({ kind: 'setSelection', playerIds: ['p1'] });
  store.dispatch({ kind: 'show', sizeN: 0.1 });
  const s1 = store.dispatch({ kind: 'move', playerId: 'p1', nx: 0.3, ny: 0.4 });
  assert.equal(s1.byPlayerId.p1?.nx, 0.3);
  assert.equal(s1.byPlayerId.p1?.ny, 0.4);
  const s2 = store.reset();
  assert.deepEqual(s2.selectedPlayerIds, []);
  assert.equal(s2.visible, false);
  assert.deepEqual(s2.byPlayerId, {});
});

void test('ScenePlayerTokensSessionStore rotateMapCwSteps', () => {
  const store = new ScenePlayerTokensSessionStore();
  store.dispatch({ kind: 'setSelection', playerIds: ['p1'] });
  store.dispatch({ kind: 'show', sizeN: 0.1 });
  store.dispatch({ kind: 'move', playerId: 'p1', nx: 0.2, ny: 0.1 });
  const s = store.rotateMapCwSteps(1);
  assert.equal(s.byPlayerId.p1?.nx, 0.9);
  assert.equal(s.byPlayerId.p1?.ny, 0.2);
});

void test('ScenePlayerTokensSessionStore setSize updates placement', () => {
  const store = new ScenePlayerTokensSessionStore();
  store.dispatch({ kind: 'setSelection', playerIds: ['p1'] });
  store.dispatch({ kind: 'show', sizeN: 0.1 });
  const nxBefore = store.getState().byPlayerId.p1?.nx;
  const s1 = store.dispatch({ kind: 'setSize', playerId: 'p1', sizeN: 0.22 });
  assert.equal(s1.byPlayerId.p1?.sizeN, 0.22);
  assert.equal(s1.byPlayerId.p1?.nx, nxBefore);
  const s2 = store.dispatch({ kind: 'move', playerId: 'p1', nx: 0.4, ny: 0.5 });
  assert.equal(s2.byPlayerId.p1?.sizeN, 0.22);
});
