import AppKit
import CoreGraphics

@MainActor
public enum OverlayWindowPolicy {
    public static let styleMask: NSWindow.StyleMask = [
        .borderless,
        .fullSizeContentView,
        .nonactivatingPanel
    ]

    public static let collectionBehavior: NSWindow.CollectionBehavior = [
        .canJoinAllSpaces,
        .fullScreenAuxiliary,
        .stationary,
        .transient,
        .ignoresCycle
    ]

    public static let levelOffsetBelowMainMenu: CGWindowLevel = 1

    public static var quickSwitchLevel: NSWindow.Level {
        let mainMenuLevel = CGWindowLevelForKey(.mainMenuWindow)
        return NSWindow.Level(rawValue: Int(mainMenuLevel - levelOffsetBelowMainMenu))
    }

    public static var currentLevel: CGWindowLevel {
        CGWindowLevel(quickSwitchLevel.rawValue)
    }

    public static func apply(to panel: NSPanel, on screen: NSScreen?) {
        panel.styleMask = styleMask
        panel.collectionBehavior = collectionBehavior
        panel.level = quickSwitchLevel
        panel.hidesOnDeactivate = false
        panel.isReleasedWhenClosed = false
        panel.isOpaque = false
        panel.backgroundColor = .clear

        if let screen {
            panel.setFrame(screen.frame, display: false)
        }
    }

    public static func isBelowRescueSystemWindows(_ level: NSWindow.Level = quickSwitchLevel) -> Bool {
        level.rawValue < Int(CGWindowLevelForKey(.mainMenuWindow))
    }
}
