// Tests for the infinite-board model (F7 便利贴 + 双链).

import 'dart:ui' show Offset, Rect, Size;

import 'package:flutter_test/flutter_test.dart';

import 'package:badnote/editor/board/board.dart';

BoardCard _card(String id, double x, double y, {String text = ''}) => BoardCard(
      id: id,
      position: Offset(x, y),
      size: const Size(100, 80),
      text: text,
    );

void main() {
  test('add / cardById / removeById', () {
    final b = Board.empty.add(_card('a', 0, 0)).add(_card('b', 200, 0));
    expect(b.length, 2);
    expect(b.cardById('a')!.position, const Offset(0, 0));
    expect(b.removeById('a').cardById('a'), isNull);
  });

  test('duplicate id throws', () {
    final b = Board.empty.add(_card('a', 0, 0));
    expect(() => b.add(_card('a', 5, 5)), throwsArgumentError);
  });

  test('moveCard / setText are copy-on-write', () {
    final b0 = Board.empty.add(_card('a', 0, 0));
    final b1 = b0.moveCard('a', const Offset(50, 60)).setText('a', 'hi');
    expect(b0.cardById('a')!.position, const Offset(0, 0)); // original intact
    expect(b1.cardById('a')!.position, const Offset(50, 60));
    expect(b1.cardById('a')!.text, 'hi');
  });

  test('cardsIn culls cards outside the viewport', () {
    final b = Board.empty
        .add(_card('near', 0, 0)) // bounds 0,0,100,80
        .add(_card('far', 5000, 5000));
    final visible = b.cardsIn(const Rect.fromLTWH(0, 0, 300, 300));
    expect(visible.map((c) => c.id).toSet(), {'near'});
  });

  test('linkGraph derives backlinks from card [[links]]', () {
    final b = Board.empty
        .add(_card('a', 0, 0, text: 'see [[b]] and [[c]]'))
        .add(_card('b', 200, 0, text: 'see [[c]]'))
        .add(_card('c', 400, 0, text: 'leaf'));
    expect(b.backlinksOf('c'), {'a', 'b'});
    expect(b.backlinksOf('b'), {'a'});
    expect(b.backlinksOf('a'), isEmpty);
    expect(b.linkGraph().linksFrom('a'), {'b', 'c'});
  });

  test('value equality + immutable card list', () {
    final a = Board.empty.add(_card('x', 1, 1));
    final b = Board.empty.add(_card('x', 1, 1));
    expect(a, b);
    expect(() => a.cards.add(_card('y', 0, 0)), throwsUnsupportedError);
  });

  test('BoardCard.bounds + copyWith', () {
    final c = _card('a', 10, 20);
    expect(c.bounds, const Rect.fromLTWH(10, 20, 100, 80));
    expect(c.copyWith(text: 'z').text, 'z');
    expect(c.copyWith().position, const Offset(10, 20));
  });
}
