import QuartzCore
import Foundation

private struct SnatchFrame {
    let tint: CGPath
    let ink: CGPath
}

private struct SnatchCanvas {
    var tint = CGMutablePath() as CGPath
    var ink = CGMutablePath() as CGPath

    mutating func put(fill: CGPath, outline: CGPath, tinted: Bool = true) {
        let region = fill.union(outline)
        tint = tint.subtracting(region)
        if tinted { tint = tint.union(fill) }
        ink = ink.subtracting(region).union(outline)
    }

    mutating func solid(_ path: CGPath) {
        tint = tint.subtracting(path)
        ink = ink.union(path)
    }

    mutating func line(_ path: CGPath) {
        ink = ink.union(path)
    }
}

private enum SnatchModel {
    static let duration = 3.2
    static let count = 96
    static let d = 0.6
    static let bx = 60.0
    static let gy = 98.0
    static let k = 1.05
    static let ts = 1.02
    static let ta = 1.1
    static let tr = 1.2
    static let tc = 1.36
    static let ocx = 60.0
    static let ocy = 25.0
    static let orx = 26.0
    static let ory = 9.0
    static let op = 1.6

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

    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 back(_ u: Double) -> Double {
        let v = clamp(u) - 1
        return 1 + 2.7 * v * v * v + 1.7 * v * v
    }

    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 orbit(_ t: Double) -> (Double, Double, Double) {
        let a = 2 * Double.pi * t / op
        return (ocx + orx * cos(a), ocy + ory * sin(a), sin(a))
    }

    static func pose(_ rt: Double) -> (Double, Double) {
        let t = rt - d
        var sy = keys(t, [(0, 1), (0.15, 1), (0.45, 0.965), (0.85, 0.965), (0.98, 0.93), (1.06, 1.04), (1.2, 1.03), (1.34, 1.0), (1.42, 0.95), (1.56, 1.02), (1.7, 0.995), (1.8, 1)])
        let sx = keys(t, [(0, 1), (1.38, 1), (1.46, 1.09), (1.58, 0.98), (1.72, 1.02), (1.85, 1)])
        let br = 0.01 * sin(2 * Double.pi * rt / 0.64) * (1 - ease((t - 0.05) / 0.3) + ease((t - 1.9) / 0.3))
        sy += br
        return (sx / sy.squareRoot(), sy)
    }

    static func tw(_ p: (Double, Double), _ ps: (Double, Double)) -> (Double, Double) {
        (bx + p.0 * ps.0 * k, gy + p.1 * ps.1 * k)
    }

    static func mouthOpen(_ rt: Double) -> Double {
        let t = rt - d
        return keys(t, [(0, 0), (0.85, 0), (0.98, 0.12), (1.03, 1), (1.3, 1), (1.4, 0)])
    }

    static func target() -> (Double, Double) {
        let o = orbit(ta + d)
        return (o.0, o.1)
    }

    static func tongue(_ rt: Double, _ ps: (Double, Double)) -> ((Double, Double)?, (Double, Double)) {
        let m = tw((0, -21 + 19 * mouthOpen(rt) - 7), ps)
        let t = rt - d
        if t < ts || t > tc || (t > tr && mouthOpen(t + d) < 0.75) { return (nil, m) }
        let tg = target()
        let e: Double
        if t < ta { e = eout((t - ts) / (ta - ts)) } else if t < tr { e = 1 } else { e = 1 - ease((t - tr) / (tc - 0.06 - tr)) }
        return ((m.0 + (tg.0 - m.0) * e, m.1 + (tg.1 - m.1) * e), m)
    }

    static func stroked(_ path: CGPath, _ width: Double, cap: CGLineCap = .butt) -> CGPath {
        path.copy(strokingWithWidth: width, lineCap: cap, lineJoin: .round, miterLimit: 10)
    }

