import 'package:flutter/material.dart';

import '../db/enums.dart';
import 'theme.dart';

/// A colour for a chip/label: a soft [fill] to tint the background and a darker,
/// same-hue [ink] readable on that fill and on white (text, dot, checkmark).
class Swatch {
  const Swatch(this.fill, this.ink);
  final Color fill;
  final Color ink;
}

/// A muted, earthy palette — one low-saturation key, hues spread around the
/// wheel — so botanical families (categories) are distinguishable at a glance
/// without shouting over the green brand. Kept calm on purpose (soft fills,
/// legible ink). 14 tones keep collisions rare for a typical 6–10 family
/// inventory. Order is stable; new entries append only.
// Inks are tuned so the label meets WCAG AA (≥4.5:1) on its own fill — see
// test/ui/category_palette_contrast_test.dart.
const _familyPalette = <Swatch>[
  Swatch(Color(0xFFE8EEDA), Color(0xFF556B2F)), // olive
  Swatch(Color(0xFFF3E2D8), Color(0xFF8E5336)), // terracotta
  Swatch(Color(0xFFF3EBD3), Color(0xFF7C621B)), // ochre
  Swatch(Color(0xFFDDEAE6), Color(0xFF3E7168)), // sage teal
  Swatch(Color(0xFFF0E1E4), Color(0xFF8F4E5E)), // dusty rose
  Swatch(Color(0xFFE0E6EE), Color(0xFF4A6489)), // slate blue
  Swatch(Color(0xFFE9E1EE), Color(0xFF6E5090)), // plum
  Swatch(Color(0xFFEBE3D8), Color(0xFF7A5A3A)), // warm brown
  Swatch(Color(0xFFDCEAD6), Color(0xFF3E6B3A)), // forest green
  Swatch(Color(0xFFD6E7EA), Color(0xFF2C6A73)), // petrol
  Swatch(Color(0xFFF3DEDB), Color(0xFFA14234)), // brick red
  Swatch(Color(0xFFEFDCEA), Color(0xFF864C7C)), // mauve
  Swatch(Color(0xFFE1E1F1), Color(0xFF4E5199)), // indigo
  Swatch(Color(0xFFDFE4E9), Color(0xFF4C5E70)), // steel
];

/// A stable (launch-to-launch, platform-independent) hash of a category name.
/// `String.hashCode` is randomised per run, which would reshuffle colours on
/// every launch — so fold the code units ourselves (FNV-1a-ish).
int _stableHash(String s) {
  var h = 0x811c9dc5;
  for (final c in s.codeUnits) {
    h = (h ^ c) * 0x01000193;
    h &= 0xffffffff;
  }
  return h;
}

/// The stable colour for a free-text category (a botanical family). The same
/// name always maps to the same tonality.
Swatch categorySwatch(String category) =>
    _familyPalette[_stableHash(category) % _familyPalette.length];

/// A fixed tonality per lot form, so the form chips read as their own colour
/// group (distinct from the family chips). Greens for the leafy forms, warmer
/// tones for woody/underground ones.
Swatch lotTypeSwatch(LotType type) => switch (type) {
  LotType.seed => const Swatch(seedPrimaryContainer, seedOnPrimaryContainer),
  LotType.seedling => const Swatch(Color(0xFFDDEBCF), Color(0xFF456D29)),
  LotType.plant => const Swatch(Color(0xFFD9EAD9), Color(0xFF2A702F)),
  LotType.tree => const Swatch(Color(0xFFE3D9C8), Color(0xFF6B4F2A)),
  LotType.bulb => const Swatch(Color(0xFFF3E9CF), Color(0xFF7B611B)),
  LotType.cutting => const Swatch(Color(0xFFE6EAD3), Color(0xFF5D692C)),
};
