import QuartzCore
import Foundation

private struct CastFrame {
    let rope: CGPath
    let tint: CGPath
    let dome: CGPath
    let line: CGPath
    let water: CGPath
    let rings: CGPath
    let drops: CGPath
    let rod: CGPath
    let reelTint: CGPath
    let reelRing: CGPath
}

private enum CastModel {
    typealias V = SIMD2<Double>

    static let duration = 4.4
    static let fps = 30.0
    static let count = 132
    static let sub = 8
    static let dt = 1.0 / (fps * Double(sub))
    static let rope = 22
    static let gravity = 650.0
    static let pivot = V(34, 98)
    static let rodLength = 54.0
    static let waterY = 96.0
    static let waterX0 = 48.0
    static let landX = 212.0
    static let lureDrop = 15.0
    static let tr = 0.98
    static let tl = 2.03
    static let ts = 3.05
    static let te = 3.75
    static let tu = 3.93

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }

    static func ease(_ value: Double) -> Double {
        let u = clamp(value)
        return u * u * (3 - 2 * u)
    }

    static func eout(_ value: Double) -> Double {
        let u = clamp(value)
        return 1 - pow(1 - u, 3)
    }

    static func back(_ value: Double) -> Double {
        let u = clamp(value) - 1
        return 1 + 2.7 * u * u * u + 1.7 * u * u
    }

    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 let angleKeys: [(Double, Double)] = [(0, 50), (0.35, 50), (0.45, 44), (0.85, 92), (0.92, 90), (1.02, 22), (1.16, 36), (1.6, 50), (3.05, 50), (3.2, 60), (3.75, 58), (4.05, 50)]
    static let bendKeys: [(Double, Double)] = [(0, -9), (0.35, -9), (0.45, -4), (0.7, -36), (0.85, 8), (0.91, 36), (0.97, 72), (1.03, -50), (1.11, 26), (1.2, -15), (1.29, 8), (1.38, -4), (3.05, -4), (3.2, -18), (3.75, -16), (3.9, -6), (4.05, -12), (4.2, -9)]
    static let camKeys: [(Double, Double)] = [(0, 0), (1.1, 0), (2.05, 130), (3.05, 130), (3.8, 0)]
    static let floatKeys: [(Double, Double)] = [(0.06, waterY + 3), (0.14, waterY - 4.5), (0.22, waterY - 2.5), (0.3, waterY - 3), (0.44, waterY + 11), (0.54, waterY + 12), (0.68, waterY - 5.5), (0.8, waterY - 2.2), (0.9, waterY - 3.4), (1.0, waterY - 3)]
    static let squashKeys: [(Double, Double)] = [(0, 0), (0.03, 0.32), (0.08, -0.12), (0.15, 0.07), (0.22, 0), (0.32, 0), (0.4, -0.18), (0.52, 0), (0.62, -0.22), (0.7, 0.17), (0.8, -0.06), (0.9, 0.02), (1.0, 0)]

    static func rodPoints(_ t: Double) -> [V] {
        let a = keys(t, angleKeys) * Double.pi / 180
        let b = keys(t, bendKeys) * Double.pi / 180
        var pts = [pivot]
        var p = pivot
        let n = 14
        for i in 0..<n {
            let s = (Double(i) + 0.5) / Double(n)
            let ang = a + b * s * s
            p.x += rodLength / Double(n) * cos(ang)
            p.y -= rodLength / Double(n) * sin(ang)
            pts.append(p)
        }
        return pts
    }

    static func tip(_ t: Double) -> V { rodPoints(t).last ?? pivot }

    static func floatY(_ u: Double) -> Double {
        if u < 0.06 { return waterY - 3 + 6 * eout(u / 0.06) }
        var y = keys(u, floatKeys)
        if u > 1.0 { y += 0.7 * sin((u - 1.0) * 9) }
        return y
    }

    static func keyed(_ t: Double, _ p0: V, _ tp: V) -> V {
        if t < tl {
            let u = (t - tr) / (tl - tr)
            let x = p0.x + (landX - p0.x) * (1 - exp(-2.0 * u)) / (1 - exp(-2.0))
            let y = p0.y + (waterY - 3 - p0.y) * u - 4 * 105.0 * u * (1 - u)
            return V(x, y)
        }
        if t < ts { return V(landX, floatY(t - tl)) }
        if t < te {
            let u = ease((t - ts) / (te - ts))
            return V(landX + (74 - landX) * u, waterY - 3 + 1.2 * sin(Double.pi * u))
        }
        let u = ease((t - te) / (tu - te))
        return V(74 + (tp.x - 74) * u, waterY - 3 + (tp.y + lureDrop - (waterY - 3)) * u)
    }

    static func length(_ v: V) -> Double { (v.x * v.x + v.y * v.y).squareRoot() }

    nonisolated(unsafe) static let sim: (ropes: [[V]], lures: [V], origin: V) = {
        let loop = count * sub
        var tp = tip(0)
        var lure = V(tp.x, tp.y + lureDrop)
        var lprev = lure
        var points = (0..<rope).map { tp + (lure - tp) * Double($0) / Double(rope - 1) }
        var prev = points
        var lr = lureDrop
        var held: V?
        var origin = V(0, 0)
        var ropes: [[V]] = Array(repeating: [], count: count)
        var lures: [V] = Array(repeating: V(0, 0), count: count)
        for step in 0..<(2 * loop) {
            let t = Double(step % loop) * dt
            tp = tip(t)
            if t < tr || t >= tu {
                let v = (lure - lprev) * 0.997
                lprev = lure
                lure += V(v.x, v.y + gravity * dt * dt)
                let diff = lure - tp
                let d = length(diff)
                if d > lureDrop { lure = tp + diff / d * lureDrop }
                held = nil
            } else {
                if held == nil {
                    held = lure
                    origin = lure
                }
                lprev = lure
                lure = keyed(t, held ?? lure, tp)
            }
            let d = length(lure - tp)
            if tr <= t && t < tl {
                lr = max(lr, d * 1.08)
            } else if ts <= t {
                lr = max(max(d, lr - 300 * dt), lureDrop)
            } else if t < tr {
                lr = lureDrop
            }
            let seg = lr / Double(rope - 1)
            for i in 1..<(rope - 1) {
                let p = points[i]
                let v = (p - prev[i]) * 0.995
                prev[i] = p
                points[i] = V(p.x + v.x, p.y + v.y + 300 * dt * dt)
            }
            points[0] = tp
            points[rope - 1] = lure
            for _ in 0..<30 {
                for i in 0..<(rope - 1) {
                    let diff = points[i + 1] - points[i]
                    let dd = max(length(diff), 1e-6)
                    if dd > seg {
                        let k = (dd - seg) / dd
                        if i == 0 {
                            points[i + 1] -= diff * k
                        } else if i == rope - 2 {
                            points[i] += diff * k
                        } else {
                            points[i] += diff * k / 2
                            points[i + 1] -= diff * k / 2
                        }
                    }
                }
                for i in 1..<(rope - 1) where points[i].x > waterX0 && points[i].y > waterY - 2.5 {
                    points[i].y = waterY - 2.5
                    prev[i].x = points[i].x + (prev[i].x - points[i].x) * 0.6
                }
            }
            points[0] = tp
            points[rope - 1] = lure
            if step >= loop && (step - loop) % sub == 0 {
                let f = (step - loop) / sub
                ropes[f] = points
                lures[f] = lure
            }
        }
        return (ropes, lures, origin)
    }()

    static func camera(_ t: Double) -> Double {
        if tr <= t && t < ts {
            let x = keyed(t, sim.origin, V(0, 0)).x
            return max(0, min(130, 0.76 * (x - sim.origin.x)))
        }
        return keys(t, camKeys)
    }

    static func cameraY(_ t: Double, _ frame: Int) -> Double {
        let ly = tr <= t && t < tl ? keyed(t, sim.origin, V(0, 0)).y : sim.lures[frame % count].y
        return max(0, 40 - ly) * 0.72
    }

    static func wave(_ x: Double, _ t: Double, _ lure: V) -> Double {
        var y = waterY + 1.6 * sin(x * 0.42 - 2 * Double.pi * 3 * t / duration)
        for (t0, a0) in [(tl, 4.2), (tl - duration, 4.2), (tl + 0.62, 2.2), (tl + 0.62 - duration, 2.2)] {
            let u = t - t0
            if u > 0 {
                let dx = abs(x - landX)
                let front = 8 + 50 * u
                let spread = (dx - front * 0.5) / 11
                y -= a0 * exp(-u * 2.2) * exp(-spread * spread) * cos(dx * 0.4 - u * 15)
            }
        }
        if ts < t && t < te + 0.1 {
            let w = sin(Double.pi * clamp((t - ts) / (te + 0.1 - ts)))
            let a = (x - (lure.x - 7)) / 4.5
            let b = (x - (lure.x + 12)) / 6
            y -= 3.2 * w * exp(-a * a)
            y -= 1.8 * w * exp(-b * b)
        }
        return y
    }

    static func clipLine(_ pts: [CGPoint], _ side: (CGPoint) -> Double) -> [[CGPoint]] {
        var pieces: [[CGPoint]] = []
        var current: [CGPoint] = []
        var before = 0.0
        for (i, p) in pts.enumerated() {
            let now = side(p)
            if i > 0 && (before >= 0) != (now >= 0) {
                let u = before / (before - now)
                let q = CGPoint(x: pts[i - 1].x + (p.x - pts[i - 1].x) * u, y: pts[i - 1].y + (p.y - pts[i - 1].y) * u)
                if before >= 0 {
                    current.append(q)
                    pieces.append(current)
                    current = []
                } else {
                    current = [q]
                }
            }
            if now >= 0 { current.append(p) }
            before = now
        }
        if !current.isEmpty { pieces.append(current) }
        return pieces.filter { $0.count >= 2 }
    }

    static func clipPolygon(_ pts: [CGPoint], _ side: (CGPoint) -> Double) -> [CGPoint] {
        var out: [CGPoint] = []
        for (i, p) in pts.enumerated() {
            let q = pts[(i + 1) % pts.count]
            let a = side(p)
            let b = side(q)
            if a >= 0 { out.append(p) }
            if (a >= 0) != (b >= 0) {
                let u = a / (a - b)
                out.append(CGPoint(x: p.x + (q.x - p.x) * u, y: p.y + (q.y - p.y) * u))
            }
        }
        return out
    }

    static func smooth(_ pts: [CGPoint], into path: CGMutablePath) {
        guard let first = pts.first, let last = pts.last else { return }
        path.move(to: first)
        if pts.count > 2 {
            for i in 1..<(pts.count - 1) {
                path.addQuadCurve(to: CGPoint(x: (pts[i].x + pts[i + 1].x) / 2, y: (pts[i].y + pts[i + 1].y) / 2), control: pts[i])
            }
        }
        path.addLine(to: last)
    }

    static func taper(_ pts: [V], from head: Double, to tail: Double) -> CGPath {
        let last = pts.count - 1
        var left: [CGPoint] = []
        var right: [CGPoint] = []
        var heading = 0.0
        var width = head
        for (i, p) in pts.enumerated() {
            let a = pts[max(i - 1, 0)]
            let b = pts[min(i + 1, last)]
            heading = atan2(b.y - a.y, b.x - a.x)
            width = (head + (tail - head) * Double(i) / Double(last)) / 2
            left.append(CGPoint(x: p.x - sin(heading) * width, y: p.y + cos(heading) * width))
            right.append(CGPoint(x: p.x + sin(heading) * width, y: p.y - cos(heading) * width))
        }
        let end = pts[last]
        let start = pts[0]
        let startHeading = atan2(pts[1].y - start.y, pts[1].x - start.x)
        let cap = (1..<8).map { step -> CGPoint in
            let angle = heading + Double.pi / 2 - Double.pi * Double(step) / 8
            return CGPoint(x: end.x + cos(angle) * tail / 2, y: end.y + sin(angle) * tail / 2)
        }
        let back = (1..<8).map { step -> CGPoint in
            let angle = startHeading - Double.pi / 2 - Double.pi * Double(step) / 8
            return CGPoint(x: start.x + cos(angle) * head / 2, y: start.y + sin(angle) * head / 2)
        }
        let path = CGMutablePath()
        path.addLines(between: left + cap + right.reversed() + back)
        path.closeSubpath()
        return path
    }

    static func frame(_ f: Int, unit: Double) -> CastFrame {
        let t = Double(f) / fps
        let ropePoints = sim.ropes[f]
        let lure = sim.lures[f]
        let cx = camera(t)
        let cy = cameraY(t, f)
        let k = unit / 110
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: (-cx - 5) * k, ty: unit + (5 - cy + 4) * k)
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        func surface(_ p: CGPoint) -> Double { wave(Double(p.x), t, lure) - Double(p.y) }

        let q = ropePoints[rope - 3]
        var rot = atan2(q.x - lure.x, -(q.y - lure.y)) * 180 / Double.pi
        var st = 1.0
        if tr < t && t < tl { st = 1 + 0.38 * (1 - ease((t - tr) / (0.45 * (tl - tr)))) }
        var sx = 1 / st
        var sy = st
        let u = t - tl
        if 0 < u && u < 1.1 {
            let kk = keys(u, squashKeys)
            sx = 1 + kk
            sy = 1 - kk
        }
        if 0 < u && u < ts - tl + 0.2 {
            rot *= 1 - clamp(u / 0.08) * (1 - clamp((u - (ts - tl - 0.05)) / 0.2))
        }
        let radius = 6.5
        let place = CGAffineTransform(translationX: lure.x, y: lure.y).rotated(by: rot * Double.pi / 180).scaledBy(x: sx, y: sy)
        func local(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x, y: y).applying(place) }
        let stemTip = local(0, -(radius + 3.5))

        var ropeKeep: [CGPoint] = []
        for p in ropePoints {
            if length(p - lure) <= radius + 3.5 { break }
            ropeKeep.append(CGPoint(x: p.x, y: p.y))
        }
        ropeKeep.append(stemTip)
        let ropePath = CGMutablePath()
        for piece in clipLine(ropeKeep, surface) { smooth(piece, into: ropePath) }

        let arc = (0...18).map { i -> CGPoint in
            let a = Double.pi * Double(i) / 18
            return local(-radius * cos(a), -radius * sin(a))
        }
        let lower = (0...18).map { i -> CGPoint in
            let a = Double.pi * Double(i) / 18
            return local(radius * cos(a), radius * sin(a))
        }
        func fill(_ pts: [CGPoint]) -> CGPath {
            let path = CGMutablePath()
            let clipped = clipPolygon(pts, surface)
            if clipped.count > 2 {
                path.addLines(between: clipped)
                path.closeSubpath()
            }
            return path
        }
        let ring = (0...36).map { i -> CGPoint in
            let a = 2 * Double.pi * Double(i) / 36
            return local(radius * cos(a), radius * sin(a))
        }
        let lineGroup = CGMutablePath()
        let ringPieces = clipLine(ring, surface)
        if ringPieces.count == 1 && ringPieces[0].count == ring.count {
            lineGroup.addLines(between: Array(ring.dropLast()))
            lineGroup.closeSubpath()
        } else {
            for piece in ringPieces {
                lineGroup.addLines(between: piece)
            }
        }
        for piece in clipLine([local(0, -radius), stemTip], surface) { lineGroup.addLines(between: piece) }

        let x0 = max(waterX0, cx)
        let x1 = cx + 125
        let waterPath = CGMutablePath()
        if x1 > x0 {
            let pts = (0...44).map { i -> CGPoint in
                let x = x0 + (x1 - x0) * Double(i) / 44
                return CGPoint(x: x, y: wave(x, t, lure))
            }
            waterPath.addLines(between: pts)
        }

        let rings = CGMutablePath()
        for (i, (dx, r)) in [(-2.0, 2.2), (3, 1.6), (-4, 1.3), (2, 1.9)].enumerated() {
            let t0 = tl + 0.4 + 0.055 * Double(i)
            let uu = t - t0
            if 0 < uu && uu < 0.4 {
                let y = waterY + 10 - 70 * uu
                let x = landX + dx + 1.5 * sin(uu * 30 + Double(i))
                if y > waterY - 1 {
                    let rr = r * back(uu / 0.08) * (1 - ease((y - (waterY + 1)) / -2))
                    if rr > 0.2 { rings.addEllipse(in: CGRect(x: x - rr, y: y - rr, width: 2 * rr, height: 2 * rr)) }
                }
            }
        }

        let drops = CGMutablePath()
        func blob(_ x: Double, _ y: Double, _ r: Double) {
            if r > 0.15 { drops.addEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r)) }
        }
        for (vx, vy, r, d0) in [(-55.0, 170.0, 3.6, 0.0), (-16, 215, 3.2, 0.03), (20, 200, 3.4, 0.015), (58, 160, 3.0, 0.04)] {
            let uu = t - tl - d0
            if 0 < uu && uu < 0.6 {
                let x = landX + (vx > 0 ? 5 : -5) + vx * uu
                let y = waterY - 4 - vy * uu + 0.5 * 1150 * uu * uu
                if y < waterY + 2 { blob(x, y, r * back(uu / 0.12) * (1 - ease((uu - 0.38) / 0.2))) }
            }
        }
        for j in 0..<7 {
            let t0 = ts + 0.08 + Double(j) * 0.09
            let uu = t - t0
            if 0 < uu && uu < 0.32 {
                let sxx = landX + (74 - landX) * ease((t0 - ts) / (te - ts)) + 6
                let x = sxx + Double(10 + 3 * (j % 3)) * uu
                let y = waterY - 3 - 70 * uu + 0.5 * 600 * uu * uu
                if y < waterY + 1 { blob(x, y, (2.4 - 0.4 * Double(j % 2)) * back(uu / 0.08) * (1 - ease((uu - 0.2) / 0.12))) }
            }
        }
        for (vx, vy, r) in [(-8.0, 20.0, 2.6), (6, 10, 2.2)] {
            let uu = t - te - 0.06
            if 0 < uu && uu < 0.4 {
                let x = 74 + vx * uu * 2
                let y = waterY - 8 + vy * uu + 0.5 * 500 * uu * uu
                if y < waterY + 1 { blob(x, y, r * (1 - ease((uu - 0.25) / 0.15))) }
            }
        }

        let angle = keys(t, angleKeys)
        let spin = CGAffineTransform(translationX: pivot.x, y: pivot.y).rotated(by: -angle * Double.pi / 180).translatedBy(x: -pivot.x, y: -pivot.y)
        let rodPath = CGMutablePath()
        rodPath.addPath(taper(rodPoints(t), from: 4.8, to: 1.8))
        rodPath.addPath(CGPath(roundedRect: CGRect(x: pivot.x - 10, y: pivot.y - 4, width: 24, height: 8), cornerWidth: 4, cornerHeight: 4, transform: nil), transform: spin)
        let reelCenter = CGPoint(x: pivot.x + 2, y: pivot.y + 7).applying(spin)
        rodPath.addEllipse(in: CGRect(x: reelCenter.x - 1.8, y: reelCenter.y - 1.8, width: 3.6, height: 3.6))
        let reel = CGPath(ellipseIn: CGRect(x: reelCenter.x - 6, y: reelCenter.y - 6, width: 12, height: 12), transform: nil)

        return CastFrame(
            rope: placed(ropePath),
            tint: placed(fill(lower)),
            dome: placed(fill(arc)),
            line: placed(lineGroup),
            water: placed(waterPath),
            rings: placed(rings),
            drops: placed(drops),
            rod: placed(rodPath),
            reelTint: placed(reel),
            reelRing: placed(reel)
        )
    }
}

