import QuartzCore
import Foundation

private struct DribbleFrame {
    let shadow: CGPath
    let shadowOpacity: Float
    let dust: CGPath
    let streaks: CGPath
    let streakOpacity: Float
    let ballFill: CGPath
    let ballRing: CGPath
    let seams: CGPath
    let gloveFill: CGPath
    let gloveInk: CGPath
    let gloveHide: CGPath
}

private enum DribbleModel {
    static let duration = 1.12
    static let count = 68
    static let step = 0.28
    static let drop = 0.1
    static let squash = 0.06
    static let launch = 0.12
    static let floorY = 101.0
    static let radius = 14.0
    static let glove = 0.062
    static let tops: [(Double, Double)] = [(37, 60), (83, 60), (83, 60), (37, 60)]
    static let flex = [60.0, 88.0, 60.0, 32.0]
    static let owner = [0, 1, 1, 0]
    static let home: [(Double, Double)] = [(34, 53), (86, 53)]

    nonisolated(unsafe) static let silhouette = parse(silhouetteText, 0.1)
    nonisolated(unsafe) static let ink = parse(inkText, 0.05)
    nonisolated(unsafe) static let frames: [DribbleFrame] = (0..<count).map { build(Double($0) * duration / Double(count)) }

    static func parse(_ text: String, _ k: Double) -> CGPath {
        let regex = try! NSRegularExpression(pattern: "[MmCcLlZz]|-?\\d+\\.?\\d*")
        let source = text as NSString
        let tokens = regex.matches(in: text, range: NSRange(location: 0, length: source.length)).map { source.substring(with: $0.range) }
        let path = CGMutablePath()
        func point(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x * k, y: 800 - y * k) }
        func number(_ index: Int) -> Double { Double(tokens[index]) ?? 0 }
        var command: Character = " "
        var cx = 0.0, cy = 0.0, sx = 0.0, sy = 0.0
        var index = 0
        while index < tokens.count {
            let token = tokens[index]
            if let first = token.first, first.isLetter {
                command = first
                index += 1
                if command == "Z" || command == "z" {
                    path.closeSubpath()
                    cx = sx
                    cy = sy
                }
                continue
            }
            switch command {
            case "M", "m":
                var x = number(index), y = number(index + 1)
                index += 2
                if command == "m" { x += cx; y += cy }
                cx = x; cy = y; sx = x; sy = y
                path.move(to: point(x, y))
                command = command == "m" ? "l" : "L"
            case "C", "c":
                var v = (0..<6).map { number(index + $0) }
                index += 6
                if command == "c" { v = v.enumerated().map { $0.element + ($0.offset % 2 == 0 ? cx : cy) } }
                path.addCurve(to: point(v[4], v[5]), control1: point(v[0], v[1]), control2: point(v[2], v[3]))
                cx = v[4]; cy = v[5]
            case "L", "l":
                var x = number(index), y = number(index + 1)
                index += 2
                if command == "l" { x += cx; y += cy }
                path.addLine(to: point(x, y))
                cx = x; cy = y
            default:
                index += 1
            }
        }
        return path
    }

    static func wrap(_ x: Double, _ period: Double) -> Double {
        let r = x.truncatingRemainder(dividingBy: period)
        return r < 0 ? r + period : r
    }

    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 compose(_ steps: [CGAffineTransform]) -> CGAffineTransform {
        var result = CGAffineTransform.identity
        for item in steps.reversed() { result = result.concatenating(item) }
        return result
    }

    static func turn(_ degrees: Double) -> CGAffineTransform { CGAffineTransform(rotationAngle: degrees * .pi / 180) }

    static func traj(_ time: Double) -> (x: Double, y: Double, sy: Double, cu: Double) {
        let total = step * 4
        let t = wrap(time, total)
        let i = min(3, Int(floor(t / step)))
        let s = t - Double(i) * step
        let a = tops[i], b = tops[(i + 1) % 4]
        let fx = flex[i]
        let ground = floorY - radius
        if s < drop {
            let u = s / drop
            return (a.0 + (fx - a.0) * u, a.1 + (ground - a.1) * u * u, 1, -1)
        }
        if s < drop + squash {
            let u = (s - drop) / squash
            let sq = 0.42 * pow(max(sin(.pi * u), 0), 0.5)
            return (fx, floorY - radius * (1 - sq), 1 - sq, u)
        }
        let u = (s - drop - squash) / launch
        let w = 1 - (1 - u) * (1 - u)
        return (fx + (b.0 - fx) * u, ground + (b.1 - ground) * w, 1, -1)
    }

    static func contact(_ t: Double, _ hand: Int) -> Double {
        var best = 0.0
        for i in -1..<6 where owner[((i % 4) + 4) % 4] == hand {
            let d = t - Double(i) * step
            let k = d < 0 ? clamp(1 + d / 0.1) : clamp(1 - d / 0.09)
            best = max(best, ease(k))
        }
        return best
    }

    static func handFx(_ t: Double, _ hand: Int) -> (dy: Double, rot: Double, sx: Double, sy: Double) {
        var dy = 0.0, rot = 0.0, sx = 1.0, sy = 1.0
        for i in -2..<7 where owner[((i % 4) + 4) % 4] == hand {
            let d = t - Double(i) * step
            if d > -0.26 && d < -0.04 {
                let a = pow(max(sin(.pi * (d + 0.26) / 0.22), 0), 1.5)
                dy -= 6.5 * a
                rot += 14 * a
                sy += 0.12 * a
                sx -= 0.07 * a
            }
            if d > 0.06 && d < 0.5 {
                let e = d - 0.06
                let r = exp(-e / 0.11) * sin(2 * .pi * e / 0.2)
                dy -= 6 * r
                rot -= 10 * r
                sx += 0.1 * r
                sy -= 0.1 * r
            }
        }
        let ph = (t / (step * 4)) * 4 * .pi + (hand == 0 ? 0 : .pi)
        let b = sin(ph)
        dy += 1.8 * b
        rot += 4 * sin(ph + 0.8)
        sx += 0.04 * b
        sy -= 0.04 * b
        return (dy, rot, sx, sy)
    }

    static func build(_ t: Double) -> DribbleFrame {
        let total = step * 4
        let now = traj(t)
        let e = 1.0 / 240
        let before = traj(t - e), after = traj(t + e)
        let vx = (after.x - before.x) / (2 * e), vy = (after.y - before.y) / (2 * e)
        let sp = hypot(vx, vy)
        let x = now.x, y = now.y, sy = now.sy, cu = now.cu
        let height = floorY - radius - y
        let shs = clamp(1 - height / 70)

        let shadow = CGPath(ellipseIn: CGRect(x: x - radius * (0.7 + 0.5 * shs) * (1 + (1 - sy)), y: floorY + 1.5 - (2.6 + 0.8 * shs), width: radius * (0.7 + 0.5 * shs) * (1 + (1 - sy)) * 2, height: (2.6 + 0.8 * shs) * 2), transform: nil)
        let shadowOpacity = Float(0.12 + 0.22 * shs)

        let dust = CGMutablePath()
        for j in 0..<4 {
            let dt = wrap(t - (Double(j) * step + drop), total)
            guard dt < 0.2 else { continue }
            let p = dt / 0.2
            for side in [-1.0, 1.0] {
                let ox = flex[j] + side * (radius + 3 + 14 * (1 - (1 - p) * (1 - p)))
                let oy = floorY - 3 - 9 * sin(.pi * min(1, p * 1.2)) * 0.6
                let r = 3.2 * pow(1 - p, 0.8)
                if r > 0.3 { dust.addEllipse(in: CGRect(x: ox - r, y: oy - r, width: r * 2, height: r * 2)) }
            }
        }

        let streaks = CGMutablePath()
        var streakOpacity: Float = 0
        if sp > 300 && cu < 0 {
            let a = clamp((sp - 300) / 500)
            streakOpacity = Float(0.45 + 0.45 * a)
            let ux = vx / sp, uy = vy / sp
            let px = -uy, py = ux
            for (j, off) in [-7.0, 0.0, 7.0].enumerated() {
                let ln = (4 + 9 * a) * (1 - 0.3 * abs(off) / 7)
                let bx = x - ux * (radius + 4 + 2 * Double(j % 2)) + px * off
                let by = y - uy * (radius + 4 + 2 * Double(j % 2)) + py * off
                var ex = bx - ux * ln, ey = by - uy * ln
                let lim = floorY - 4
                if by > lim { continue }
                if ey > lim {
                    let f = (lim - by) / (ey - by)
                    ex = bx + (ex - bx) * f
                    ey = lim
                }
                if hypot(ex - bx, ey - by) < 2 { continue }
                streaks.move(to: CGPoint(x: bx, y: by))
                streaks.addLine(to: CGPoint(x: ex, y: ey))
            }
        }

        let st = cu >= 0 ? 0 : min(0.22, sp / 3400)
        let ang = sp > 1 ? atan2(vy, vx) * 180 / .pi : 0
        let seamTurn = (x - 60) * 4.5
        let ballTr: CGAffineTransform
        if cu >= 0 {
            let sx = 1 + (1 - sy) * 0.9
            ballTr = compose([CGAffineTransform(translationX: x, y: floorY), CGAffineTransform(scaleX: sx, y: sy), CGAffineTransform(translationX: 0, y: -radius)])
        } else {
            ballTr = compose([CGAffineTransform(translationX: x, y: y), turn(ang), CGAffineTransform(scaleX: 1 + st, y: 1 / (1 + st)), turn(-ang)])
        }
        let circle = CGPath(ellipseIn: CGRect(x: -radius, y: -radius, width: radius * 2, height: radius * 2), transform: nil)
        var ballMap = ballTr
        let ballFill = circle.copy(using: &ballMap) ?? circle
        let seamBase = CGMutablePath()
        let inner = radius - 1
        seamBase.move(to: CGPoint(x: 0, y: -inner))
        seamBase.addLine(to: CGPoint(x: 0, y: inner))
        seamBase.move(to: CGPoint(x: -9, y: -10.5))
        seamBase.addQuadCurve(to: CGPoint(x: -9, y: 10.5), control: CGPoint(x: -3.4, y: 0))
        seamBase.move(to: CGPoint(x: 9, y: -10.5))
        seamBase.addQuadCurve(to: CGPoint(x: 9, y: 10.5), control: CGPoint(x: 3.4, y: 0))
        var seamMap = compose([ballTr, turn(seamTurn)])
        let seams = seamBase.copy(using: &seamMap) ?? seamBase

        let gloveFill = CGMutablePath()
        let gloveInk = CGMutablePath()
        var gloveHide: CGPath = CGMutablePath()
        for hand in 0..<2 {
            let w = contact(t, hand)
            let (hx, hy) = home[hand]
            let m = hand == 0 ? -1.0 : 1.0
            let tx = x - 3.0 * (hand == 0 ? -1 : 1), ty = y - 2.0
            let px = hx + (tx - hx) * w
            var py = hy + (ty - hy) * w
            let fxs = handFx(t, hand)
            py += fxs.dy * (1 - w)
            var squeeze = 0.0
            for i in -1..<6 where owner[((i % 4) + 4) % 4] == hand {
                let d = abs(t - Double(i) * step)
                if d < 0.08 { squeeze = max(squeeze, 1 - d / 0.08) }
            }
            squeeze = ease(squeeze)
            let rot = m * (-14 - 18 * w + fxs.rot * (1 - w))
            let fx = (1 + 0.1 * squeeze) * (1 + (fxs.sx - 1) * (1 - w))
            let fy = (1 - 0.12 * squeeze) * (1 + (fxs.sy - 1) * (1 - w))
            let map = compose([CGAffineTransform(translationX: px, y: py), turn(rot), CGAffineTransform(scaleX: glove * m * fx, y: glove * fy), CGAffineTransform(translationX: -330, y: -560)])
            gloveFill.addPath(silhouette, transform: map)
            gloveInk.addPath(ink, transform: map)
            var handMap = map
            if let hand = silhouette.copy(using: &handMap) { gloveHide = gloveHide.union(hand) }
        }

        return DribbleFrame(shadow: shadow, shadowOpacity: shadowOpacity, dust: dust, streaks: streaks, streakOpacity: streakOpacity, ballFill: ballFill, ballRing: ballFill, seams: seams, gloveFill: gloveFill, gloveInk: gloveInk, gloveHide: gloveHide)
    }

    static let silhouetteText = """
M2770 7140 c-63 -5 -146 -15 -185 -23 -38 -8 -99 -18 -135 -22 -36 -4 -90 -17 -120 -30 -30 -13 -82 -30 -115 -38 -33 -9 -119 -42 -190 -75 -448 -204 -754 -571 -810 -971 -47 -329 21 -535 233 -710 74 -62 77 -81 27 -146 -107 -140 -162 -356 -151 -585 36 -724 5 -928 -219 -1440 -61 -140 -97 -275 -91 -345 23 -290 243 -475 566 -475 72 0 136 6 170 15 30 8 81 22 113 31 188 51 347 182 489 404 61 96 148 289 190 425 67 212 81 258 98 331 65 281 85 301 219 232 132 -68 258 -217 363 -428 60 -121 118 -266 118 -297 0 -10 12 -49 26 -88 14 -38 34 -117 44 -175 11 -58 27 -145 36 -195 20 -110 14 -412 -10 -545 -25 -134 -39 -361 -32 -518 7 -153 35 -261 99 -388 30 -60 158 -193 208 -216 19 -9 59 -27 89 -41 196 -90 443 -79 665 29 105 51 110 51 190 22 76 -27 322 -30 390 -5 22 9 69 26 105 40 36 13 83 33 105 45 22 12 43 22 48 22 40 0 251 185 331 290 124 163 218 419 236 644 15 178 25 195 133 215 153 28 274 139 353 324 159 372 -63 1211 -505 1903 -358 561 -790 999 -1340 1358 -84 55 -87 68 -31 159 105 169 67 428 -96 663 -55 79 -212 237 -258 261 -17 9 -55 34 -84 55 -29 22 -70 46 -90 55 -20 8 -48 23 -62 32 -26 18 -212 91 -231 91 -6 0 -43 13 -82 29 -40 15 -99 31 -132 35 -33 4 -87 14 -120 21 -58 13 -346 37 -409 33 -17 0 -83 -4 -146 -8z
"""

    static let inkText = """
M5590 14834 c-25 -2 -101 -8 -170 -14 -113 -10 -481 -65 -700 -106
-114 -21 -610 -187 -788 -263 -481 -206 -859 -457 -1197 -796 -592 -591 -874
-1251 -875 -2047 0 -456 99 -788 336 -1117 114 -159 119 -208 45 -429 -116
-345 -137 -503 -131 -972 9 -741 6 -1239 -8 -1365 -45 -399 -130 -686 -377
-1265 -225 -529 -283 -846 -217 -1178 177 -884 990 -1393 1991 -1246 220 32
517 124 710 220 599 297 1083 939 1376 1823 44 133 125 201 240 201 151 0 233
-109 323 -430 16 -58 46 -157 66 -220 36 -115 74 -292 122 -569 48 -276 42
-653 -15 -1057 -48 -333 -56 -459 -56 -844 0 -377 6 -457 52 -675 124 -597
484 -1068 992 -1300 323 -148 512 -189 866 -189 329 -1 515 32 804 143 182 69
219 76 328 56 334 -59 749 -38 1003 50 485 169 714 297 1024 574 497 443 788
985 920 1717 35 191 58 222 248 324 399 216 713 665 813 1165 123 615 -7 1470
-365 2415 -415 1093 -1072 2126 -1945 3053 -180 193 -340 343 -675 636 -540
472 -619 596 -725 1146 -59 307 -93 442 -161 640 -30 88 -59 174 -63 190 -18
66 -146 263 -270 415 -389 477 -893 811 -1581 1048 -369 127 -435 143 -878
218 -204 34 -868 64 -1062 48z m550 -1099 c193 -15 351 -32 380 -40 8 -2 92
-18 185 -34 174 -31 489 -128 696 -214 192 -80 522 -277 565 -338 11 -15 50
-62 88 -105 224 -256 293 -476 205 -653 -88 -176 -278 -224 -634 -161 -715
127 -765 130 -1035 58 -41 -11 -84 -22 -95 -25 -11 -2 -49 -13 -85 -23 -36
-10 -83 -23 -105 -29 -142 -34 -139 -31 -40 -57 112 -30 166 -42 230 -55 28
-5 74 -16 103 -24 28 -8 78 -22 110 -30 104 -28 216 -67 280 -96 34 -16 65
-29 68 -29 14 0 322 -139 454 -205 269 -133 445 -247 810 -520 269 -202 396
-287 680 -455 476 -281 759 -505 1159 -916 971 -996 1708 -2276 1996 -3469
118 -487 143 -964 59 -1140 -65 -137 -257 -178 -373 -79 -55 48 -69 85 -106
283 -38 205 -43 226 -136 551 -137 481 -192 637 -334 960 -171 387 -423 792
-572 917 -32 26 -94 83 -139 126 -99 93 -109 95 -100 25 3 -29 10 -118 15
-198 9 -139 13 -159 96 -460 48 -173 118 -412 156 -531 63 -200 88 -284 220
-759 78 -281 175 -802 199 -1070 6 -69 31 -245 56 -392 46 -277 50 -326 34
-393 -5 -22 -19 -121 -30 -220 -29 -249 -53 -366 -111 -540 -100 -298 -212
-489 -399 -675 -201 -200 -312 -275 -525 -356 -164 -61 -299 3 -340 164 -19
72 -16 91 51 374 121 516 180 1083 171 1648 -12 698 -93 1194 -283 1726 -119
335 -168 432 -304 604 -50 63 -102 130 -116 148 -14 17 -29 32 -33 32 -5 0
-12 -102 -16 -228 -7 -225 -7 -228 24 -392 41 -223 67 -396 85 -586 56 -569
67 -687 77 -839 20 -292 3 -592 -57 -1053 -50 -388 -91 -577 -175 -826 -33
-96 -70 -239 -104 -403 -76 -358 -85 -373 -297 -460 -68 -28 -167 -70 -222
-93 -535 -227 -1056 -40 -1210 434 -81 247 -83 719 -6 1256 52 366 68 898 35
1180 -30 259 -121 705 -185 910 -21 69 -55 181 -74 250 -63 229 -239 616 -404
887 -320 528 -762 886 -1166 945 -288 41 -559 -115 -699 -404 -67 -138 -80
-178 -161 -493 -323 -1255 -668 -1814 -1217 -1974 -231 -67 -373 -78 -557 -42
-221 43 -348 155 -387 341 -25 119 8 252 145 573 430 1018 522 1550 469 2742
-30 678 2 867 202 1167 150 227 186 424 115 633 -44 130 -85 186 -261 360
-219 218 -267 294 -299 484 -59 345 49 788 272 1122 310 463 758 778 1424
1000 222 74 255 83 500 124 145 24 328 49 408 54 80 6 163 13 185 14 98 8 204
6 385 -8z
"""
}

