import 'dart:convert';

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

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

class CampusNewsImage {
  final int id;
  final String path;
  final String thumbnailPath;

  const CampusNewsImage({
    required this.id,
    required this.path,
    this.thumbnailPath = '',
  });

  String get previewPath => thumbnailPath.trim().isNotEmpty ? thumbnailPath : path;

  factory CampusNewsImage.fromJson(Map<String, dynamic> json) {
    return CampusNewsImage(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      path: '${json['path'] ?? json['image_path'] ?? ''}',
      thumbnailPath: '${json['thumbnail_path'] ?? json['thumbnail'] ?? ''}',
    );
  }
}

class CampusNewsVideo {
  final int id;
  final String path;
  final String fileName;
  final String mimeType;
  final int sizeBytes;
  final DateTime? createdAt;

  const CampusNewsVideo({
    required this.id,
    required this.path,
    required this.fileName,
    required this.mimeType,
    required this.sizeBytes,
    this.createdAt,
  });

  factory CampusNewsVideo.fromJson(Map<String, dynamic> json) {
    return CampusNewsVideo(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      path: '${json['path'] ?? json['video_path'] ?? ''}',
      fileName: '${json['file_name'] ?? json['original_name'] ?? 'Campus video'}',
      mimeType: '${json['mime_type'] ?? 'video/mp4'}',
      sizeBytes: int.tryParse('${json['size_bytes'] ?? json['video_size'] ?? 0}') ?? 0,
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}'),
    );
  }

  String get formattedSize => CampusNewsService.formatBytes(sizeBytes);
}

class CampusNewsArticle {
  final int id;
  final int authorId;
  final String title;
  final String body;
  final String category;
  final String campus;
  final String school;
  final String department;
  final String status;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final DateTime createdAt;
  final DateTime? publishedAt;
  final DateTime? updatedAt;
  final List<CampusNewsImage> images;
  final CampusNewsVideo? video;
  final int likeCount;
  final int commentCount;
  final bool likedByMe;
  final bool isTrending;

  const CampusNewsArticle({
    required this.id,
    required this.authorId,
    required this.title,
    required this.body,
    required this.category,
    required this.campus,
    required this.school,
    required this.department,
    required this.status,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.createdAt,
    required this.publishedAt,
    required this.updatedAt,
    required this.images,
    required this.video,
    required this.likeCount,
    required this.commentCount,
    required this.likedByMe,
    required this.isTrending,
  });

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

    CampusNewsVideo? video;
    final rawVideo = json['video'];
    if (rawVideo is Map) {
      final mapped = rawVideo.map((key, value) => MapEntry(key.toString(), value));
      if ('${mapped['path'] ?? mapped['video_path'] ?? ''}'.trim().isNotEmpty) {
        video = CampusNewsVideo.fromJson(mapped);
      }
    } else if (json['videos'] is List && (json['videos'] as List).isNotEmpty) {
      final first = (json['videos'] as List).first;
      if (first is Map) {
        video = CampusNewsVideo.fromJson(
          first.map((key, value) => MapEntry(key.toString(), value)),
        );
      }
    }

    return CampusNewsArticle(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      authorId: int.tryParse('${json['author_id'] ?? 0}') ?? 0,
      title: '${json['title'] ?? ''}',
      body: '${json['body'] ?? json['content'] ?? ''}',
      category: '${json['category'] ?? 'General'}',
      campus: '${json['campus'] ?? ''}',
      school: '${json['school'] ?? ''}',
      department: '${json['department'] ?? json['program'] ?? ''}',
      status: '${json['status'] ?? 'published'}',
      authorName: '${json['author_name'] ?? 'Rockview User'}',
      authorRole: '${json['author_role'] ?? 'user'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
      publishedAt: DateTime.tryParse('${json['published_at'] ?? ''}'),
      updatedAt: DateTime.tryParse('${json['updated_at'] ?? ''}'),
      images: images,
      video: video,
      likeCount: int.tryParse('${json['like_count'] ?? 0}') ?? 0,
      commentCount: int.tryParse('${json['comment_count'] ?? 0}') ?? 0,
      likedByMe: _asBool(json['liked_by_me']),
      isTrending: _asBool(json['is_trending'] ?? json['isTrending']),
    );
  }

  CampusNewsArticle copyWith({
    int? likeCount,
    int? commentCount,
    bool? likedByMe,
    bool? isTrending,
    List<CampusNewsImage>? images,
    CampusNewsVideo? video,
    bool clearVideo = false,
  }) {
    return CampusNewsArticle(
      id: id,
      authorId: authorId,
      title: title,
      body: body,
      category: category,
      campus: campus,
      school: school,
      department: department,
      status: status,
      authorName: authorName,
      authorRole: authorRole,
      authorProfilePicture: authorProfilePicture,
      createdAt: createdAt,
      publishedAt: publishedAt,
      updatedAt: updatedAt,
      images: images ?? this.images,
      video: clearVideo ? null : (video ?? this.video),
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      likedByMe: likedByMe ?? this.likedByMe,
      isTrending: isTrending ?? this.isTrending,
    );
  }
}

