import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/enums.dart';
import 'package:tane/ui/category_palette.dart';

/// Chip labels are drawn in [Swatch.ink] over [Swatch.fill]; that pairing must
/// clear WCAG AA for normal text (≥4.5:1), like the rest of the palette
/// (see theme_contrast_test.dart). Locks the tuned inks against regressions.
void main() {
  double lin(double c) =>
      c <= 0.03928 ? c / 12.92 : math.pow((c + 0.055) / 1.055, 2.4).toDouble();
  double luminance(Color c) =>
      0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b);
  double contrast(Color a, Color b) {
    final la = luminance(a), lb = luminance(b);
    final hi = math.max(la, lb), lo = math.min(la, lb);
    return (hi + 0.05) / (lo + 0.05);
  }

  test('every category swatch label meets AA on its fill', () {
    // Cover the whole palette by probing many distinct category names.
    for (var i = 0; i < 60; i++) {
      final s = categorySwatch('family-$i');
      expect(contrast(s.ink, s.fill), greaterThanOrEqualTo(4.5),
          reason: 'category-$i ink on fill');
    }
  });

  test('every lot-form swatch label meets AA on its fill', () {
    for (final type in LotType.values) {
      final s = lotTypeSwatch(type);
      expect(contrast(s.ink, s.fill), greaterThanOrEqualTo(4.5),
          reason: '$type ink on fill');
    }
  });

  // A *selected* swatch chip fills solid with its ink and draws white content
  // (label, icon, checkmark). That pairing must clear AA too.
  test('white content meets AA on every selected (ink-filled) swatch', () {
    for (var i = 0; i < 60; i++) {
      final s = categorySwatch('family-$i');
      expect(contrast(Colors.white, s.ink), greaterThanOrEqualTo(4.5),
          reason: 'white on category-$i ink');
    }
    for (final type in LotType.values) {
      final s = lotTypeSwatch(type);
      expect(contrast(Colors.white, s.ink), greaterThanOrEqualTo(4.5),
          reason: 'white on $type ink');
    }
  });
}
