import UIKit

// MARK: - Data Types

struct ViewableImageInfo: Equatable, Identifiable {
    let attachmentId: String
    let messageId: String
    let senderName: String
    let timestamp: Date
    let caption: String
    var id: String { attachmentId }
}

struct ImageViewerState: Equatable {
    let images: [ViewableImageInfo]
    let initialIndex: Int
    let sourceFrame: CGRect
}

// MARK: - ImageViewerPresenter

@MainActor
final class ImageViewerPresenter {
    static let shared = ImageViewerPresenter()
    private weak var presentedController: GalleryViewController?
    var onShowInChat: ((String) -> Void)?

    func present(state: ImageViewerState, sourceView: UIView? = nil) {
        guard presentedController == nil else { return }

        let galleryVC = GalleryViewController(state: state, sourceView: sourceView)
        galleryVC.onShowInChat = { [weak self] messageId in
            self?.onShowInChat?(messageId)
        }

        guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let root = scene.keyWindow?.rootViewController else { return }

        var presenter = root
        while let p = presenter.presentedViewController { presenter = p }
        presenter.present(galleryVC, animated: false)
        presentedController = galleryVC
    }

    func dismiss() {
        presentedController?.dismiss(animated: false)
        presentedController = nil
    }
}
