import AppKit
import CoreGraphics
import MastermindPOCCore
import SwiftUI

final class OverlayWindowController {
    let viewModel = OverlayViewModel()

    private let panel: NSPanel
    private var clickThroughEnabled = false

    init(initialSettings: OverlaySettings, actions: OverlayActions) {
        let screenFrame = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1280, height: 800)
        let size = NSSize(width: 440, height: 210)
        let origin = NSPoint(
            x: screenFrame.maxX - size.width - 28,
            y: screenFrame.maxY - size.height - 28
        )

        panel = NSPanel(
            contentRect: NSRect(origin: origin, size: size),
            styleMask: [.borderless, .nonactivatingPanel],
            backing: .buffered,
            defer: false
        )

        panel.isReleasedWhenClosed = false
        panel.isOpaque = false
        panel.backgroundColor = .clear
        panel.hasShadow = true
        panel.level = .floating
        panel.isMovableByWindowBackground = true
        panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
        panel.sharingType = .none
        panel.title = "Mastermind POC Overlay"
        viewModel.backgroundOpacity = initialSettings.backgroundOpacity
        panel.contentView = NSHostingView(rootView: OverlayView(viewModel: viewModel, actions: actions))
    }

    var excludedWindowIDs: Set<CGWindowID> {
        [CGWindowID(panel.windowNumber)]
    }

    func show() {
        panel.orderFrontRegardless()
    }

    func hide() {
        panel.orderOut(nil)
    }

    @discardableResult
    func toggleClickThrough() -> Bool {
        clickThroughEnabled.toggle()
        panel.ignoresMouseEvents = clickThroughEnabled
        return clickThroughEnabled
    }
}
