import QuartzCore
import Foundation

private struct KeysKey {
    let left: CGPath
    let front: CGPath
    let top: CGPath
    let outline: CGPath
    let dash: CGPath
    let topOpacity: Float
    let dashOpacity: Float
}

private struct KeysFrame {
    let keys: [KeysKey]
    let fx: CGPath
}

private enum KeysModel {
    static let fps = 60.0
    static let duration = 2.2
    static let count = Int((duration * fps).rounded())
    static let yaw = 30.0 * Double.pi / 180
    static let pitch = 55.0 * Double.pi / 180
    static let kx = [0.0, 31.0, 62.0]
    static let kw = 24.0
    static let kz0 = -34.0
    static let kz1 = -10.0
    static let depth = 15.0
    static let sx0 = 0.0
    static let sx1 = 86.0
    static let sz0 = 0.0
    static let sz1 = 16.0
    static let press: [(Int, Double)] = [(0, 0.3), (2, 0.62), (0, 0.94)]
    static let space = 1.36
    static let pk: [(Double, Double)] = [(0, 0), (0.05, 0.9), (0.08, 0.82), (0.2, 0.82), (0.28, -0.3), (0.37, 0.08), (0.46, -0.03), (0.54, 0)]
    static let wk: [(Double, Double)] = [(0, 0), (0.05, 0), (0.08, 0.07), (0.14, -0.02), (0.2, 0), (0.28, -0.05), (0.37, 0.02), (0.46, 0)]
    static let fl: [(Double, Double)] = [(0, 0), (0.04, 1), (0.2, 1), (0.28, 0)]
    static let hopKeys: [(Double, Double)] = [(0, 0), (0.22, 0), (0.28, -0.45), (0.38, 0.12), (0.48, -0.04), (0.56, 0)]

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let v = clamp(u); return v * v * (3 - 2 * v) }
    static func eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 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 proj0(_ x: Double, _ y: Double, _ z: Double) -> (Double, Double) {
        let x1 = x * cos(yaw) + z * sin(yaw)
        let z1 = -x * sin(yaw) + z * cos(yaw)
        let y2 = y * cos(pitch) - z1 * sin(pitch)
        return (x1, -y2)
    }

    static let frame: (scale: Double, ox: Double, oy: Double) = {
        var pts: [(Double, Double)] = []
        for x in [sx0, sx1] {
            for z in [kz0, sz1] {
                for y in [0, depth] { pts.append(proj0(x, y, z)) }
            }
        }
        let bx0 = pts.map { $0.0 }.min()!
        let bx1 = pts.map { $0.0 }.max()!
        let by0 = pts.map { $0.1 }.min()!
        let by1 = pts.map { $0.1 }.max()!
        let sc = 94 / max(bx1 - bx0, by1 - by0)
        return (sc, 60 - sc * (bx0 + bx1) / 2, 62 - sc * (by0 + by1) / 2)
    }()

    static func proj(_ x: Double, _ y: Double, _ z: Double) -> CGPoint {
        let p = proj0(x, y, z)
        return CGPoint(x: frame.ox + frame.scale * p.0, y: frame.oy + frame.scale * p.1)
    }

    static func rpoly(_ pts: [CGPoint], _ r: Double) -> CGPath {
        let path = CGMutablePath()
        let n = pts.count
        for i in 0..<n {
            let p0 = pts[(i + n - 1) % n]
            let p1 = pts[i]
            let p2 = pts[(i + 1) % n]
            func toward(_ a: CGPoint, _ b: CGPoint) -> CGPoint {
                let dx = b.x - a.x
                let dy = b.y - a.y
                let l = hypot(dx, dy)
                let m = min(r, l / 2.2)
                return CGPoint(x: a.x + dx * m / l, y: a.y + dy * m / l)
            }
            let q0 = toward(p1, p0)
            let q1 = toward(p1, p2)
            if i == 0 { path.move(to: q0) } else { path.addLine(to: q0) }
            path.addQuadCurve(to: q1, control: p1)
        }
        path.closeSubpath()
        return path
    }

    static func blob(_ x: Double, _ y: Double, _ r: Double, _ path: CGMutablePath) {
        if r > 0.05 { path.addEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r)) }
    }

    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)
    }

    struct Parts {
        let left: CGPath
        let front: CGPath
        let top: CGPath
        let dash: CGPath
        let silhouette: CGPath
    }

    static func key(_ x0: Double, _ x1: Double, _ z0: Double, _ z1: Double, _ p: Double, _ wob: Double, _ dashed: Bool) -> Parts {
        let h = depth * (1 - p)
        let cx = (x0 + x1) / 2
        let cz = (z0 + z1) / 2
        let hw = (x1 - x0) / 2 * (1 + wob)
        let hd = (z1 - z0) / 2 * (1 + wob * 0.5)
        let a0 = cx - hw
        let a1 = cx + hw
        let b0 = cz - hd
        let b1 = cz + hd
        let left = rpoly([proj(x0, 0, z0), proj(x0, 0, z1), proj(a0, h, b1), proj(a0, h, b0)], 4)
        let front = rpoly([proj(x0, 0, z1), proj(x1, 0, z1), proj(a1, h, b1), proj(a0, h, b1)], 4)
        let top = rpoly([proj(a0, h, b0), proj(a1, h, b0), proj(a1, h, b1), proj(a0, h, b1)], 4)
        let dash = CGMutablePath()
        if dashed {
            dash.move(to: proj(cx - 5, h, cz))
            dash.addLine(to: proj(cx + 5, h, cz))
        }
        let all = CGMutablePath()
        all.addPath(left)
        all.addPath(front)
        all.addPath(top)
        return Parts(left: left, front: front, top: top, dash: dash, silhouette: left.union(front).union(top))
    }

    nonisolated(unsafe) static let frames: [KeysFrame] = (0..<count).map { build(Double($0) * duration / Double(count)) }

    static func build(_ t: Double) -> KeysFrame {
        let hop = t >= space ? keys(t - space, hopKeys) : 0
        var specs: [(Double, Double, Double, Double, Double, Double, Bool)] = []
        for i in [2, 1, 0] {
            var p = 0.0
            var wob = 0.0
            var f = 0.0
            for (ki, tp) in press where ki == i && t >= tp - 0.01 {
                p += keys(t - tp, pk)
                wob += keys(t - tp, wk)
                f = max(f, keys(t - tp, fl))
            }
            if p == 0 { p = hop }
            specs.append((kx[i], kx[i] + kw, p, wob, f, 0, true))
        }
        let sp = t >= space ? keys(t - space, pk) : 0
        let sw = t >= space ? keys(t - space, wk) * 0.35 : 0
        let sf = t >= space ? keys(t - space, fl) : 0
        let parts: [Parts] = specs.map { key($0.0, $0.1, kz0, kz1, $0.2, $0.3, true) } + [key(sx0, sx1, sz0, sz1, sp, sw, false)]
        let fills = specs.map { $0.4 } + [sf]
        var out: [KeysKey] = []
        for (j, part) in parts.enumerated() {
            var cover: CGPath?
            for later in parts[(j + 1)...] { cover = cover.map { $0.union(later.silhouette) } ?? later.silhouette }
            func clipped(_ path: CGPath) -> CGPath { cover.map { path.subtracting($0) } ?? path }
            let all = CGMutablePath()
            all.addPath(part.left)
            all.addPath(part.front)
            all.addPath(part.top)
            let outline = all.copy(strokingWithWidth: 3.5, lineCap: .butt, lineJoin: .round, miterLimit: 10)
            let dashOutline = part.dash.copy(strokingWithWidth: 4, lineCap: .round, lineJoin: .round, miterLimit: 10)
            let hasDash = !part.dash.isEmpty
            let top = hasDash ? part.top.subtracting(dashOutline) : part.top
            out.append(KeysKey(
                left: clipped(part.left),
                front: clipped(part.front),
                top: clipped(top),
                outline: clipped(outline),
                dash: hasDash ? clipped(dashOutline) : CGMutablePath(),
                topOpacity: Float(0.3 + 0.7 * fills[j]),
                dashOpacity: Float(1 - fills[j])
            ))
        }
        let fx = CGMutablePath()
        for (ki, tp) in press {
            let x = kx[ki]
            for (side, ex, ez) in [(-1.0, x, kz1), (1.0, x + kw, kz1)] {
                let s = proj(ex, 0, ez)
                for (dx, dy, r, d0, dur) in [(4.0, -1.0, 3.2, 0.0, 0.3), (8.0, -6.0, 2.2, 0.04, 0.26)] {
                    let u = eout((t - tp - d0) / dur)
                    blob(s.x + side * dx * u, s.y - 2 + dy * u, life(t, tp + d0, dur, r), fx)
                }
            }
            let tip = proj(x + kw / 2, depth, (kz0 + kz1) / 2)
            for (j, (dx, h, r)) in [(-3.0, 17.0, 4.0), (4.0, 12.0, 2.8)].enumerated() {
                let t0 = tp + 0.22 + 0.04 * Double(j)
                let u = clamp((t - t0) / 0.42)
                blob(tip.x + dx * eout(u), tip.y - 8 - h * eout(u), life(t, t0, 0.42, r), fx)
            }
        }
        for (side, ex) in [(-1.0, sx0), (1.0, sx1)] {
            let s = proj(ex, 0, sz1)
            for (dx, dy, r, d0, dur) in [(5.0, -1.0, 4.2, 0.0, 0.38), (9.0, -7.0, 3.0, 0.04, 0.32), (2.0, -10.0, 2.2, 0.08, 0.3)] {
                let u = eout((t - space - d0) / dur)
                blob(s.x + side * (1 + dx * u), s.y - 2 + dy * u, life(t, space + d0, dur, r), fx)
            }
        }
        return KeysFrame(keys: out, fx: fx)
    }
}

