import AppKit
import Foundation
enum Spirit { static let framesPerSecond = 20.0 }
struct SpiritStar: Equatable {
    var x: Double, y: Double        // 0 ..< 1
    var size: Double                // radius in points
    var phase: Double, rate: Double // twinkle
    var drift: Double               // points a second, to the left
}

enum SpiritStars {
    nonisolated static let count = 110
    /// The same stars every time: made from a fixed number, not from the clock, so two pictures of the same
    /// moment are the same picture.
    nonisolated static func make(seed: UInt64 = 0x484F_5053_5049_5249, count: Int = SpiritStars.count) -> [SpiritStar] {
        var s = seed
        func next() -> Double {       // SplitMix64, as a share of one
            s &+= 0x9E37_79B9_7F4A_7C15
            var z = s
            z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
            z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
            z ^= z >> 31
            return Double(z >> 11) / Double(1 << 53)
        }
        return (0..<count).map { _ in
            SpiritStar(x: next(), y: next(), size: 0.45 + 0.85 * next() * next(), phase: next() * 2 * .pi,
                       rate: 0.25 + 0.9 * next(), drift: 0.4 + 2.2 * next())
        }
    }
    nonisolated static let all = make()
}

/// Everything that moves is drawn here with plain Core Graphics calls, so `--selftest` can draw the same frames
/// off screen and time them.
enum SpiritPaint {
    private nonisolated static let white = CGColor(red: 1, green: 1, blue: 1, alpha: 1)
    private nonisolated static let accent = CGColor(red: 99 / 255, green: 179 / 255, blue: 237 / 255, alpha: 1)

    /// Small white stars at 30 to 60 percent, drifting slowly to the left and coming back in on the right.
    nonisolated static func stars(_ cg: CGContext, size: CGSize, t: Double, stars: [SpiritStar] = SpiritStars.all) {
        guard size.width > 0, size.height > 0 else { return }
        for s in stars {
            var x = (s.x * size.width - t * s.drift).truncatingRemainder(dividingBy: size.width)
            if x < 0 { x += size.width }
            let a = 0.30 + 0.30 * (0.5 + 0.5 * sin(t * s.rate + s.phase))
            cg.setFillColor(white.copy(alpha: a) ?? white)
            cg.fillEllipse(in: CGRect(x: x - s.size, y: s.y * size.height - s.size, width: s.size * 2, height: s.size * 2))
        }
    }

    /// How strong a ripple is at a share `u` of the way out: 22 percent at the point, 4 percent at the rim, and
    /// gone over the last tenth so a ripple does not vanish with a jump.
    nonisolated static func rippleStrength(_ u: Double) -> Double {
        let v = min(max(u, 0), 1)
        let base = 0.04 + 0.18 * (1 - v) * (1 - v)
        return v > 0.9 ? base * (1 - v) / 0.1 : base
    }

    /// Stylized gravitational waves from a binary system, not a physical simulation.
    /// The two-lobed deformation follows the retarded orbital phase as each ring expands.
    nonisolated static func ripples(_ cg: CGContext, center: CGPoint, reach: CGFloat, t: Double, rings: Int = 6) {
        guard reach > 0, rings > 0 else { return }
        cg.saveGState()
        defer { cg.restoreGState() }
        cg.setLineWidth(0.8)
        for k in 0..<rings {
            var u = (t / 18 + Double(k) / Double(rings)).truncatingRemainder(dividingBy: 1)
            if u < 0 { u += 1 }
            let radius = (0.10 + 0.90 * u) * reach
            let phase = (t - u * 18) * 2 * Double.pi / 18
            let strength = rippleStrength(u) * min(1, u * 12)
            cg.setStrokeColor(accent.copy(alpha: strength) ?? accent)
            let path = CGMutablePath()
            for sample in 0...96 {
                let angle = Double(sample) * 2 * Double.pi / 96
                let r = radius * (1 + 0.045 * cos(2 * (angle - phase)))
                let p = CGPoint(x: center.x + cos(angle) * r, y: center.y + sin(angle) * r * 0.76)
                if sample == 0 { path.move(to: p) } else { path.addLine(to: p) }
            }
            path.closeSubpath()
            cg.addPath(path)
            cg.strokePath()
        }
    }

