import AppKit
import SwiftUI

/// Hosts SettingsView in a real window. The app is a menu-bar accessory, so it has to
/// activate itself explicitly or the window opens behind whatever you were using.
@MainActor
final class SettingsWindowController {
    private var window: NSWindow?

    func show(store: SettingsStore) {
        if let window {
            place(window)
            NSApp.activate(ignoringOtherApps: true)
            window.makeKeyAndOrderFront(nil)
            return
        }

        let hosting = NSHostingController(rootView: SettingsView(store: store))
        let win = NSWindow(contentViewController: hosting)
        win.title = "Alien Reminder by Incuv8or"
        win.styleMask = [.titled, .closable, .miniaturizable]
        win.isReleasedWhenClosed = false
        // Follow you onto whichever Space you're on rather than yanking you to another.
        win.collectionBehavior.insert(.moveToActiveSpace)
        window = win

        place(win)
        NSApp.activate(ignoringOtherApps: true)
        win.makeKeyAndOrderFront(nil)
    }

    /// Centres on the screen the pointer is on, then clamps inside that screen's
    /// visible area. `NSWindow.center()` can land off-screen on multi-display setups
    /// where a second display sits above the built-in one.
    private func place(_ window: NSWindow) {
        let mouse = NSEvent.mouseLocation
        let screen = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) }
            ?? NSScreen.main
            ?? NSScreen.screens.first
        guard let screen else { return }

        let visible = screen.visibleFrame
        let size = window.frame.size
        var origin = NSPoint(
            x: visible.midX - size.width / 2,
            y: visible.midY - size.height / 2)

        origin.x = min(max(origin.x, visible.minX), max(visible.minX, visible.maxX - size.width))
        origin.y = min(max(origin.y, visible.minY), max(visible.minY, visible.maxY - size.height))

        window.setFrameOrigin(origin)
    }
}
