const test = require('node:test');
const assert = require('node:assert/strict');
require('./ts-register');

const {
  WorkspaceEngine,
  DESK_CANVAS_PADDING,
} = require('../src/desktop/workspaceEngine.ts');

const makeEngine = () => {
  const engine = new WorkspaceEngine();
  engine.setEnsureDocumentSize(() => ({ width: 200, height: 200 }));
  engine.setCanvasSize({ width: 1200, height: 800 });
  return engine;
};

test('syncLayoutSnapshot clones from layout map', () => {
  const engine = makeEngine();
  engine.setItems([{ id: 'doc-1' }]);
  engine.ensureLayoutForItems();
  engine.syncLayoutSnapshot();

  const firstSnapshot = engine.getSnapshot();
  assert(firstSnapshot.layout instanceof Map);
  assert(firstSnapshot.layout.get('doc-1'));

  engine.layout.set('doc-1', {
    centerX: DESK_CANVAS_PADDING + 150,
    centerY: DESK_CANVAS_PADDING + 150,
    rotation: 0,
    width: 200,
    height: 200,
  });
  engine.syncLayoutSnapshot();

  const secondSnapshot = engine.getSnapshot();
  assert.notStrictEqual(secondSnapshot.layout, engine.layout);
  assert.equal(secondSnapshot.layout.get('doc-1').centerX, engine.layout.get('doc-1').centerX);
});

test('recalcVisibleDocIds respects viewport bounds', () => {
  const engine = makeEngine();
  engine.items = [{ id: 'visible' }, { id: 'hidden' }];
  engine.setDocumentLookup(new Map([
    ['visible', { id: 'visible' }],
    ['hidden', { id: 'hidden' }],
  ]));

  engine.layout = new Map([
    ['visible', {
      centerX: DESK_CANVAS_PADDING + 150,
      centerY: DESK_CANVAS_PADDING + 150,
      rotation: 0,
      width: 200,
      height: 200,
    }],
    ['hidden', {
      centerX: -500,
      centerY: -500,
      rotation: 0,
      width: 200,
      height: 200,
    }],
  ]);
  engine.layoutSnapshot = new Map(engine.layout);

  engine.recalcVisibleDocIds();

  const snapshot = engine.getSnapshot();
  assert(snapshot.visibleDocIds.has('visible'));
  assert(!snapshot.visibleDocIds.has('hidden'));
});
