// claude-red: turns every screen red, with the project's name on it, until you
// next touch the keyboard or mouse. Hook input arrives as JSON on stdin.
import AppKit

let hook = (try? JSONSerialization.jsonObject(with: FileHandle.standardInput.readDataToEndOfFile())) as? [String: Any]
let project = URL(fileURLWithPath: hook?["cwd"] as? String ?? "Claude").lastPathComponent

let app = NSApplication.shared
app.setActivationPolicy(.accessory)           // no Dock icon, never takes focus

var windows: [NSWindow] = []
for screen in NSScreen.screens {
    let w = NSWindow(contentRect: screen.frame, styleMask: .borderless, backing: .buffered, defer: false)
    w.level = .screenSaver
    w.ignoresMouseEvents = true                // clicks go straight through
    w.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
    w.backgroundColor = NSColor.systemRed.withAlphaComponent(0.5)
    w.isOpaque = false
    let label = NSTextField(labelWithString: project)
    label.font = .systemFont(ofSize: 96, weight: .bold)
    label.textColor = .white
    label.sizeToFit()
    label.setFrameOrigin(NSPoint(x: (screen.frame.width - label.frame.width) / 2,
                                 y: (screen.frame.height - label.frame.height) / 2))
    w.contentView?.addSubview(label)
    w.orderFrontRegardless()
    windows.append(w)
}

// Stay until the first key press, click or mouse move at least 1.5s after it appeared
// (or after the display woke, so the key that wakes it doesn't clear it unseen). 8 hours at most.
var start = Date()
let began = Date()
let anyInput = CGEventType(rawValue: ~0)!
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { _ in
    if CGDisplayIsAsleep(CGMainDisplayID()) != 0 { start = Date() }
    let shown = Date().timeIntervalSince(start)
    let idle = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: anyInput)
    if (shown > 1.5 && idle < shown - 1.5) || Date().timeIntervalSince(began) > 28800 { exit(0) }
}
app.run()
