import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

import '../networks/api_client.dart';

class MarketMedia {
  final int id;
  final String type;
  final String path;
  final String thumbnailPath;
  final int fileSize;

  const MarketMedia({
    required this.id,
    required this.type,
    required this.path,
    required this.thumbnailPath,
    required this.fileSize,
  });

  bool get isImage => type.toLowerCase() == 'image';

  factory MarketMedia.fromJson(Map<String, dynamic> json) {
    return MarketMedia(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      type: '${json['type'] ?? json['media_type'] ?? 'image'}',
      path: '${json['path'] ?? json['media_path'] ?? ''}',
      thumbnailPath: '${json['thumbnail_path'] ?? json['thumb_path'] ?? ''}',
      fileSize: int.tryParse('${json['file_size'] ?? 0}') ?? 0,
    );
  }
}

class MarketItem {
  final int id;
  final int? sellerUserId;
  final String title;
  final String description;
  final double price;
  final String category;
  final String condition;
  final int quantity;
  final String campus;
  final String location;
  final String sellerName;
  final String sellerPhone;
  final String sellerRole;
  final String sellerProfilePicture;
  final String status;
  final String reportReason;
  final String legacyImageUrl;
  final DateTime createdAt;
  final DateTime? updatedAt;
  final DateTime? soldAt;
  final List<MarketMedia> media;
  final int likeCount;
  final int commentCount;
  final int inquiryCount;
  final bool likedByMe;

  const MarketItem({
    required this.id,
    required this.sellerUserId,
    required this.title,
    required this.description,
    required this.price,
    required this.category,
    required this.condition,
    required this.quantity,
    required this.campus,
    required this.location,
    required this.sellerName,
    required this.sellerPhone,
    required this.sellerRole,
    required this.sellerProfilePicture,
    required this.status,
    required this.reportReason,
    required this.legacyImageUrl,
    required this.createdAt,
    required this.updatedAt,
    required this.soldAt,
    required this.media,
    required this.likeCount,
    required this.commentCount,
    required this.inquiryCount,
    required this.likedByMe,
  });

  List<MarketMedia> get images => media.where((m) => m.isImage).toList();

  factory MarketItem.fromJson(Map<String, dynamic> json) {
    final rawMedia = json['media'];
    final media = <MarketMedia>[];
    if (rawMedia is List) {
      for (final item in rawMedia) {
        if (item is Map) {
          media.add(MarketMedia.fromJson(
            item.map((key, value) => MapEntry(key.toString(), value)),
          ));
        }
      }
    }

    return MarketItem(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      sellerUserId: int.tryParse('${json['seller_user_id'] ?? ''}'),
      title: '${json['title'] ?? 'Untitled item'}',
      description: '${json['description'] ?? ''}',
      price: double.tryParse('${json['price'] ?? 0}') ?? 0,
      category: '${json['category'] ?? 'Other'}',
      condition: '${json['condition'] ?? 'Used'}',
      quantity: int.tryParse('${json['quantity'] ?? 1}') ?? 1,
      campus: '${json['campus'] ?? ''}',
      location: '${json['location'] ?? ''}',
      sellerName: '${json['seller_name'] ?? 'Rockview Member'}',
      sellerPhone: '${json['seller_phone'] ?? ''}',
      sellerRole: '${json['seller_role'] ?? 'staff'}',
      sellerProfilePicture: '${json['seller_profile_picture'] ?? ''}',
      status: '${json['status'] ?? 'pending'}',
      reportReason: '${json['report_reason'] ?? ''}',
      legacyImageUrl: '${json['image_url'] ?? json['legacy_image_url'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
      updatedAt: DateTime.tryParse('${json['updated_at'] ?? ''}'),
      soldAt: DateTime.tryParse('${json['sold_at'] ?? ''}'),
      media: media,
      likeCount: int.tryParse('${json['like_count'] ?? 0}') ?? 0,
      commentCount: int.tryParse('${json['comment_count'] ?? 0}') ?? 0,
      inquiryCount: int.tryParse('${json['inquiry_count'] ?? 0}') ?? 0,
      likedByMe: _asBool(json['liked_by_me']),
    );
  }