class CampusNewsComment {
  final int id;
  final int newsId;
  final int userId;
  final int? parentCommentId;
  final String replyToAuthorName;
  final String authorName;
  final String authorRole;
  final String authorProfilePicture;
  final String comment;
  final DateTime createdAt;

  const CampusNewsComment({
    required this.id,
    required this.newsId,
    required this.userId,
    required this.parentCommentId,
    required this.replyToAuthorName,
    required this.authorName,
    required this.authorRole,
    required this.authorProfilePicture,
    required this.comment,
    required this.createdAt,
  });

  factory CampusNewsComment.fromJson(Map<String, dynamic> json) {
    return CampusNewsComment(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      newsId: int.tryParse('${json['news_id'] ?? 0}') ?? 0,
      userId: int.tryParse('${json['user_id'] ?? 0}') ?? 0,
      parentCommentId: json['parent_comment_id'] == null
          ? null
          : int.tryParse('${json['parent_comment_id']}'),
      replyToAuthorName: '${json['reply_to_author_name'] ?? ''}',
      authorName: '${json['author_name'] ?? 'Rockview User'}',
      authorRole: '${json['author_role'] ?? 'user'}',
      authorProfilePicture: '${json['author_profile_picture'] ?? ''}',
      comment: '${json['comment'] ?? ''}',
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }
}

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

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

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

class CampusNewsNotification {
  final int id;
  final int newsId;
  final int? commentId;
  final int? actorUserId;
  final String type;
  final String actorName;
  final String actorProfilePicture;
  final String articleTitle;
  final String commentPreview;
  final bool isRead;
  final DateTime createdAt;

  const CampusNewsNotification({
    required this.id,
    required this.newsId,
    required this.commentId,
    required this.actorUserId,
    required this.type,
    required this.actorName,
    required this.actorProfilePicture,
    required this.articleTitle,
    required this.commentPreview,
    required this.isRead,
    required this.createdAt,
  });

  factory CampusNewsNotification.fromJson(Map<String, dynamic> json) {
    return CampusNewsNotification(
      id: int.tryParse('${json['id'] ?? 0}') ?? 0,
      newsId: int.tryParse('${json['news_id'] ?? 0}') ?? 0,
      commentId: json['comment_id'] == null ? null : int.tryParse('${json['comment_id']}'),
      actorUserId: json['actor_user_id'] == null ? null : int.tryParse('${json['actor_user_id']}'),
      type: '${json['type'] ?? 'comment'}',
      actorName: '${json['actor_name'] ?? 'Rockview User'}',
      actorProfilePicture: '${json['actor_profile_picture'] ?? ''}',
      articleTitle: '${json['article_title'] ?? ''}',
      commentPreview: '${json['comment_preview'] ?? ''}',
      isRead: _asBool(json['is_read']),
      createdAt: DateTime.tryParse('${json['created_at'] ?? ''}') ?? DateTime.now(),
    );
  }

  CampusNewsNotification copyWith({bool? isRead}) {
    return CampusNewsNotification(
      id: id,
      newsId: newsId,
      commentId: commentId,
      actorUserId: actorUserId,
      type: type,
      actorName: actorName,
      actorProfilePicture: actorProfilePicture,
      articleTitle: articleTitle,
      commentPreview: commentPreview,
      isRead: isRead ?? this.isRead,
      createdAt: createdAt,
    );
  }
}

class CampusNewsPage {
  final List<CampusNewsArticle> articles;
  final int page;
  final int limit;
  final int total;
  final bool hasMore;

  const CampusNewsPage({
    required this.articles,
    required this.page,
    required this.limit,
    required this.total,
    required this.hasMore,
  });
}

class CampusNewsNotificationPage {
  final List<CampusNewsNotification> notifications;
  final int unreadCount;

  const CampusNewsNotificationPage({
    required this.notifications,
    required this.unreadCount,
  });
}

class CampusNewsService {
  static const int maxVideoBytes = 10 * 1024 * 1024;

  static const List<String> categories = <String>[
    'Announcement',
    'Academic',
    'Research',
    'Events',
    'Sports',
    'Student Life',
    'Achievement',
    'Community',
    'General',
  ];

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

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

