

library;

enum TimeBucketScheme { watched, added }


class TimeBucket {
  final String key;
  final String label;
  final int order;

  const TimeBucket({
    required this.key,
    required this.label,
    required this.order,
  });
}

const _bucketToday = TimeBucket(key: 'today', label: '今天', order: 0);
const _bucketYesterday = TimeBucket(key: 'yesterday', label: '昨天', order: 1);
const _bucketThisWeekWatched = TimeBucket(
  key: 'this_week',
  label: '本周',
  order: 2,
);
const _bucketEarlierWatched = TimeBucket(key: 'earlier', label: '更早', order: 3);

const _bucketThisWeekAdded = TimeBucket(
  key: 'this_week',
  label: '本周',
  order: 1,
);
const _bucketThisMonthAdded = TimeBucket(
  key: 'this_month',
  label: '本月',
  order: 2,
);
const _bucketEarlierAdded = TimeBucket(key: 'earlier', label: '更早', order: 3);


DateTime? parseEmbyDate(Object? raw) {
  if (raw is DateTime) return raw.toLocal();
  if (raw is! String || raw.isEmpty) return null;
  final parsed = DateTime.tryParse(raw);
  return parsed?.toLocal();
}

DateTime _dateOnly(DateTime d) => DateTime(d.year, d.month, d.day);


DateTime _startOfWeek(DateTime now) {
  final today = _dateOnly(now);
  return today.subtract(Duration(days: today.weekday - DateTime.monday));
}


TimeBucket bucketFor(DateTime? when, DateTime now, TimeBucketScheme scheme) {
  final earlier = scheme == TimeBucketScheme.watched
      ? _bucketEarlierWatched
      : _bucketEarlierAdded;
  if (when == null) return earlier;

  final whenDay = _dateOnly(when);
  final todayDay = _dateOnly(now);
  final dayDiff = todayDay.difference(whenDay).inDays;

  switch (scheme) {
    case TimeBucketScheme.watched:
      if (dayDiff <= 0) return _bucketToday;
      if (dayDiff == 1) return _bucketYesterday;
      if (!whenDay.isBefore(_startOfWeek(now))) return _bucketThisWeekWatched;
      return _bucketEarlierWatched;
    case TimeBucketScheme.added:
      if (dayDiff <= 0) return _bucketToday;
      if (!whenDay.isBefore(_startOfWeek(now))) return _bucketThisWeekAdded;
      if (whenDay.year == todayDay.year && whenDay.month == todayDay.month) {
        return _bucketThisMonthAdded;
      }
      return _bucketEarlierAdded;
  }
}


String? relativeTimeLabel(DateTime? when, DateTime now) {
  if (when == null) return null;
  final diff = now.difference(when);
  if (diff.isNegative) return '刚刚';
  if (diff.inMinutes < 1) return '刚刚';
  if (diff.inMinutes < 60) return '${diff.inMinutes} 分钟前';
  if (diff.inHours < 24) return '${diff.inHours} 小时前';
  if (diff.inDays < 7) return '${diff.inDays} 天前';
  if (diff.inDays < 35) return '${(diff.inDays / 7).floor()} 周前';
  final m = when.month.toString().padLeft(2, '0');
  final d = when.day.toString().padLeft(2, '0');
  return '${when.year}-$m-$d';
}