  MarketItem copyWith({
    int? likeCount,
    int? commentCount,
    int? inquiryCount,
    bool? likedByMe,
    String? status,
  }) {
    return MarketItem(
      id: id,
      sellerUserId: sellerUserId,
      title: title,
      description: description,
      price: price,
      category: category,
      condition: condition,
      quantity: quantity,
      campus: campus,
      location: location,
      sellerName: sellerName,
      sellerPhone: sellerPhone,
      sellerRole: sellerRole,
      sellerProfilePicture: sellerProfilePicture,
      status: status ?? this.status,
      reportReason: reportReason,
      legacyImageUrl: legacyImageUrl,
      createdAt: createdAt,
      updatedAt: updatedAt,
      soldAt: soldAt,
      media: media,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      inquiryCount: inquiryCount ?? this.inquiryCount,
      likedByMe: likedByMe ?? this.likedByMe,
    );
  }
}

class MarketComment {
  final int id;
  final int itemId;
  final int userId;
  final int? parentCommentId;
  final String comment;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final DateTime createdAt;

  const MarketComment({
    required this.id,
    required this.itemId,
    required this.userId,
    required this.parentCommentId,
    required this.comment,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.createdAt,
  });

  bool get isReply => parentCommentId != null;

  factory MarketComment.fromJson(Map<String, dynamic> json) {
    return MarketComment(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      itemId: int.tryParse('${json['item_id'] ?? 0}') ?? 0,
      userId: int.tryParse('${json['user_id'] ?? 0}') ?? 0,
      parentCommentId: int.tryParse('${json['parent_comment_id'] ?? ''}'),
      comment: '${json['comment'] ?? ''}',
      authorName: '${json['author_name'] ?? 'Rockview Member'}',
      authorRole: '${json['author_role'] ?? 'user'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }
}

class MarketMentionableUser {
  final int id;
  final String fullName;
  final String role;
  final String campus;
  final String profilePicture;

  const MarketMentionableUser({
    required this.id,
    required this.fullName,
    required this.role,
    required this.campus,
    required this.profilePicture,
  });

  factory MarketMentionableUser.fromJson(Map<String, dynamic> json) {
    return MarketMentionableUser(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      fullName: '${json['full_name'] ?? 'Rockview Member'}',
      role: '${json['role'] ?? 'user'}',
      campus: '${json['campus'] ?? ''}',
      profilePicture: '${json['profile_picture'] ?? ''}',
    );
  }
}

class MarketNotification {
  final int id;
  final int? itemId;
  final int? commentId;
  final int? actorUserId;
  final String type;
  final String title;
  final String message;
  final String actorName;
  final String actorProfilePicture;
  final bool isRead;
  final DateTime createdAt;

  const MarketNotification({
    required this.id,
    required this.itemId,
    required this.commentId,
    required this.actorUserId,
    required this.type,
    required this.title,
    required this.message,
    required this.actorName,
    required this.actorProfilePicture,
    required this.isRead,
    required this.createdAt,
  });

  factory MarketNotification.fromJson(Map<String, dynamic> json) {
    return MarketNotification(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      itemId: int.tryParse('${json['item_id'] ?? ''}'),
      commentId: int.tryParse('${json['comment_id'] ?? ''}'),
      actorUserId: int.tryParse('${json['actor_user_id'] ?? ''}'),
      type: '${json['type'] ?? 'general'}',
      title: '${json['title'] ?? 'Marketplace notification'}',
      message: '${json['message'] ?? ''}',
      actorName: '${json['actor_name'] ?? ''}',
      actorProfilePicture: '${json['actor_profile_picture'] ?? ''}',
      isRead: _asBool(json['is_read']),
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }
}

class MarketPage {
  final List<MarketItem> items;
  final int page;
  final int limit;
  final int total;
  final bool hasMore;

  const MarketPage({
    required this.items,
    required this.page,
    required this.limit,
    required this.total,
    required this.hasMore,
  });
}

class MarketNotificationPage {
  final List<MarketNotification> items;
  final int unreadCount;

  const MarketNotificationPage({required this.items, required this.unreadCount});
}

class CampusMarketService {
  static const List<String> categories = <String>[
    'Electronics',
    'Phones & Accessories',
    'Computers',
    'Home & Office',
    'Fashion',
    'Books',
    'Food & Produce',
    'Furniture',
    'Vehicles & Parts',
    'Services',
    'Other',
  ];

  static const List<String> conditions = <String>[
    'New',
    'Like New',
    'Used - Excellent',
    'Used - Good',
    'Used - Fair',
  ];

  static String mediaUrl(String raw) {
    final value = raw.trim();
    if (value.isEmpty) return '';
    if (value.startsWith('http://') || value.startsWith('https://')) return value;
    final normalized = value.startsWith('/') ? value.substring(1) : value;
    return '${ApiClient.baseUrl}/$normalized';
  }

  static bool isStoredPath(String raw) {
    final value = raw.trim().replaceAll('\\', '/');
    return value.startsWith('uploads/') || value.startsWith('/uploads/');
  }

  static Future<List<String>> getCampuses() async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/campuses.php'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) return const <String>[];
    final decoded = _decode(response);
    dynamic rows = decoded;
    if (decoded is Map) rows = decoded['campuses'] ?? decoded['data'] ?? const [];
    if (rows is! List) return const <String>[];
    final result = <String>[];
    for (final item in rows) {
      if (item is Map) {
        final name = '${item['name'] ?? ''}'.trim();
        if (name.isNotEmpty && !result.contains(name)) result.add(name);
      }
    }
    result.sort();
    return result;
  }

  static Future<Map<String, dynamic>> getCurrentUser() async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/users.php/me'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load your account.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return decoded.map((key, value) => MapEntry(key.toString(), value));
    }
    throw const FormatException('Invalid current-user response.');
  }

