import Combine
import Foundation
import UIKit

/// Telegram-parity in-app notification banner manager.
/// Shows a floating banner at the top of the screen when a message arrives
/// in foreground for a non-active, non-muted chat.
///
/// Queue: one banner at a time. New banner replaces current.
/// Auto-dismiss: 5 seconds. Swipe-up or tap dismisses immediately.
@MainActor
final class InAppBannerManager: ObservableObject {

    static let shared = InAppBannerManager()

    @Published var currentBanner: BannerData?

    private var dismissTask: Task<Void, Never>?

    /// Notification posted by SessionManager.processIncomingMessage
    /// when a foreground message should trigger an in-app banner.
    static let showBannerNotification = Notification.Name("InAppBannerManager.showBanner")

    private init() {
        NotificationCenter.default.addObserver(
            forName: Self.showBannerNotification,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let data = notification.object as? BannerData else { return }
            Task { @MainActor [weak self] in
                self?.show(data)
            }
        }
    }

    func show(_ data: BannerData) {
        // Replace current banner.
        dismissTask?.cancel()
        currentBanner = data

        // Auto-dismiss after 5 seconds (Telegram parity).
        dismissTask = Task {
            try? await Task.sleep(for: .seconds(5))
            guard !Task.isCancelled else { return }
            dismiss()
        }
    }

    func dismiss() {
        dismissTask?.cancel()
        currentBanner = nil
    }

    // MARK: - Data

    struct BannerData: Identifiable {
        let senderKey: String
        let senderName: String
        let messagePreview: String
        let isGroup: Bool
        let verified: Int

        var id: String { senderKey }
    }
}
