import AppKit

/// The copy-paste fallback for Claude sign-in: shown only when Nucleic can't bind a loopback port
/// to catch the OAuth redirect automatically. The consent page renders an authorization code
/// (`code#state`); this asks the user to paste it back. Normal sign-ins never reach this — the
/// loopback path completes without any pasting.
enum ClaudeLoginPrompt {
    /// Present a modal asking for the pasted authorization code. Returns the trimmed code, or nil if
    /// the user cancelled. Always runs on the main actor (AppKit requirement).
    @MainActor
    static func requestCode(consentURL: URL) async -> String? {
        let alert = NSAlert()
        alert.messageText = "Finish signing in to Claude"
        alert.informativeText =
            "Your browser opened Anthropic's sign-in page. After you approve, it shows an "
            + "authorization code — paste it here to finish."
        alert.addButton(withTitle: "Sign In")
        alert.addButton(withTitle: "Cancel")

        let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 320, height: 24))
        field.placeholderString = "Paste the authorization code"
        alert.accessoryView = field
        alert.window.initialFirstResponder = field

        // Prefer a sheet on an existing window: it suspends only this task, not the main
        // thread. `runModal` remains only for the no-window case (all windows closed) —
        // it parks the main thread in a nested modal run loop until answered.
        let response: NSApplication.ModalResponse
        if let window = NSApp.keyWindow ?? NSApp.mainWindow {
            response = await alert.beginSheetModal(for: window)
        } else {
            response = alert.runModal()
        }
        guard response == .alertFirstButtonReturn else { return nil }
        let code = field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
        return code.isEmpty ? nil : code
    }
}
