import AppKit
import MastermindPOCCore
import SwiftUI

final class SettingsWindowController {
    private let panel: NSPanel

    init(settingsStore: OverlaySettingsStore) {
        panel = NSPanel(
            contentRect: NSRect(x: 0, y: 0, width: 360, height: 160),
            styleMask: [.titled, .closable, .utilityWindow],
            backing: .buffered,
            defer: false
        )

        panel.isReleasedWhenClosed = false
        panel.hidesOnDeactivate = false
        panel.title = "Mastermind Settings"
        panel.level = .floating
        panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
        panel.contentView = NSHostingView(rootView: SettingsView(settingsStore: settingsStore))
    }

    func show() {
        panel.center()
        NSApp.activate(ignoringOtherApps: true)
        panel.makeKeyAndOrderFront(nil)
    }
}

private struct SettingsView: View {
    @ObservedObject var settingsStore: OverlaySettingsStore

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("Window")
                .font(.headline)

            VStack(alignment: .leading, spacing: 8) {
                HStack {
                    Text("Opacity")
                    Spacer()
                    Text("\(Int(settingsStore.backgroundOpacity * 100))%")
                        .font(.caption.monospacedDigit())
                        .foregroundStyle(.secondary)
                }

                Slider(
                    value: Binding(
                        get: { settingsStore.backgroundOpacity },
                        set: { settingsStore.updateBackgroundOpacity($0) }
                    ),
                    in: OverlaySettings.minimumOpacity...OverlaySettings.maximumOpacity
                )
            }

            Text("Changes apply to the HUD background only.")
                .font(.caption)
                .foregroundStyle(.secondary)
        }
        .padding(20)
        .frame(width: 360, height: 160)
    }
}