extension FlairLayer {
    func buildDribble() {
        let unit = side
        let k = unit / 110
        let frames = DribbleModel.frames
        let duration = DribbleModel.duration
        let steps = DribbleModel.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: (DribbleFrame) -> 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 opacities(_ pick: (DribbleFrame) -> Float) -> CAKeyframeAnimation {
            let values = (0..<steps).map { NSNumber(value: pick(frames[$0])) }
            let animation = keyframes("opacity", 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 under = container()
        under.removeFromSuperlayer()
        clipper.addSublayer(under)
        let cover = CAShapeLayer()
        cover.bounds = CGRect(origin: .zero, size: full)
        cover.position = mid
        cover.fillColor = CGColor(gray: 0, alpha: 1)
        func visible(_ frame: DribbleFrame) -> CGPath {
            CGPath(rect: CGRect(origin: .zero, size: full), transform: nil).subtracting(placed(frame.gloveHide))
        }
        cover.path = visible(frames[0])
        under.mask = cover

        let shadow = shape(placed(frames[0].shadow), size: full, at: mid, in: under)
        shadow.opacity = frames[0].shadowOpacity
        let dust = shape(placed(frames[0].dust), size: full, at: mid, in: under)
        let streaks = shape(placed(frames[0].streaks), size: full, at: mid, stroke: 3 * k, in: under)
        streaks.lineCap = .round
        streaks.opacity = frames[0].streakOpacity
        let ballFill = shape(placed(frames[0].ballFill), size: full, at: mid, in: under)
        ballFill.opacity = 0.22
        let ring = shape(placed(frames[0].ballRing), size: full, at: mid, stroke: 3.6 * k, in: under)
        let seams = shape(placed(frames[0].seams), size: full, at: mid, stroke: 3 * k, in: under)
        seams.lineCap = .round
        let gloveFill = shape(placed(frames[0].gloveFill), size: full, at: mid, in: clipper)
        gloveFill.opacity = 0.22
        let gloveInk = shape(placed(frames[0].gloveInk), size: full, at: mid, in: clipper)

        guard animating else { return }
        let reveal = keyframes("path", (0..<steps).map { visible(frames[$0]) }, times: times, timing: .linear)
        reveal.calculationMode = .discrete
        run(group([reveal], duration: duration), on: cover)
        run(group([paths { $0.shadow }, opacities { $0.shadowOpacity }], duration: duration), on: shadow)
        run(group([paths { $0.dust }], duration: duration), on: dust)
        run(group([paths { $0.streaks }, opacities { $0.streakOpacity }], duration: duration), on: streaks)
        run(group([paths { $0.ballFill }], duration: duration), on: ballFill)
        run(group([paths { $0.ballRing }], duration: duration), on: ring)
        run(group([paths { $0.seams }], duration: duration), on: seams)
        run(group([paths { $0.gloveFill }], duration: duration), on: gloveFill)
        run(group([paths { $0.gloveInk }], duration: duration), on: gloveInk)
    }
}