extension FlairLayer {
    func buildKeys() {
        let unit = side
        let k = unit / 110
        let frames = KeysModel.frames
        let duration = KeysModel.duration
        let steps = KeysModel.count
        let flip = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        func screen(_ path: CGPath) -> CGPath {
            var m = flip
            return path.copy(using: &m) ?? 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 discrete(_ name: String, _ values: [Any]) -> CAKeyframeAnimation {
            let animation = keyframes(name, values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func drift(_ layer: CAShapeLayer, _ pick: @escaping (KeysFrame) -> CGPath) {
            run(group([discrete("path", frames.map { screen(pick($0)) })], duration: duration), on: layer)
        }
        func both(_ layer: CAShapeLayer, _ pick: @escaping (KeysFrame) -> CGPath, _ fade: @escaping (KeysFrame) -> Float) {
            run(group([discrete("path", frames.map { screen(pick($0)) }), discrete("opacity", frames.map { NSNumber(value: fade($0)) })], duration: duration), on: layer)
        }
        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

        var tops: [CAShapeLayer] = []
        var dashes: [CAShapeLayer] = []
        for j in 0..<frames[0].keys.count {
            let first = frames[0].keys[j]
            let left = shape(screen(first.left), size: full, at: mid, in: clipper)
            left.opacity = 0.5
            let front = shape(screen(first.front), size: full, at: mid, in: clipper)
            front.opacity = 0.22
            let top = shape(screen(first.top), size: full, at: mid, in: clipper)
            tops.append(top)
            shape(screen(first.outline), size: full, at: mid, in: clipper)
            let dash = shape(screen(first.dash), size: full, at: mid, in: clipper)
            dashes.append(dash)
            if animating {
                drift(left) { $0.keys[j].left }
                drift(front) { $0.keys[j].front }
                both(top, { $0.keys[j].top }, { $0.keys[j].topOpacity })
                both(dash, { $0.keys[j].dash }, { $0.keys[j].dashOpacity })
            }
        }
        var outlines: [CAShapeLayer] = []
        for layer in (clipper.sublayers ?? []).compactMap({ $0 as? CAShapeLayer }) where layer.opacity == 1 && !tops.contains(layer) && !dashes.contains(layer) { outlines.append(layer) }
        let fx = shape(screen(frames[0].fx), size: full, at: mid, in: clipper)

        guard animating else { return }
        drift(fx) { $0.fx }
        for (j, layer) in outlines.enumerated() where j < frames[0].keys.count { drift(layer) { $0.keys[j].outline } }
    }
}
