//
//  PhotoBrowserManager.swift

//
//  Created by Leon on 2025/7/26.
//

import UIKit

class PhotoBrowserManager {
    public static let shared = PhotoBrowserManager()
    private var browserWindow: UIWindow?

    private init() {}

    private func getBrowserWindow() -> UIWindow {
//        if browserWindow == nil {
//            browserWindow = UIWindow(frame: UIScreen.main.bounds)
//            browserWindow?.backgroundColor = .clear
//        }
//        return browserWindow!
        guard let windowScene = UIApplication.shared.connectedScenes
            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
        else {
            return UIWindow.applicationKey!
        }
        let window = UIWindow(windowScene: windowScene)
        window.frame = UIScreen.main.bounds
        return window
    }

    static func hidePhotoBrowserWindow() {
        shared.hidePhotoBrowser()
    }

    func showPhotoBrowser(with models: [PhotoBrowserModel], currentIndex: Int) {
        showPhotoBrowser(with: models, currentIndex: currentIndex, type: .normal)
    }

    func showPhotoBrowser(with models: [PhotoBrowserModel], currentIndex: Int, type: PhotoBrowserType) {
        guard !models.isEmpty else { return }
        let safeIndex = max(0, min(currentIndex, models.count - 1))

        let window = getBrowserWindow()
        window.windowLevel = .statusBar - 2
        window.isHidden = false
        self.browserWindow = window

        let browserVC = PhotoBrowserController()
        browserVC.type = type
        browserVC.setupView(with: models, currentIndex: safeIndex)
        let navc = CLNavigationController(rootViewController: browserVC)
        window.rootViewController = navc//browserVC
    }

    func setupPhotoBrowserType(_ type: PhotoBrowserType) {
        guard let browserVC = browserWindow?.rootViewController as? PhotoBrowserController else { return }
        browserVC.type = type
    }

    func hidePhotoBrowser() {
        browserWindow?.isHidden = true
        browserWindow?.rootViewController = nil
    }

    deinit {
        print("♻️PhotoBrowserManager dealloc")
    }
}

enum ImageBrowser {
    static func show(models: [PhotoBrowserModel], index: Int, type: PhotoBrowserType) {
        PhotoBrowserManager.shared.showPhotoBrowser(with: models, currentIndex: index, type: type)
    }

    static func hide() {
        PhotoBrowserManager.hidePhotoBrowserWindow()
    }
}