extension FlairLayer {
    func buildCast() {
        let unit = side
        let k = unit / 110
        let steps = CastModel.count
        let duration = CastModel.duration
        let frames = (0..<steps).map { CastModel.frame($0, unit: unit) }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func paths(_ pick: (CastFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { pick(frames[$0]) }
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", 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 rope = shape(frames[0].rope, size: full, at: mid, stroke: 2 * k, in: clipper)
        rope.lineCap = .round
        rope.lineJoin = .round
        let tint = shape(frames[0].tint, size: full, at: mid, in: clipper)
        tint.opacity = 0.22
        let dome = shape(frames[0].dome, size: full, at: mid, in: clipper)
        let line = shape(frames[0].line, size: full, at: mid, stroke: 3 * k, in: clipper)
        line.lineCap = .round
        line.lineJoin = .round
        let water = shape(frames[0].water, size: full, at: mid, stroke: 3.5 * k, in: clipper)
        water.lineCap = .round
        water.lineJoin = .round
        let rings = shape(frames[0].rings, size: full, at: mid, stroke: 1.6 * k, in: clipper)
        let drops = shape(frames[0].drops, size: full, at: mid, in: clipper)
        let rod = shape(frames[0].rod, size: full, at: mid, in: clipper)
        let reelTint = shape(frames[0].reelTint, size: full, at: mid, in: clipper)
        reelTint.opacity = 0.22
        let reelRing = shape(frames[0].reelRing, size: full, at: mid, stroke: 3 * k, in: clipper)

        guard animating else { return }
        let targets: [(CAShapeLayer, (CastFrame) -> CGPath)] = [
            (rope, { $0.rope }), (tint, { $0.tint }), (dome, { $0.dome }), (line, { $0.line }), (water, { $0.water }),
            (rings, { $0.rings }), (drops, { $0.drops }), (rod, { $0.rod }), (reelTint, { $0.reelTint }), (reelRing, { $0.reelRing }),
        ]
        for (layer, pick) in targets {
            run(group([paths(pick)], duration: duration), on: layer)
        }
    }
}
