import AppKit

enum WindowActions {
    @MainActor
    static func zoomActiveWindow() {
        guard let window = NSApp.keyWindow ?? NSApp.mainWindow else { return }
        toggleMaximize(window)
    }

    @MainActor
    static func toggleMaximize(_ window: NSWindow) {
        guard let visibleFrame = window.screen?.visibleFrame ?? NSScreen.main?.visibleFrame else {
            return
        }

        let currentFrame = window.frame
        let isMaximized =
            abs(currentFrame.minX - visibleFrame.minX) < 2 &&
            abs(currentFrame.minY - visibleFrame.minY) < 2 &&
            abs(currentFrame.width - visibleFrame.width) < 2 &&
            abs(currentFrame.height - visibleFrame.height) < 2

        if isMaximized {
            let restoredSize = NSSize(
                width: min(max(window.minSize.width, 1280), visibleFrame.width),
                height: min(max(window.minSize.height, 860), visibleFrame.height)
            )
            let restoredFrame = NSRect(
                x: visibleFrame.midX - restoredSize.width / 2,
                y: visibleFrame.midY - restoredSize.height / 2,
                width: restoredSize.width,
                height: restoredSize.height
            )
            window.setFrame(restoredFrame, display: true, animate: false)
        } else {
            window.setFrame(visibleFrame, display: true, animate: false)
        }
    }

    @MainActor
    static func showMainWindow() {
        if let appDelegate = NSApp.delegate as? AppDelegate {
            appDelegate.showDashboardWindow()
            return
        }

        let mainWindow = NSApp.windows.first { window in
            window.identifier?.rawValue == "main-dashboard-window"
        } ?? NSApp.windows.first { window in
            !(window is NSPanel) && window.title == "TokenLens"
        } ?? NSApp.windows.first { window in
            !(window is NSPanel) && !window.title.contains("设置")
        }

        NSApp.windows
            .filter { $0 !== mainWindow && $0.title.contains("设置") }
            .forEach { $0.orderOut(nil) }

        NSApp.activate(ignoringOtherApps: true)
        NSApp.unhide(nil)
        if mainWindow?.isMiniaturized == true {
            mainWindow?.deminiaturize(nil)
        }
        guard let mainWindow else { return }
        mainWindow.makeKeyAndOrderFront(nil)
        mainWindow.makeMain()
        mainWindow.orderFrontRegardless()
    }
}
