import AppKit
import SwiftUI

/// Singleton controller that manages the settings window.
/// When the settings panel opens, the app becomes a regular app
/// (visible in Dock / Cmd-Tab). When it closes, the app reverts
/// to an accessory (menu-bar-only) app.
class SettingsWindowController: NSObject, NSWindowDelegate {

    static let shared = SettingsWindowController()

    private var window: NSWindow?

    private override init() {
        super.init()
    }

    // MARK: - Show / Hide

    func showSettings() {
        if let existing = window {
            existing.makeKeyAndOrderFront(nil)
            NSApp.activate(ignoringOtherApps: true)
            return
        }

        let settingsView = SettingsView()
        let hostingView = NSHostingView(rootView: settingsView)

        let win = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 700, height: 500),
            styleMask: [.titled, .closable, .resizable],
            backing: .buffered,
            defer: false
        )
        win.title = "CommandNotch Settings"
        win.identifier = NSUserInterfaceItemIdentifier("settings.window")
        win.contentView = hostingView
        win.center()
        win.delegate = self
        win.isReleasedWhenClosed = false

        // Appear in Dock while settings are open
        NSApp.setActivationPolicy(.regular)

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

        window = win
    }

    // MARK: - NSWindowDelegate

    func windowWillClose(_ notification: Notification) {
        // Revert to accessory (menu-bar-only) mode
        NSApp.setActivationPolicy(.accessory)
        window = nil
    }
}
