import SwiftUI

// MARK: - ChatListCollectionView

/// SwiftUI bridge wrapping `ChatListCollectionController` (UIKit UICollectionView).
///
/// Follows the same bridge pattern as `RosettaTabBarContainer` and `NativeMessageList`:
/// - Callbacks deferred via `DispatchQueue.main.async` to avoid SwiftUI layout-pass blocking.
/// - Data updates via `updateUIViewController` trigger DiffableDataSource snapshot apply.
struct ChatListCollectionView: UIViewControllerRepresentable {

    // MARK: - Data

    let pinnedDialogs: [Dialog]
    let unpinnedDialogs: [Dialog]
    let requestsCount: Int
    let typingDialogs: [String: Set<String>]
    let isSyncing: Bool
    let isLoading: Bool

    // MARK: - Callbacks

    var onSelectDialog: ((Dialog) -> Void)?
    var onDeleteDialog: ((Dialog) -> Void)?
    var onTogglePin: ((Dialog) -> Void)?
    var onToggleMute: ((Dialog) -> Void)?
    var onPinnedStateChange: ((Bool) -> Void)?
    var onShowRequests: (() -> Void)?
    var onScrollOffsetChange: ((CGFloat) -> Void)?
    var onMarkAsRead: ((Dialog) -> Void)?

    // MARK: - UIViewControllerRepresentable

    func makeUIViewController(context: Context) -> ChatListCollectionController {
        let controller = ChatListCollectionController()
        controller.onSelectDialog = onSelectDialog
        controller.onDeleteDialog = onDeleteDialog
        controller.onTogglePin = onTogglePin
        controller.onToggleMute = onToggleMute
        controller.onPinnedStateChange = onPinnedStateChange
        controller.onShowRequests = onShowRequests
        controller.onScrollOffsetChange = onScrollOffsetChange
        controller.onMarkAsRead = onMarkAsRead
        return controller
    }

    func updateUIViewController(_ controller: ChatListCollectionController, context: Context) {
        // Update callbacks (closures may capture new state)
        controller.onSelectDialog = onSelectDialog
        controller.onDeleteDialog = onDeleteDialog
        controller.onTogglePin = onTogglePin
        controller.onToggleMute = onToggleMute
        controller.onPinnedStateChange = onPinnedStateChange
        controller.onShowRequests = onShowRequests
        controller.onScrollOffsetChange = onScrollOffsetChange
        controller.onMarkAsRead = onMarkAsRead

        // Skip data update if loading (shimmer is shown by SwiftUI)
        guard !isLoading else { return }

        // Update data and apply snapshot
        controller.updateDialogs(
            pinned: pinnedDialogs,
            unpinned: unpinnedDialogs,
            requestsCount: requestsCount,
            typingDialogs: typingDialogs,
            isSyncing: isSyncing
        )
    }
}