    /// Two dark horizons orbit their common centre, with steady photon rings and accretion light.
    nonisolated static func core(_ cg: CGContext, center: CGPoint, radius: CGFloat, t: Double) {
        guard radius > 0 else { return }
        let phase = t * 2 * Double.pi / 18
        let orbit = radius * 5.8
        // Draw the farther horizon first; apparent size subtly follows depth, never a brightness pulse.
        let phases = [phase, phase + Double.pi].sorted { sin($0) < sin($1) }
        for angle in phases {
            let r = radius * (1.45 + 0.12 * sin(angle))
            let c = CGPoint(x: center.x + cos(angle) * orbit, y: center.y + sin(angle) * orbit * 0.60)
            let warm = CGColor(red: 1, green: 0.73, blue: 0.42, alpha: 0.85)
            cg.saveGState()
            cg.setShadow(offset: .zero, blur: r * 1.1, color: warm.copy(alpha: 0.45))
            cg.setStrokeColor(warm)
            cg.setLineWidth(max(0.65, r * 0.14))
            cg.strokeEllipse(in: CGRect(x: c.x - r * 2.4, y: c.y - r * 0.62, width: r * 4.8, height: r * 1.24))
            cg.setShadow(offset: .zero, blur: 0, color: nil)
            cg.setFillColor(CGColor(red: 0.005, green: 0.005, blue: 0.009, alpha: 1))
            cg.fillEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2))
            cg.setStrokeColor(CGColor(red: 1, green: 0.88, blue: 0.67, alpha: 0.95))
            cg.setLineWidth(max(0.55, r * 0.10))
            cg.strokeEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2))
            cg.restoreGState()
        }
    }

    /// One whole frame of the home screen: the sky, gravitational waves and orbiting horizons.
    nonisolated static func frame(_ cg: CGContext, size: CGSize, t: Double) {
        stars(cg, size: size, t: t)
        let c = CGPoint(x: size.width / 2, y: size.height * 0.4)
        ripples(cg, center: c, reach: max(size.width, size.height) * 0.6, t: t)
        core(cg, center: c, radius: 5, t: t)
    }

    /// Draws `frames` whole frames into an off-screen picture of a window at twice the points (a Retina screen)
    /// and returns the average milliseconds of processor time a frame. Processor time of this thread, not time on
    /// the clock: a busy Mac makes the clock run long without the drawing costing more. Used by `--selftest`.
    nonisolated static func averageFrameMilliseconds(size: CGSize = CGSize(width: 820, height: 520), frames: Int = 60) -> Double? {
        let w = Int(size.width * 2), h = Int(size.height * 2)
        guard frames > 0, let cg = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0,
                                             space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
        cg.scaleBy(x: 2, y: 2)
        for k in 0..<3 { frame(cg, size: size, t: Double(k)) }       // first use of the drawing code is not counted
        let start = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID)
        for k in 0..<frames {
            cg.clear(CGRect(origin: .zero, size: size))
            frame(cg, size: size, t: 10 + Double(k) / Spirit.framesPerSecond)
        }
        return Double(clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - start) / 1_000_000 / Double(frames)
    }
}

struct SpiritClock {
    let showing: Bool
    let reduceMotion: Bool
    var still: Bool { !showing || reduceMotion || SpiritClock.testing }
    static let testing = CommandLine.arguments.contains("--uitest") || CommandLine.arguments.contains("--selftest")
    /// The moment drawn when nothing moves.
    static let restMoment = 12.0
    func moment(_ date: Date) -> Double { still ? Self.restMoment : date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 86_400) }
}

for (index, time) in [0.0, 4.5].enumerated() {
 let size = CGSize(width: 820, height: 520)
 let cg = CGContext(data: nil, width: 1640, height: 1040, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
 cg.scaleBy(x: 2, y: 2)
 cg.setFillColor(CGColor(red: 0.039, green: 0.039, blue: 0.059, alpha: 1))
 cg.fill(CGRect(origin: .zero, size: size))
 SpiritPaint.frame(cg, size: size, t: time)
 let image = NSBitmapImageRep(cgImage: cg.makeImage()!)
 try image.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: "build/black-holes-\(index).png"))
}

let paused = SpiritClock(showing: true, reduceMotion: true)
precondition(paused.still && paused.moment(Date(timeIntervalSince1970: 0)) == paused.moment(Date(timeIntervalSince1970: 30)))
precondition(SpiritClock(showing: false, reduceMotion: false).still)
print("PASS: Reduce Motion and hidden window freeze the clock")
if let ms = SpiritPaint.averageFrameMilliseconds() { print("Frame CPU milliseconds: \(ms)"); precondition(ms < 16) }