  static Future<MarketPage> getItems({
    String status = 'active',
    bool mine = false,
    bool moderation = false,
    String? category,
    String? campus,
    String? search,
    int page = 1,
    int limit = 12,
  }) async {
    final params = <String, String>{
      'status': status,
      'page': '$page',
      'limit': '$limit',
    };
    if (mine) params['mine'] = '1';
    if (moderation) params['moderation'] = '1';
    if (category != null && category.trim().isNotEmpty && category != 'All Categories') {
      params['category'] = category.trim();
    }
    if (campus != null && campus.trim().isNotEmpty && campus != 'All Campuses') {
      params['campus'] = campus.trim();
    }
    if (search != null && search.trim().isNotEmpty) params['q'] = search.trim();

    final uri = Uri.parse('${ApiClient.baseUrl}/api/market_feed.php')
        .replace(queryParameters: params);
    final response = await ApiClient.offlineFirstGet(uri, headers: await ApiClient.getHeaders())
        .timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load marketplace items.'));
    }

    final decoded = _decode(response);
    dynamic rows = decoded;
    Map<String, dynamic> pagination = <String, dynamic>{};
    if (decoded is Map) {
      rows = decoded['data'] ?? const [];
      if (decoded['pagination'] is Map) {
        pagination = Map<String, dynamic>.from(decoded['pagination'] as Map);
      }
    }
    if (rows is! List) throw const FormatException('Marketplace returned invalid data.');

    final items = rows
        .whereType<Map>()
        .map((e) => MarketItem.fromJson(
              e.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();

    return MarketPage(
      items: items,
      page: int.tryParse('${pagination['page'] ?? page}') ?? page,
      limit: int.tryParse('${pagination['limit'] ?? limit}') ?? limit,
      total: int.tryParse('${pagination['total'] ?? items.length}') ?? items.length,
      hasMore: pagination.containsKey('has_more')
          ? _asBool(pagination['has_more'])
          : items.length >= limit,
    );
  }

  static Future<int> createItem({
    required String title,
    required String description,
    required double price,
    required String category,
    required String condition,
    required int quantity,
    required String sellerPhone,
    required String location,
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_feed.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({
        'title': title.trim(),
        'description': description.trim(),
        'price': price,
        'category': category,
        'condition': condition,
        'quantity': quantity,
        'seller_phone': sellerPhone.trim(),
        'location': location.trim(),
      }),
    ).timeout(const Duration(seconds: 25));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to create listing.'));
    }
    final decoded = _decode(response);
    if (decoded is Map) {
      return int.tryParse('${decoded['id'] ?? 0}') ?? 0;
    }
    throw const FormatException('Create listing returned invalid data.');
  }

