import 'package:intl/intl.dart';
import '../../models/content_models.dart';
String formatDistance(double? distance, String locale) {
if (distance == null) return '';
return NumberFormat('0.0', locale).format(distance);
}
String formatDistanceLabel(double? distance, String locale) {
if (distance == null) return '';
if (distance < 1) {
return '${NumberFormat.decimalPattern(locale).format((distance * 1000).round())} m';
}
return '${NumberFormat('0.0', locale).format(distance)} km';
}
String formatRating(double rating, String locale) {
return NumberFormat('0.0', locale).format(rating);
}
String formatCount(int count, String locale) {
return NumberFormat.decimalPattern(locale).format(count);
}
String formatLocalizedNumber(double? value, String locale) {
if (value == null) return '';
return NumberFormat('0.##', locale).format(value);
}
String formatCurrencyAmount(double? value, String currency, String locale) {
if (value == null) return '';
return NumberFormat.currency(
name: currency.isEmpty ? 'EUR' : currency,
locale: locale,
decimalDigits: 2,
).format(value);
}
String formatDate(String raw, String locale, {bool? includeTime}) {
final parsed = DateTime.tryParse(raw);
if (parsed == null) return raw;
final date = parsed.toLocal();
// WordPress date fields are often serialized as YYYY-MM-DD. Appending
// midnight to those values is misleading, so only show a clock when the
// source actually contains a time component.
final hasTime =
includeTime ?? RegExp(r'[T ]\d{1,2}:\d{2}').hasMatch(raw.trim());
final formatter = hasTime
? DateFormat.yMMMd(locale).add_Hm()
: DateFormat.yMMMd(locale);
return formatter.format(date);
}
String formatOpeningHours(
OpeningHoursData openingHours,
String locale,
String closedLabel,
) {
if (!openingHours.parsed || openingHours.entries.isEmpty) {
return openingHours.raw;
}
final dayIndexes = <String, int>{
'mon': 0,
'tue': 1,
'wed': 2,
'thu': 3,
'fri': 4,
'sat': 5,
'sun': 6,
};
final dayFormatter = DateFormat.E(locale);
String dayLabel(List<String> days) {
final labels = days
.map((day) {
final index = dayIndexes[day];
return index == null
? day
: dayFormatter.format(DateTime.utc(2024, 1, index + 1));
})
.where((label) => label.isNotEmpty)
.toList(growable: false);
if (labels.length >= 2 &&
days.length >= 2 &&
dayIndexes[days.last] != null &&
dayIndexes[days.first] != null &&
dayIndexes[days.last]! - dayIndexes[days.first]! == days.length - 1) {
return '${labels.first}–${labels.last}';
}
return labels.join(', ');
}
return openingHours.entries
.map((entry) {
final label = dayLabel(entry.days);
if (entry.closed) return '$label: $closedLabel';
final slots = entry.slots
.map((slot) => '${slot.open}–${slot.close}')
.join(', ');
return '$label: $slots';
})
.join('\n');
}
