import QuartzCore
import Foundation

private struct BricksFrame {
    let studs: CGPath
    let bodies: CGPath
    let dust: CGPath
    let lineWidth: Double
}

private enum BricksModel {
    static let pitch = 28.0
    static let height = 22.0
    static let fall = 0.24
    static let bricks: [(x: Double, w: Double, top: Double, n: Int)] = [
        (0, 56, -22, 2), (56, 56, -22, 2), (112, 56, -22, 2), (28, 56, -44, 2), (84, 56, -44, 2), (56, 56, -66, 2)
    ]
    static let landings: [Double] = {
        var out: [Double] = []
        var t = 0.3
        for i in 0..<6 {
            out.append(t)
            t += i < 4 ? 0.42 : 0.56
        }
        return out
    }()
    static let bounceAt = landings[5]
    static let outAt = bounceAt + 1.3
    static let duration = outAt + 5 * 0.06 + 0.5
    static let count = Int((duration / (1.0 / 30.0)).rounded())
    static let squashKeys: [(Double, Double)] = [(0, 0), (0.05, -0.15), (0.18, 0.07), (0.3, -0.03), (0.42, 0.012), (0.54, 0)]
    static let rockKeys: [(Double, Double)] = [(0, 0), (0.1, 2.0), (0.22, -0.8), (0.34, 0)]
    static let houseKeys: [(Double, Double)] = [(0, 0), (0.06, -0.12), (0.2, 0.07), (0.34, -0.03), (0.48, 0.01), (0.6, 0)]
    static let camera: [(Double, Double, Double)] = simulate()
    nonisolated(unsafe) static let frames: [BricksFrame] = (0..<count).map { build(Double($0) * duration / Double(count), $0) }

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let c = clamp(u); return c * c * (3 - 2 * c) }
    static func easeOut(_ u: Double) -> Double { let c = clamp(u); return 1 - pow(1 - c, 3) }

    static func keys(_ t: Double, _ ks: [(Double, Double)]) -> Double {
        if t <= ks[0].0 { return ks[0].1 }
        for (a, b) in zip(ks, ks.dropFirst()) where t <= b.0 {
            return a.1 + (b.1 - a.1) * ease((t - a.0) / (b.0 - a.0))
        }
        return ks[ks.count - 1].1
    }

    static func compose(_ steps: [CGAffineTransform]) -> CGAffineTransform {
        var result = CGAffineTransform.identity
        for item in steps.reversed() { result = result.concatenating(item) }
        return result
    }

    static func turn(_ degrees: Double, _ cx: Double, _ cy: Double) -> [CGAffineTransform] {
        [CGAffineTransform(translationX: cx, y: cy), CGAffineTransform(rotationAngle: degrees * .pi / 180), CGAffineTransform(translationX: -cx, y: -cy)]
    }

    static func outAt(_ i: Int) -> Double { outAt + Double(5 - i) * 0.06 }
    static func present(_ i: Int, _ t: Double) -> Bool { landings[i] - fall <= t && t < outAt(i) + 0.22 }

    static func view(_ count: Int) -> (Double, Double, Double) {
        let n = max(count, 1)
        let xs = (0..<n).map { bricks[$0].x } + (0..<n).map { bricks[$0].x + bricks[$0].w }
        let ys = (0..<n).map { bricks[$0].top - 8 } + [0.0]
        let w = xs.max()! - xs.min()!, h = ys.max()! - ys.min()!
        let s = max(w + 24, h + 24, 135)
        return ((xs.max()! + xs.min()!) / 2, (ys.max()! + ys.min()!) / 2, 96 / s)
    }

    static func target(_ t: Double) -> (Double, Double, Double) {
        if t >= outAt(0) + 0.24 { return view(1) }
        var n = 0
        for i in 0..<bricks.count where t >= landings[i] - fall - 0.1 { n = i + 1 }
        return view(n)
    }

    static func simulate() -> [(Double, Double, Double)] {
        let dt = duration / Double(count)
        var (cx, cy, z) = view(1)
        var vx = 0.0, vy = 0.0, vz = 0.0
        var out: [(Double, Double, Double)] = []
        for loop in 0..<2 {
            for k in 0..<count {
                let (tx, ty, tz) = target(Double(k) * dt)
                let w = 7.0
                for _ in 0..<4 {
                    let h = dt / 4
                    vx += (w * w * (tx - cx) - 2 * w * vx) * h; cx += vx * h
                    vy += (w * w * (ty - cy) - 2 * w * vy) * h; cy += vy * h
                    vz += (w * w * (tz - z) - 2 * w * vz) * h; z += vz * h
                }
                if loop == 1 { out.append((cx, cy, z)) }
            }
        }
        return out
    }

    static func life(_ t: Double, _ t0: Double, _ dur: Double, _ rmax: Double) -> Double {
        let u = (t - t0) / dur
        if u <= 0 || u >= 1 { return 0 }
        return rmax * pow(sin(.pi * pow(u, 0.6)), 1.2)
    }

    static func build(_ t: Double, _ k: Int) -> BricksFrame {
        let (cx, cy, z) = camera[k]
        let sw = 4.0 * sqrt(z)
        let pz = 1 / sqrt(z)
        let scene = compose([CGAffineTransform(translationX: 60, y: 60), CGAffineTransform(scaleX: z, y: z), CGAffineTransform(translationX: -cx, y: -cy)])
        let hq = t >= bounceAt ? keys(t - bounceAt, houseKeys) : 0
        let hsy = 1 + hq
        let hsx = hq < 0 ? 1 - hq : 1 / sqrt(hsy)
        let houseTr = compose([CGAffineTransform(translationX: 84, y: 0), CGAffineTransform(scaleX: hsx, y: hsy), CGAffineTransform(translationX: -84, y: 0)])
        let studs = CGMutablePath()
        let bodies = CGMutablePath()
        let dust = CGMutablePath()
        let last = bricks.count - 1
        for (i, b) in bricks.enumerated() {
            guard present(i, t) else { continue }
            let mx = b.x + b.w / 2, by = b.top + height
            var steps: [CGAffineTransform]
            if t < landings[i] {
                let u = (t - landings[i] + fall) / fall
                let dy = -(1 - u * u) * 75 / z
                let st = (i == last ? 0.2 : 0.14) * u * u
                let tilt = (i == last ? 0 : (i % 2 == 1 ? 6.0 : -6.0)) * (1 - ease(u))
                steps = [CGAffineTransform(translationX: 0, y: dy)] + turn(tilt, mx, by - 11) + [CGAffineTransform(translationX: mx, y: by), CGAffineTransform(scaleX: 1 / sqrt(1 + st), y: 1 + st), CGAffineTransform(translationX: -mx, y: -by)]
            } else {
                let q = keys(t - landings[i], squashKeys) * (i == last ? 0.7 : 1)
                let sy = 1 + q
                let sx = q < 0 ? 1 - q : 1 / sqrt(sy)
                let rk = keys(t - landings[i], rockKeys) * (i % 2 == 1 ? 1 : -1)
                var so = 1.0
                if t >= outAt(i) {
                    let u = (t - outAt(i)) / 0.22
                    so = u < 0.3 ? 1 + 0.12 * sin(.pi * u / 0.3) : 1 - ease((u - 0.3) / 0.7)
                }
                steps = turn(rk, mx, by) + [CGAffineTransform(translationX: mx, y: by - height / 2 * (1 - so)), CGAffineTransform(scaleX: sx * so, y: sy * so), CGAffineTransform(translationX: -mx, y: -by)]
                var points: [(Double, Double, Double)] = [(mx - b.w / 2, by, 1), (mx + b.w / 2, by, 1)]
                if i == last { points = [(mx - b.w / 2, by, 1.15), (mx + b.w / 2, by, 1.15), (0, 0, 1.5), (168, 0, 1.5)] }
                for (index, p) in points.enumerated() {
                    let side = index % 2 == 0 ? -1.0 : 1.0
                    for (dx, dy, r, d0, dur) in [(9.0, -1.0, 5.0, 0.0, 0.4), (4, -9, 3.6, 0.03, 0.34), (13, -8, 2.7, 0.06, 0.3)] {
                        let uu = easeOut((t - landings[i] - d0) / dur)
                        let px = p.0 + side * dx * uu * pz * p.2
                        let py = p.1 - 3 + dy * uu * pz * p.2
                        let radius = life(t, landings[i] + d0, dur, r * pz * p.2)
                        if radius > 0.05 {
                            let d = CGPath(ellipseIn: CGRect(x: px - radius, y: py - radius, width: radius * 2, height: radius * 2), transform: nil)
                            dust.addPath(d, transform: scene)
                        }
                    }
                }
            }
            let tr = compose(steps).concatenating(houseTr).concatenating(scene)
            for n in 0..<b.n {
                let c = b.x + pitch * (Double(n) + 0.5)
                studs.addPath(CGPath(roundedRect: CGRect(x: c - 7, y: b.top - 8, width: 14, height: 10), cornerWidth: 3, cornerHeight: 3, transform: nil), transform: tr)
            }
            bodies.addPath(CGPath(roundedRect: CGRect(x: b.x + 1.5, y: b.top, width: b.w - 3, height: height), cornerWidth: 4.5, cornerHeight: 4.5, transform: nil), transform: tr)
        }
        return BricksFrame(studs: studs, bodies: bodies, dust: dust, lineWidth: sw)
    }
}

