import AppKit

final class PasswordPromptSheet: NSViewController {

    var onComplete: ((String?) -> Void)?

    private let prompt: String
    private let passwordField = NSSecureTextField()

    init(prompt: String) {
        self.prompt = prompt
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { fatalError() }

    override func loadView() {
        view = NSView(frame: NSRect(x: 0, y: 0, width: 320, height: 110))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        buildUI()
    }

    private func buildUI() {
        let promptLabel = NSTextField(labelWithString: prompt)
        promptLabel.lineBreakMode = .byWordWrapping
        promptLabel.setAccessibilityLabel(prompt)

        passwordField.placeholderString = "password"
        passwordField.setAccessibilityLabel("Password")
        passwordField.target = self; passwordField.action = #selector(okClicked)

        let cancelButton = NSButton(title: "Cancel", target: self, action: #selector(cancelClicked))
        cancelButton.bezelStyle = .rounded
        cancelButton.setAccessibilityLabel("Cancel")

        let okButton = NSButton(title: "OK", target: self, action: #selector(okClicked))
        okButton.bezelStyle = .rounded
        okButton.keyEquivalent = "\r"
        okButton.setAccessibilityLabel("Submit password")

        let buttonRow = NSStackView(views: [NSView(), cancelButton, okButton])
        buttonRow.orientation = .horizontal; buttonRow.spacing = 8

        let stack = NSStackView(views: [promptLabel, passwordField, buttonRow])
        stack.orientation = .vertical
        stack.spacing = 10
        stack.edgeInsets = NSEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        stack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.topAnchor.constraint(equalTo: view.topAnchor),
            stack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            stack.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        passwordField.becomeFirstResponder()
    }

    @objc private func okClicked() {
        let pw = passwordField.stringValue
        dismiss(nil)
        onComplete?(pw)
    }

    @objc private func cancelClicked() {
        dismiss(nil)
        onComplete?(nil)
    }
}