    static func circle(_ x: Double, _ y: Double, _ r: Double) -> CGPath {
        CGPath(ellipseIn: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2), transform: nil)
    }

    static func ellipse(_ x: Double, _ y: Double, _ rx: Double, _ ry: Double) -> CGPath {
        CGPath(ellipseIn: CGRect(x: x - rx, y: y - ry, width: rx * 2, height: ry * 2), transform: nil)
    }

    nonisolated(unsafe) static let bodyPath: CGPath = {
        let p = CGMutablePath()
        func pt(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x, y: y) }
        p.move(to: pt(-34, 0))
        p.addCurve(to: pt(-17, -37), control1: pt(-42, -20), control2: pt(-32, -36))
        p.addQuadCurve(to: pt(17, -37), control: pt(0, -32))
        p.addCurve(to: pt(34, 0), control1: pt(32, -36), control2: pt(42, -20))
        p.closeSubpath()
        return p
    }()

    static func frog(_ t: Double, _ ps: (Double, Double), _ fly: (Double, Double), into canvas: inout SnatchCanvas) {
        var local = SnatchCanvas()
        let o = mouthOpen(t)
        for s in [-1.0, 1.0] {
            let e = ellipse(31 * s, -9, 11, 9)
            local.put(fill: e, outline: stroked(e, 3.5))
        }
        local.put(fill: bodyPath, outline: stroked(bodyPath, 3.5))
        for s in [-1.0, 1.0] {
            let e = ellipse(21 * s, -1.5, 8, 4.6)
            local.put(fill: e, outline: stroked(e, 3.5))
        }
        let w = 21 + 4 * o
        if o < 0.05 {
            let p = CGMutablePath()
            p.move(to: CGPoint(x: -20, y: -17))
            p.addQuadCurve(to: CGPoint(x: 20, y: -17), control: CGPoint(x: 0, y: -25))
            local.line(stroked(p, 3, cap: .round))
        } else {
            let lo = -21 + 19 * o
            let cy = -18 - 3 * o
            let tp = -21 - 9 * o
            let p = CGMutablePath()
            p.move(to: CGPoint(x: -w, y: cy))
            p.addQuadCurve(to: CGPoint(x: w, y: cy), control: CGPoint(x: 0, y: tp))
            p.addCurve(to: CGPoint(x: -w, y: cy), control1: CGPoint(x: w * 0.95, y: lo), control2: CGPoint(x: -w * 0.95, y: lo))
            p.closeSubpath()
            local.put(fill: p, outline: stroked(p, 3), tinted: false)
            if o > 0.4 { local.line(ellipse(0, lo - 6 * o, 9 * o, 3.6 * o)) }
        }
        let lid = keys(t - d, [(0, 0), (0.1, 0), (0.45, -2.5), (0.95, -2.5), (1.0, -5), (1.35, -5), (1.5, 0)])
        for s in [-1.0, 1.0] {
            let ex = 18 * s
            let ey = -39.0
            let eye = circle(ex, ey, 10.5)
            local.put(fill: eye, outline: CGMutablePath(), tinted: false)
            let (wx, wy) = tw((ex, ey), ps)
            let dx = fly.0 - wx
            let dy = fly.1 - wy
            let dist = hypot(dx, dy) == 0 ? 1 : hypot(dx, dy)
            local.solid(circle(ex + 3.2 * dx / dist, ey + 1.5 + 2.4 * dy / dist, 4.2))
            let yo = ey - 2 + lid
            let yi = ey + 2 + lid
            let xo = ex + 13 * s
            let xi = ex - 13 * s
            let poly = CGMutablePath()
            poly.move(to: CGPoint(x: xo, y: yo))
            poly.addLine(to: CGPoint(x: xi, y: yi))
            poly.addLine(to: CGPoint(x: xi, y: ey - 14))
            poly.addLine(to: CGPoint(x: xo, y: ey - 14))
            poly.closeSubpath()
            let edge = stroked(poly, 3.5)
            local.put(fill: poly.intersection(eye), outline: edge.intersection(eye))
            local.line(stroked(eye, 3.5))
        }
        var tf = CGAffineTransform.identity.translatedBy(x: bx, y: gy).scaledBy(x: ps.0 * k, y: ps.1 * k)
        let tinted = local.tint.copy(using: &tf) ?? local.tint
        let inked = local.ink.copy(using: &tf) ?? local.ink
        canvas.tint = canvas.tint.union(tinted)
        canvas.ink = canvas.ink.union(inked)
    }

    static func flyPaths(_ x: Double, _ y: Double, _ t: Double, _ s: Double, _ smear: (Double, Double)?, into canvas: inout SnatchCanvas) {
        if s < 0.05 { return }
        let f = sin(2 * Double.pi * t * 5)
        var wingFill = CGMutablePath() as CGPath
        var wingInk = CGMutablePath() as CGPath
        for sd in [-1.0, 1.0] {
            var rot = CGAffineTransform.identity
                .translatedBy(x: x, y: y - 1)
                .rotated(by: sd * (10 + 28 * f) * .pi / 180)
                .translatedBy(x: -x, y: -(y - 1))
            let c = circle(x + 3.6 * sd, y - 3.8, 3.2)
            let ring = stroked(c, 1.8)
            let region = c.union(ring)
            wingFill = wingFill.union(c.copy(using: &rot) ?? c)
            wingInk = wingInk.union(ring.copy(using: &rot) ?? ring)
            _ = region
        }
        let bodyDot = circle(x, y, 3.6)
        var inner = CGAffineTransform.identity.translatedBy(x: x, y: y).scaledBy(x: 1.2 * s, y: 1.2 * s).translatedBy(x: -x, y: -y)
        var full = inner
        if let smear {
            let (ang, kk) = smear
            let outer = CGAffineTransform.identity
                .translatedBy(x: x, y: y)
                .rotated(by: ang * .pi / 180)
                .scaledBy(x: kk, y: 1 / kk)
                .rotated(by: -ang * .pi / 180)
                .translatedBy(x: -x, y: -y)
            full = inner.concatenating(outer)
        }
        inner = full
        let tintPart = wingFill.copy(using: &inner) ?? wingFill
        let inkPart = wingInk.union(bodyDot).copy(using: &inner) ?? wingInk
        canvas.tint = canvas.tint.union(tintPart)
        canvas.ink = canvas.ink.subtracting(tintPart).union(inkPart)
    }

    static func trail(_ t: Double, _ grow: Double, into canvas: inout SnatchCanvas) {
        if grow < 0.05 { return }
        let p = CGMutablePath()
        for i in 0...Int(32 * grow) {
            let o = orbit(t - 0.012 * Double(i))
            if i == 0 { p.move(to: CGPoint(x: o.0, y: o.1)) } else { p.addLine(to: CGPoint(x: o.0, y: o.1)) }
        }
        let dashed = p.copy(dashingWithPhase: 0.8, lengths: [2.2, 3.6])
        canvas.line(stroked(dashed, 1.8, cap: .round))
    }

    static func smear(_ c: Double, _ tip: (Double, Double), _ m: (Double, Double)) -> (Double, Double) {
        let ang = atan2(tip.1 - m.1, tip.0 - m.0) * 180 / .pi
        var kk = 1 + 0.55 * sin(.pi * clamp((c - tr) / (tc - 0.06 - tr)))
        kk *= 1 - 0.3 * sin(.pi * clamp((c - ta) / 0.1))
        return (ang, kk)
    }

    static func fxLines(_ c: Double, _ tip: (Double, Double), into canvas: inout SnatchCanvas) {
        let u = (c - ta) / 0.22
        guard u > 0 && u < 1 else { return }
        let e = eout(u)
        for i in 0..<7 {
            let th = (-90 + Double(i - 3) * 34) * .pi / 180
            let r0 = 8 + 9 * e
            let r1 = 11 + 9 * e - 3 * u
            let w = 2.6 * (1 - ease((u - 0.3) / 0.7))
            if w > 0.2 && r1 > r0 {
                let p = CGMutablePath()
                p.move(to: CGPoint(x: tip.0 + r0 * cos(th), y: tip.1 + r0 * sin(th)))
                p.addLine(to: CGPoint(x: tip.0 + r1 * cos(th), y: tip.1 + r1 * sin(th)))
                canvas.line(stroked(p, w, cap: .round))
            }
        }
    }

    static func build(_ t: Double) -> SnatchFrame {
        let ps = pose(t)
        let (tipOpt, m) = tongue(t, ps)
        var (fx, fy, depth) = orbit(t)
        var fs = 1.0 + 0.15 * depth
        let c = t - d
        let stuck = tipOpt != nil && c >= ta
        if stuck, let tip = tipOpt {
            fx = tip.0
            fy = tip.1
            fs = c < tr ? 1.0 : clamp((1 - ease((c - tr) / (tc - 0.06 - tr))) / 0.35)
        } else if ta <= c && c < 2.0 {
            fs = 0
        } else if 2.0 <= c && c < 2.3 {
            fs *= back((c - 2.0) / 0.3)
        }
        var canvas = SnatchCanvas()
        let tg: Double
        if c >= ta && c < 2.0 { tg = 0 } else if 2.0 <= c && c < 2.5 { tg = ease((c - 2.0) / 0.5) } else { tg = 1 - ease((c - ts + 0.1) / 0.1) }
        trail(t, stuck ? 0 : tg, into: &canvas)
        frog(t, ps, (fx, fy), into: &canvas)
        if let tip = tipOpt {
            let dx = tip.0 - m.0
            let dy = tip.1 - m.1
            let len = hypot(dx, dy) == 0 ? 1 : hypot(dx, dy)
            let px = -dy / len
            let py = dx / len
            var left: [CGPoint] = []
            var right: [CGPoint] = []
            for i in 0..<13 {
                let u = Double(i) / 12
                let r = 5.2 - 2.2 * pow(u, 0.6)
                let x = m.0 + dx * u
                let y = m.1 + dy * u
                left.append(CGPoint(x: x + px * r, y: y + py * r))
                right.append(CGPoint(x: x - px * r, y: y - py * r))
            }
            let ribbon = CGMutablePath()
            ribbon.addLines(between: left + right.reversed())
            ribbon.closeSubpath()
            canvas.solid(ellipse(m.0, m.1 + 1, 7.5, 3.6))
            canvas.solid(ribbon)
            canvas.solid(circle(tip.0, tip.1, 5.5))
            fxLines(c, tip, into: &canvas)
        }
        let sm: (Double, Double)? = (stuck && tipOpt != nil) ? smear(c, tipOpt!, m) : nil
        flyPaths(fx, fy, t, fs, sm, into: &canvas)
        return SnatchFrame(tint: canvas.tint, ink: canvas.ink)
    }
}

extension FlairLayer {
    func buildSnatch() {
        let unit = side
        let k = unit / 110
        let frames = SnatchModel.frames
        let duration = SnatchModel.duration
        let steps = SnatchModel.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)
        func paths(_ pick: (SnatchFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { placed(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

        shape(placed(SnatchModel.ellipse(60, SnatchModel.gy + 1, 48, 6.5)), size: full, at: mid, in: clipper)
        let tint = shape(placed(frames[0].tint), size: full, at: mid, in: clipper)
        tint.opacity = 0.22
        let ink = shape(placed(frames[0].ink), size: full, at: mid, in: clipper)

        guard animating else { return }
        run(group([paths { $0.tint }], duration: duration), on: tint)
        run(group([paths { $0.ink }], duration: duration), on: ink)
    }
}
