import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import 'push_actions.dart';

/// Routes foreground notification interactions from the single
/// flutter_local_notifications response callback. Action responses (reply /
/// mark-read) are dispatched straight to [PushActions]; a plain tap publishes
/// the target chat token via [pendingChatToken] for [App] to navigate to.
class PushTapRouter {
  PushTapRouter._();

  /// Chat token of the most recently tapped Talk notification, or null. [App]
  /// listens to this and opens the chat, then resets it to null.
  static final ValueNotifier<String?> pendingChatToken = ValueNotifier(null);

  /// Newsletter id of the most recently tapped Marianum-Message notification,
  /// or null. [App] listens to this and opens the message, then resets it.
  static final ValueNotifier<String?> pendingNewsletterId = ValueNotifier(null);

  static void handleResponse(NotificationResponse response) {
    final actionId = response.actionId;
    if (actionId == kTalkReplyActionId || actionId == kTalkMarkReadActionId) {
      // Reuse the isolate-safe action dispatch for foreground actions too.
      PushActions.handleBackgroundResponse(response);
      return;
    }
    final map = _payloadMap(response.payload);
    if (map == null) return;
    final newsletterId = _stringValue(map, 'newsletterId');
    if (newsletterId != null) {
      pendingNewsletterId.value = newsletterId;
      return;
    }
    final token = _stringValue(map, 'chatToken');
    if (token != null) pendingChatToken.value = token;
  }

  static Map<String, dynamic>? _payloadMap(String? payload) {
    if (payload == null || payload.isEmpty) return null;
    try {
      return jsonDecode(payload) as Map<String, dynamic>;
    } on Object {
      return null;
    }
  }

  static String? _stringValue(Map<String, dynamic> map, String key) {
    final value = map[key];
    return value is String && value.isNotEmpty ? value : null;
  }
}
