import 'dart:ui' as ui;

import 'package:flutter_test/flutter_test.dart';

import 'package:badnote/editor/pdf/page_tile_cache.dart';
import 'package:badnote/editor/pdf/page_tile_layer.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  test('PageTileCache LRU evicts oldest', () async {
    final cache = PageTileCache(maxTiles: 2);
    final a = await _tinyImage();
    final b = await _tinyImage();
    final c = await _tinyImage();
    cache.put(const TileKey('p1', 96), a);
    cache.put(const TileKey('p2', 96), b);
    expect(cache.length, 2);
    cache.put(const TileKey('p3', 96), c);
    expect(cache.length, 2);
    expect(cache.get(const TileKey('p1', 96)), isNull);
  });

  test('PageTileLayer falls back to last good', () async {
    final layer = PageTileLayer(cache: PageTileCache(maxTiles: 4));
    final img = await _tinyImage();
    layer.put(const TileKey('p1', 96), img);
    expect(layer.resolve(const TileKey('p1', 192)), same(img));
    // Don't call dispose() in unit test — cache dispose needs a frame.
  });
}

Future<ui.Image> _tinyImage() async {
  final recorder = ui.PictureRecorder();
  final canvas = ui.Canvas(recorder);
  canvas.drawRect(
    const ui.Rect.fromLTWH(0, 0, 2, 2),
    ui.Paint()..color = const ui.Color(0xFFFFFFFF),
  );
  final picture = recorder.endRecording();
  return picture.toImage(2, 2);
}