extension FlairLayer {
    func buildBricks() {
        let unit = side
        let k = unit / 110
        let frames = BricksModel.frames
        let duration = BricksModel.duration
        let steps = BricksModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        func paths(_ pick: (BricksFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { placed(pick(frames[$0])) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func widths() -> CAKeyframeAnimation {
            let values = (0..<steps).map { NSNumber(value: frames[$0].lineWidth * Double(k)) }
            let animation = keyframes("lineWidth", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        let clipper = container()
        let tile = CAShapeLayer()
        tile.bounds = CGRect(origin: .zero, size: full)
        tile.position = mid
        tile.path = CGPath(roundedRect: CGRect(origin: .zero, size: full), cornerWidth: 22 * k, cornerHeight: 22 * k, transform: nil)
        tile.fillColor = CGColor(gray: 0, alpha: 1)
        clipper.mask = tile

        let dust = shape(placed(frames[0].dust), size: full, at: mid, in: clipper)
        let studs = shape(placed(frames[0].studs), size: full, at: mid, in: clipper)
        let fill = shape(placed(frames[0].bodies), size: full, at: mid, in: clipper)
        fill.opacity = 0.22
        let edge = shape(placed(frames[0].bodies), size: full, at: mid, stroke: CGFloat(frames[0].lineWidth) * k, in: clipper)
        edge.lineJoin = .round

        guard animating else { return }
        run(group([paths { $0.dust }], duration: duration), on: dust)
        run(group([paths { $0.studs }], duration: duration), on: studs)
        run(group([paths { $0.bodies }], duration: duration), on: fill)
        run(group([paths { $0.bodies }, widths()], duration: duration), on: edge)
    }
}
