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

import {
  applyPreviewRotationToSceneMarkers,
  previewRotationStepsCw,
  rotateMapNormPointByCwSteps,
  rotateMapNormPointCw90,
  rotateSceneTokensByCwSteps,
} from './scenePreviewRotation';

void test('previewRotationStepsCw wraps correctly', () => {
  assert.equal(previewRotationStepsCw(0, 90), 1);
  assert.equal(previewRotationStepsCw(90, 180), 1);
  assert.equal(previewRotationStepsCw(0, 270), 3);
  assert.equal(previewRotationStepsCw(270, 0), 1);
  assert.equal(previewRotationStepsCw(90, 90), 0);
});

void test('rotateMapNormPointCw90 matches CSS rotate(90deg) y-down', () => {
  assert.deepEqual(rotateMapNormPointCw90(0, 0), { nx: 1, ny: 0 });
  assert.deepEqual(rotateMapNormPointCw90(1, 0), { nx: 1, ny: 1 });
  assert.deepEqual(rotateMapNormPointCw90(1, 1), { nx: 0, ny: 1 });
  assert.deepEqual(rotateMapNormPointCw90(0, 1), { nx: 0, ny: 0 });
  assert.deepEqual(rotateMapNormPointCw90(0.25, 0.1), { nx: 0.9, ny: 0.25 });
});

void test('four Cw90 steps return to start', () => {
  const start = { nx: 0.2, ny: 0.7 };
  assert.deepEqual(rotateMapNormPointByCwSteps(start.nx, start.ny, 4), start);
});

void test('rotateSceneTokensByCwSteps also turns facing', () => {
  const [tok] = rotateSceneTokensByCwSteps([{ id: 'a', nx: 0.2, ny: 0.1, rotationDeg: 15 }], 1);
  assert.ok(tok);
  assert.equal(tok.nx, 0.9);
  assert.equal(tok.ny, 0.2);
  assert.equal(tok.rotationDeg, 105);
});

void test('applyPreviewRotationToSceneMarkers remaps when rotation changes', () => {
  const scene = {
    previewRotationDeg: 0 as const,
    tokens: [{ id: 't', nx: 0.2, ny: 0.1, rotationDeg: 0 }],
    npcTokens: [{ id: 'n', nx: 0.5, ny: 0.5 }],
    traps: [{ id: 'tr', nx: 0, ny: 0 }],
  };
  const next = applyPreviewRotationToSceneMarkers(scene, 90);
  assert.deepEqual(next.tokens[0], { id: 't', nx: 0.9, ny: 0.2, rotationDeg: 90 });
  assert.deepEqual(next.npcTokens[0], { id: 'n', nx: 0.5, ny: 0.5 });
  assert.deepEqual(next.traps[0], { id: 'tr', nx: 1, ny: 0 });
});