  static Future<void> updateItem(int id, Map<String, dynamic> changes) async {
    final response = await http.put(
      Uri.parse('${ApiClient.baseUrl}/api/market_feed.php?id=$id'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(changes),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update listing.'));
    }
  }

  static Future<void> deleteItem(int id) async {
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/market_feed.php?id=$id'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to delete listing.'));
    }
  }

  static Future<List<MarketMedia>> uploadImages(int itemId, List<XFile> files) async {
    if (files.isEmpty) return const <MarketMedia>[];
    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/market_media.php'),
    );
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['item_id'] = '$itemId';

    for (final file in files) {
      final bytes = await file.readAsBytes();
      request.files.add(http.MultipartFile.fromBytes(
        'images[]',
        bytes,
        filename: file.name,
      ));
    }

    final streamed = await request.send().timeout(const Duration(seconds: 60));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200 && response.statusCode != 201) {
      throw Exception(_errorMessage(response, 'Unable to upload listing images.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] : null;
    if (rows is! List) return const <MarketMedia>[];
    return rows
        .whereType<Map>()
        .map((e) => MarketMedia.fromJson(
              e.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

  static Future<void> deleteMedia(int mediaId) async {
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/market_media.php?id=$mediaId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to delete listing image.'));
    }
  }

  static Future<Map<String, dynamic>> toggleLike(int itemId) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_likes.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({'item_id': itemId}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update like.'));
    }
    final decoded = _decode(response);
    return decoded is Map ? Map<String, dynamic>.from(decoded) : <String, dynamic>{};
  }

  static Future<List<MarketComment>> getComments(int itemId) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/market_comments.php?item_id=$itemId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load comments.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] : decoded;
    if (rows is! List) return const <MarketComment>[];
    return rows
        .whereType<Map>()
        .map((e) => MarketComment.fromJson(
              e.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

  static Future<MarketComment> addComment(
    int itemId,
    String comment, {
    int? parentCommentId,
    List<int> mentionUserIds = const <int>[],
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_comments.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({
        'item_id': itemId,
        'comment': comment.trim(),
        if (parentCommentId != null) 'parent_comment_id': parentCommentId,
        if (mentionUserIds.isNotEmpty) 'mention_user_ids': mentionUserIds,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to post comment.'));
    }
    final decoded = _decode(response);
    dynamic payload = decoded;
    if (decoded is Map) payload = decoded['data'] ?? decoded;
    if (payload is! Map) throw const FormatException('Invalid comment response.');
    return MarketComment.fromJson(
      payload.map((key, value) => MapEntry(key.toString(), value)),
    );
  }

  static Future<List<MarketMentionableUser>> getMentionableUsers(
    int itemId, {
    String query = '',
  }) async {
    final params = <String, String>{'item_id': '$itemId'};
    if (query.trim().isNotEmpty) params['q'] = query.trim();
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/market_mentions.php')
          .replace(queryParameters: params),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) return const <MarketMentionableUser>[];
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] : decoded;
    if (rows is! List) return const <MarketMentionableUser>[];
    return rows
        .whereType<Map>()
        .map((e) => MarketMentionableUser.fromJson(
              e.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

  static Future<MarketNotificationPage> getNotifications({int limit = 30}) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/market_notifications.php?limit=$limit'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to load marketplace notifications.'));
    }
    final decoded = _decode(response);
    final rows = decoded is Map ? decoded['data'] : null;
    final unread = decoded is Map ? int.tryParse('${decoded['unread_count'] ?? 0}') ?? 0 : 0;
    if (rows is! List) {
      return MarketNotificationPage(items: const <MarketNotification>[], unreadCount: unread);
    }
    return MarketNotificationPage(
      items: rows
          .whereType<Map>()
          .map((e) => MarketNotification.fromJson(
                e.map((key, value) => MapEntry(key.toString(), value)),
              ))
          .toList(),
      unreadCount: unread,
    );
  }

  static Future<void> markNotificationRead(int id) async {
    final response = await http.put(
      Uri.parse('${ApiClient.baseUrl}/api/market_notifications.php?id=$id'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({'is_read': true}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to update notification.'));
    }
  }

  static Future<void> markAllNotificationsRead() async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_notifications.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({'action': 'mark_all_read'}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to mark notifications as read.'));
    }
  }

  static Future<void> sendInquiry(int itemId, String message) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_inquiries.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({
        'item_id': itemId,
        'message': message.trim(),
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to contact seller.'));
    }
  }

  static Future<void> reportItem(int itemId, String reason) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_reports.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({
        'item_id': itemId,
        'reason': reason.trim(),
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to report listing.'));
    }
  }

  static Future<void> moderateItem(int itemId, String action) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/market_reports.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode({
        'item_id': itemId,
        'action': action,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, 'Unable to moderate listing.'));
    }
  }
}

dynamic _decode(http.Response response) {
  final body = response.body.trim();
  if (body.isEmpty) return <String, dynamic>{};
  return jsonDecode(body);
}

String _errorMessage(http.Response response, String fallback) {
  try {
    final data = _decode(response);
    if (data is Map) {
      final value = '${data['detail'] ?? data['error'] ?? data['message'] ?? ''}'.trim();
      if (value.isNotEmpty) return value;
    }
  } catch (_) {}
  return fallback;
}

bool _asBool(dynamic value) {
  if (value is bool) return value;
  if (value is num) return value != 0;
  final text = '${value ?? ''}'.trim().toLowerCase();
  return text == '1' || text == 'true' || text == 't' || text == 'yes';
}