  static String formatBytes(int bytes) {
    if (bytes <= 0) return '0 MB';
    final mb = bytes / (1024 * 1024);
    if (mb >= 1) return '${mb.toStringAsFixed(mb >= 10 ? 0 : 1)} MB';
    final kb = bytes / 1024;
    return '${kb.toStringAsFixed(0)} KB';
  }

  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 data = _decodeJson(response);
    dynamic rows = data;
    if (data is Map) rows = data['campuses'] ?? data['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);
      } else if (item != null) {
        final name = '$item'.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, fallback: 'Unable to load your account.'));
    }
    final data = _decodeJson(response);
    if (data is Map) return data.map((key, value) => MapEntry(key.toString(), value));
    throw const FormatException('Current-user endpoint returned invalid JSON.');
  }

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

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

    final data = _decodeJson(response);
    dynamic rows = data;
    Map<String, dynamic> pagination = <String, dynamic>{};
    if (data is Map) {
      rows = data['data'] ?? data['news'] ?? const [];
      if (data['pagination'] is Map) {
        pagination = (data['pagination'] as Map).map((key, value) => MapEntry(key.toString(), value));
      }
    }
    if (rows is! List) throw const FormatException('News endpoint did not return a list.');

    final articles = rows
        .whereType<Map>()
        .map((item) => CampusNewsArticle.fromJson(
              item.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();

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

  static Future<CampusNewsArticle> getArticle(int id) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/news.php/$id'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to load the news article.'));
    }
    final data = _decodeJson(response);
    if (data is Map) {
      return CampusNewsArticle.fromJson(data.map((key, value) => MapEntry(key.toString(), value)));
    }
    throw const FormatException('News article endpoint returned invalid JSON.');
  }

  static Future<int> createNews({
    required String title,
    required String body,
    required String category,
    String status = 'draft',
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/news.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'title': title.trim(),
        'body': body.trim(),
        'category': category.trim(),
        'status': status,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to create the news post.'));
    }
    final data = _decodeJson(response);
    if (data is Map) return int.tryParse('${data['id'] ?? 0}') ?? 0;
    throw const FormatException('Create-news endpoint returned invalid JSON.');
  }

  static Future<void> updateNews(int id, Map<String, dynamic> changes) async {
    final response = await http.put(
      Uri.parse('${ApiClient.baseUrl}/api/news.php/$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, fallback: 'Unable to update the news post.'));
    }
  }

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

  static Future<List<CampusNewsImage>> uploadImages(int newsId, List<XFile> files) async {
    if (files.isEmpty) return const <CampusNewsImage>[];

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/news_images.php'),
    );
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['news_id'] = '$newsId';
    for (final file in files) {
      request.files.add(await http.MultipartFile.fromPath('images[]', file.path));
    }

    final streamed = await request.send().timeout(const Duration(seconds: 60));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to upload the images.'));
    }

    final data = _decodeJson(response);
    final rows = data is Map ? data['images'] ?? data['data'] ?? const [] : const [];
    if (rows is! List) return const <CampusNewsImage>[];
    return rows
        .whereType<Map>()
        .map((item) => CampusNewsImage.fromJson(
              item.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

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

  static Future<CampusNewsVideo> uploadVideo(int newsId, XFile file) async {
    // Offline uploads may restore an XFile from saved bytes, with no disk path.
    final bytes = await file.readAsBytes();
    final size = bytes.length;
    if (size > maxVideoBytes) {
      throw Exception('Video must not exceed 10 MB. Selected file is ${formatBytes(size)}.');
    }

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('${ApiClient.baseUrl}/api/news_videos.php'),
    );
    final headers = await ApiClient.getHeaders();
    headers.remove('Content-Type');
    request.headers.addAll(headers);
    request.fields['news_id'] = '$newsId';
    final filename = file.name.trim().isEmpty ? 'campus_video.mp4' : file.name;
    request.files.add(http.MultipartFile.fromBytes('video', bytes, filename: filename));

    final streamed = await request.send().timeout(const Duration(seconds: 90));
    final response = await http.Response.fromStream(streamed);
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to upload the video.'));
    }

    final data = _decodeJson(response);
    final raw = data is Map ? data['video'] ?? data['data'] : null;
    if (raw is Map) {
      return CampusNewsVideo.fromJson(raw.map((key, value) => MapEntry(key.toString(), value)));
    }
    throw const FormatException('Video upload endpoint returned invalid JSON.');
  }

  static Future<void> deleteVideo(int videoId) async {
    final response = await http.delete(
      Uri.parse('${ApiClient.baseUrl}/api/news_videos.php/$videoId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to remove the video.'));
    }
  }

  static Future<List<CampusNewsComment>> getComments(int newsId) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/news_comments.php?news_id=$newsId'),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to load comments.'));
    }

    final data = _decodeJson(response);
    final rows = data is Map ? data['data'] ?? data['comments'] ?? const [] : data;
    if (rows is! List) return const <CampusNewsComment>[];
    return rows
        .whereType<Map>()
        .map((item) => CampusNewsComment.fromJson(
              item.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

  static Future<CampusNewsComment> addComment(
    int newsId,
    String comment, {
    int? parentCommentId,
    List<int>? mentionUserIds,
  }) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/news_comments.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'news_id': newsId,
        'comment': comment.trim(),
        if (parentCommentId != null) 'parent_comment_id': parentCommentId,
        if (mentionUserIds != null && 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, fallback: 'Unable to post the comment.'));
    }

    final data = _decodeJson(response);
    final raw = data is Map ? data['comment'] ?? data['data'] ?? data : data;
    if (raw is Map) {
      return CampusNewsComment.fromJson(raw.map((key, value) => MapEntry(key.toString(), value)));
    }
    throw const FormatException('Comment endpoint returned invalid JSON.');
  }

  static Future<Map<String, dynamic>> toggleLike(int newsId) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/news_likes.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{'news_id': newsId}),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to update the like.'));
    }
    final data = _decodeJson(response);
    if (data is Map) return data.map((key, value) => MapEntry(key.toString(), value));
    return <String, dynamic>{};
  }

  static Future<List<MentionUser>> searchMentionUsers(String query) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/news_mentions.php').replace(
        queryParameters: <String, String>{'q': query.trim()},
      ),
      headers: await ApiClient.getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) return const <MentionUser>[];

    final data = _decodeJson(response);
    final rows = data is Map ? data['data'] ?? data['users'] ?? const [] : data;
    if (rows is! List) return const <MentionUser>[];
    return rows
        .whereType<Map>()
        .map((item) => MentionUser.fromJson(
              item.map((key, value) => MapEntry(key.toString(), value)),
            ))
        .toList();
  }

  static Future<CampusNewsNotificationPage> getNotifications({int limit = 30}) async {
    final response = await ApiClient.offlineFirstGet(
      Uri.parse('${ApiClient.baseUrl}/api/news_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, fallback: 'Unable to load notifications.'));
    }

    final data = _decodeJson(response);
    final rows = data is Map ? data['data'] ?? data['notifications'] ?? const [] : const [];
    final unread = data is Map ? int.tryParse('${data['unread_count'] ?? 0}') ?? 0 : 0;
    return CampusNewsNotificationPage(
      notifications: rows is List
          ? rows
              .whereType<Map>()
              .map((item) => CampusNewsNotification.fromJson(
                    item.map((key, value) => MapEntry(key.toString(), value)),
                  ))
              .toList()
          : const <CampusNewsNotification>[],
      unreadCount: unread,
    );
  }

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

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

  /// Requests a short-lived signed URL, then hands the actual file transfer to
  /// the operating system/browser. This keeps large downloads out of Flutter RAM.
  static Future<void> downloadPhotos(int newsId) async {
    final url = await _requestDownloadUrl(newsId, 'images');
    await _launchExternalDownload(url);
  }

  static Future<void> downloadVideo(int newsId) async {
    final url = await _requestDownloadUrl(newsId, 'video');
    await _launchExternalDownload(url);
  }

  static Future<String> _requestDownloadUrl(int newsId, String type) async {
    final response = await http.post(
      Uri.parse('${ApiClient.baseUrl}/api/news_download_ticket.php'),
      headers: await ApiClient.getHeaders(),
      body: jsonEncode(<String, dynamic>{
        'news_id': newsId,
        'type': type,
      }),
    ).timeout(const Duration(seconds: 20));
    await ApiClient.handleUnauthorized(response);
    if (response.statusCode != 200) {
      throw Exception(_errorMessage(response, fallback: 'Unable to prepare the download.'));
    }

    final data = _decodeJson(response);
    final path = data is Map ? '${data['url'] ?? ''}'.trim() : '';
    if (path.isEmpty) throw const FormatException('Download endpoint did not return a URL.');
    if (path.startsWith('http://') || path.startsWith('https://')) return path;
    final clean = path.startsWith('/') ? path.substring(1) : path;
    return '${ApiClient.baseUrl}/$clean';
  }

  static Future<void> _launchExternalDownload(String url) async {
    final uri = Uri.parse(url);
    final opened = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!opened) throw Exception('Unable to open the system download handler.');
  }
}

dynamic _decodeJson(http.Response response) {
  final body = response.body.trim();
  if (body.isEmpty) return const <String, dynamic>{};
  try {
    return jsonDecode(body);
  } catch (_) {
    throw FormatException('Server returned invalid JSON (HTTP ${response.statusCode}).');
  }
}

String _errorMessage(http.Response response, {required String fallback}) {
  try {
    final data = _decodeJson(response);
    if (data is Map) {
      final message = '${data['detail'] ?? data['message'] ?? data['error'] ?? ''}'.trim();
      if (message.isNotEmpty) return message;
    }
  } 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' || text == 'y';
}
