import QuartzCore
import Foundation

private func dabbleChain(_ ops: [CGAffineTransform]) -> CGAffineTransform {
    ops.reversed().reduce(CGAffineTransform.identity) { $0.concatenating($1) }
}

private func dabbleMove(_ x: Double, _ y: Double) -> CGAffineTransform {
    CGAffineTransform(translationX: x, y: y)
}

private func dabbleScale(_ x: Double, _ y: Double) -> CGAffineTransform {
    CGAffineTransform(scaleX: x, y: y)
}

private func dabbleSpin(_ degrees: Double, _ x: Double = 0, _ y: Double = 0) -> CGAffineTransform {
    dabbleChain([dabbleMove(x, y), CGAffineTransform(rotationAngle: degrees * .pi / 180), dabbleMove(-x, -y)])
}

private func dabblePath(_ d: String) -> CGPath {
    var tokens: [String] = []
    var number = ""
    for ch in d {
        if ch.isLetter {
            if !number.isEmpty { tokens.append(number); number = "" }
            tokens.append(String(ch))
        } else if ch == " " {
            if !number.isEmpty { tokens.append(number); number = "" }
        } else {
            number.append(ch)
        }
    }
    if !number.isEmpty { tokens.append(number) }
    let path = CGMutablePath()
    var i = 0
    func next() -> CGPoint {
        let x = Double(tokens[i]) ?? 0
        let y = Double(tokens[i + 1]) ?? 0
        i += 2
        return CGPoint(x: x, y: y)
    }
    while i < tokens.count {
        let cmd = tokens[i]
        i += 1
        switch cmd {
        case "M": path.move(to: next())
        case "L": path.addLine(to: next())
        case "C":
            let c1 = next()
            let c2 = next()
            path.addCurve(to: next(), control1: c1, control2: c2)
        case "Q":
            let c = next()
            path.addQuadCurve(to: next(), control: c)
        case "Z": path.closeSubpath()
        default: break
        }
    }
    return path
}

private enum DabbleItem {
    case circle(Double, Double, Double)
    case ellipse(Double, Double, Double, Double)
    case line([CGPoint], Double)
}

private struct DabbleFrame {
    let outer: CGPath
    let tint: CGPath
    let footTint: CGPath
    let details: CGPath
    let water: CGPath
    let surface: CGPath
}

private enum DabbleModel {
    typealias Keys = [(Double, Double)]

    static let duration = 3.3
    static let count = 99
    static let wy = 80.0
    static let dx = 46.0
    static let ex = dx + 20
    static let te = 1.0
    static let tp = 2.54

    static let rot: Keys = [(0, 0), (0.45, 0), (0.78, -24), (0.9, -27), (1.04, 116), (1.12, 100), (1.21, 105), (2.42, 103), (2.57, -8), (2.73, 4), (2.87, -2), (3.01, 0.5), (3.3, 0)]
    static let lift: Keys = [(0, 0), (0.45, 0), (0.78, -1), (0.9, 5), (1.04, -14), (1.12, -8), (1.21, -10), (2.42, -10), (2.48, -12), (2.6, 8), (2.72, 0), (2.84, 1.2), (2.96, 0)]
    static let shift: Keys = [(0, 0), (0.45, 0), (0.78, -3), (0.9, -3.5), (1.04, 4), (2.42, 4), (2.67, 0)]
    static let squash: Keys = [(0, 1), (0.45, 1), (0.74, 0.9), (0.9, 1.16), (0.98, 1.12), (1.08, 0.94), (1.18, 1.02), (1.26, 1), (2.42, 1), (2.57, 1.08), (2.71, 0.9), (2.81, 1.04), (2.93, 0.98), (3.03, 1)]

    nonisolated(unsafe) static let body = dabblePath("M-24 -17 C-19 -12 -15 -11 -8 -12 L1.7 -15.2 C-2 -18 -4 -23 -4 -28 C-4 -36 2 -41 9.5 -41 C17 -41 22.5 -35 22.5 -27 C22.5 -21 19 -19 18.6 -16.5 C18.3 -14 23.5 -12.5 23 -8 C22.6 -4.5 21 -2 19.3 -1 C17 3 12 4 0 4 C-16 4 -21 -6 -24 -17 Z")
    nonisolated(unsafe) static let beak = dabblePath("M20 -31 Q27.5 -33 31.5 -30 Q33.5 -27.5 30.5 -25.5 Q25.5 -23.8 20 -24.5 Z")
    nonisolated(unsafe) static let wing = dabblePath("M-10 -7 Q-3 -1 7 -7")
    nonisolated(unsafe) static let foot = dabblePath("M-2 4 C-6 7 -9.5 11 -8.5 14.5 Q-4.5 12.5 0 16.5 Q4.5 12.5 8.5 14.5 C9.5 11 6 7 2 4 Q0 2.8 -2 4 Z")
    nonisolated(unsafe) static let leg: CGPath = {
        let path = CGMutablePath()
        path.move(to: .zero)
        path.addLine(to: CGPoint(x: 0, y: 5))
        return path
    }()

    nonisolated(unsafe) static let outerLocal: CGPath = {
        let beakSolid = beak.union(beak.copy(strokingWithWidth: 3.6, lineCap: .butt, lineJoin: .round, miterLimit: 10))
        let ring = body.copy(strokingWithWidth: 7.2, lineCap: .butt, lineJoin: .round, miterLimit: 10)
        return beakSolid.union(ring).subtracting(body)
    }()

    nonisolated(unsafe) static let eye: CGPath = CGPath(ellipseIn: CGRect(x: 13.5 - 2.6, y: -30 - 2.6, width: 5.2, height: 5.2), transform: nil)
    nonisolated(unsafe) static let wingStroke: CGPath = wing.copy(strokingWithWidth: 3.2, lineCap: .round, lineJoin: .round, miterLimit: 10)

    static let drops: [(Double, Double, Double, Double)] = {
        var out: [(Double, Double, Double, Double)] = []
        for i in 0..<7 {
            for side in [-1.0, 1.0] {
                let seed = (Double(i) * 0.618 + (side > 0 ? 0.3 : 0)).truncatingRemainder(dividingBy: 1)
                let ang = (52 + 28 * seed) * .pi / 180
                let sp = 150 + 50 * (Double(i) * 0.37 + 0.5).truncatingRemainder(dividingBy: 1)
                out.append((side * sp * cos(ang), sp * sin(ang), 3.0 + 1.6 * (Double(i) * 0.53).truncatingRemainder(dividingBy: 1), 0.04 + 0.03 * Double(i % 3)))
            }
        }
        out.append((0, 175, 2.8, 0.05))
        return out
    }()

    static func blur(_ field: inout [Float], _ w: Int, _ h: Int, _ radius: Int) {
        let inv = 1 / Float(2 * radius + 1)
        var cum = [Float](repeating: 0, count: max(w, h) + 1)
        for _ in 0..<3 {
            for y in 0..<h {
                let base = y * w
                for x in 0..<w { cum[x + 1] = cum[x] + field[base + x] }
                for x in 0..<w { field[base + x] = (cum[min(x + radius + 1, w)] - cum[max(x - radius, 0)]) * inv }
            }
            for x in 0..<w {
                for y in 0..<h { cum[y + 1] = cum[y] + field[y * w + x] }
                for y in 0..<h { field[y * w + x] = (cum[min(y + radius + 1, h)] - cum[max(y - radius, 0)]) * inv }
            }
        }
    }

    static func contour(_ items: [DabbleItem], _ sigma: Double) -> CGPath {
        let path = CGMutablePath()
        guard !items.isEmpty else { return path }
        let res = 2.0
        var minX = Double.infinity
        var minY = Double.infinity
        var maxX = -Double.infinity
        var maxY = -Double.infinity
        func grow(_ x: Double, _ y: Double, _ r: Double) {
            minX = min(minX, x - r)
            maxX = max(maxX, x + r)
            minY = min(minY, y - r)
            maxY = max(maxY, y + r)
        }
        for item in items {
            switch item {
            case let .circle(x, y, r): grow(x, y, r)
            case let .ellipse(x, y, rx, ry): grow(x, y, max(rx, ry))
            case let .line(ps, w): ps.forEach { grow(Double($0.x), Double($0.y), w / 2) }
            }
        }
        let pad = sigma * 3.5 + 1
        let x0 = max(minX - pad, -14)
        let y0 = max(minY - pad, -16)
        let x1 = min(maxX + pad, 120)
        let y1 = min(maxY + pad, 110)
        guard x1 > x0, y1 > y0 else { return path }
        let w = Int(ceil((x1 - x0) * res)) + 2
        let h = Int(ceil((y1 - y0) * res)) + 2
        guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return path }
        ctx.translateBy(x: 0, y: CGFloat(h))
        ctx.scaleBy(x: 1, y: -1)
        ctx.scaleBy(x: res, y: res)
        ctx.translateBy(x: -x0, y: -y0)
        ctx.setFillColor(gray: 1, alpha: 1)
        ctx.setStrokeColor(gray: 1, alpha: 1)
        ctx.setLineCap(.round)
        ctx.setLineJoin(.round)
        for item in items {
            switch item {
            case let .circle(x, y, r):
                ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
            case let .ellipse(x, y, rx, ry):
                ctx.fillEllipse(in: CGRect(x: x - rx, y: y - ry, width: 2 * rx, height: 2 * ry))
            case let .line(ps, width):
                ctx.setLineWidth(width)
                ctx.addLines(between: ps)
                ctx.strokePath()
            }
        }
        guard let data = ctx.data?.assumingMemoryBound(to: UInt8.self) else { return path }
        var field = (0..<(w * h)).map { Float(data[$0]) / 255 }
        let box = max(1, Int((sqrt(4 * sigma * res * sigma * res + 1) - 1) / 2 + 0.5))
        blur(&field, w, h, box)
        for x in 0..<w {
            field[x] = 0
            field[(h - 1) * w + x] = 0
        }
        for y in 0..<h {
            field[y * w] = 0
            field[y * w + w - 1] = 0
        }
        let level: Float = 0.45
        var links: [Int: [Int]] = [:]
        func link(_ a: Int, _ b: Int) {
            links[a, default: []].append(b)
            links[b, default: []].append(a)
        }
        for r in 0..<(h - 1) {
            for c in 0..<(w - 1) {
                let tl = field[r * w + c]
                let tr = field[r * w + c + 1]
                let br = field[(r + 1) * w + c + 1]
                let bl = field[(r + 1) * w + c]
                let index = (tl > level ? 1 : 0) | (tr > level ? 2 : 0) | (br > level ? 4 : 0) | (bl > level ? 8 : 0)
                if index == 0 || index == 15 { continue }
                let cell = (r * w + c) * 2
                let top = cell
                let bottom = ((r + 1) * w + c) * 2
                let leftEdge = cell + 1
                let rightEdge = (r * w + c + 1) * 2 + 1
                let centre = (tl + tr + br + bl) / 4 > level
                switch index {
                case 1, 14: link(leftEdge, top)
                case 2, 13: link(top, rightEdge)
                case 3, 12: link(leftEdge, rightEdge)
                case 4, 11: link(rightEdge, bottom)
                case 6, 9: link(top, bottom)
                case 7, 8: link(leftEdge, bottom)
                case 5:
                    if centre { link(top, rightEdge); link(leftEdge, bottom) } else { link(leftEdge, top); link(rightEdge, bottom) }
                default:
                    if centre { link(leftEdge, top); link(rightEdge, bottom) } else { link(top, rightEdge); link(leftEdge, bottom) }
                }
            }
        }
        func point(_ id: Int) -> CGPoint {
            let cell = id / 2
            let c = cell % w
            let r = cell / w
            var px = Double(c)
            var py = Double(r)
            if id % 2 == 0 {
                let f0 = field[r * w + c]
                let f1 = field[r * w + c + 1]
                px += Double((level - f0) / (f1 - f0))
            } else {
                let f0 = field[r * w + c]
                let f1 = field[(r + 1) * w + c]
                py += Double((level - f0) / (f1 - f0))
            }
            return CGPoint(x: x0 + (px + 0.5) / res, y: y0 + (py + 0.5) / res)
        }
        var seen = Set<Int>()
        for start in links.keys.sorted() where !seen.contains(start) {
            var loop: [CGPoint] = []
            var current = start
            var previous = -1
            while true {
                loop.append(point(current))
                seen.insert(current)
                guard let next = links[current]?.first(where: { $0 != previous && !seen.contains($0) }) else { break }
                previous = current
                current = next
            }
            if loop.count > 2 {
                path.addLines(between: loop)
                path.closeSubpath()
            }
        }
        return path
    }

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

    static func keys(_ t: Double, _ ks: Keys) -> 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 bob(_ t: Double) -> (Double, Double) {
        var env = 1 - clamp((t - 0.38) / 0.1) + clamp((t - 2.82) / 0.35)
        env = min(env, 1)
        let w = 2 * Double.pi * t / duration * 3
        return (1.2 * sin(w) * env, 3 * sin(w + 1) * env)
    }

    static func kick(_ t: Double) -> (Double, Double) {
        let env = clamp((t - 1.12) / 0.08) * (1 - clamp((t - 2.35) / 0.08))
        return (2 * Double.pi * (t - 1.12) / 0.3, env)
    }

    static func bump(_ x: Double, _ t: Double, _ t0: Double, _ a: Double, _ v: Double, _ w: Double) -> Double {
        let u = t - t0
        if u < 0 || u > 0.9 { return 0 }
        let k = a * pow(1 - u / 0.9, 2)
        var h = 0.0
        for c in [ex - v * u, ex + v * u] {
            h += exp(-pow((x - c) / w, 2))
        }
        return k * h
    }

    static func wave(_ x: Double, _ t: Double, _ t0: Double, _ a: Double) -> Double {
        let u = t - t0
        if u <= 0 || u > 1.5 { return 0 }
        let d = abs(x - ex)
        let f = 8 + 26 * u
        let w = 7 + 9 * u
        let env = exp(-pow((d - f) / w, 2)) * pow(1 - u / 1.5, 1.5) * clamp(d / 6)
        return a * env * cos(2 * Double.pi * (d - f) / 11)
    }

    static func surf(_ x: Double, _ t: Double) -> Double {
        var y = wy + 1.0 * sin(x * 0.11 + 2 * Double.pi * t / duration * 2)
        y -= bump(x, t, te, 4.5, 34, 6) - bump(x, t, te + 0.16, 2.2, 30, 5)
        y -= bump(x, t, tp, 2.0, 30, 6)
        y -= wave(x, t, te + 0.08, 3.6) + wave(x, t, te + 0.45, 2.0) + wave(x, t, tp + 0.05, 1.6)
        return y
    }

    static func splash(_ t: Double, _ t0: Double, _ big: Double, cols: Bool) -> [DabbleItem] {
        var items: [DabbleItem] = []
        for (vx, vy, r, dl) in drops {
            let u = t - t0 - dl
            if u > 0 && u < 1 {
                let x = ex + vx * big * u
                let y = wy - 2 - vy * big * u + 0.5 * 430 * u * u
                let radius = r * (0.6 + 0.4 * big) * (1 - 0.5 * clamp(u))
                if y < wy + 3 && radius > 0.15 { items.append(.circle(x, y, radius)) }
            }
        }
        if cols {
            for (side, tilt, hh, ww) in [(-1.0, 34.0, 20.0, 5.5), (1.0, 30.0, 24.0, 6.0), (1.0, 58.0, 14.0, 4.5)] {
                let u = (t - t0) / 0.46
                if u > 0 && u < 1 {
                    let h = hh * big * pow(sin(.pi * u), 0.7)
                    let w = ww * big * (1 - 0.35 * u)
                    let a = (tilt + 12 * u) * .pi / 180
                    let x0 = ex + side * (7 + 8 * u)
                    let x1 = x0 + side * h * sin(a)
                    let y1 = wy + 1 - h * cos(a)
                    items.append(.line([CGPoint(x: x0, y: wy + 2), CGPoint(x: x1, y: y1)], w))
                    if w * 0.7 > 0.15 { items.append(.circle(x1, y1 - 1, w * 0.7)) }
                }
            }
        }
        return items
    }

    static func frame(_ index: Int) -> DabbleFrame {
        let t = Double(index) * duration / Double(count)

        let xs = (0...60).map { Double($0) * 2 }
        let tops = xs.map { CGPoint(x: $0, y: surf($0, t)) }
        let waterPath = CGMutablePath()
        waterPath.move(to: CGPoint(x: 0, y: 130))
        for p in tops { waterPath.addLine(to: p) }
        waterPath.addLine(to: CGPoint(x: 120, y: 130))
        waterPath.closeSubpath()
        let abovePath = CGMutablePath()
        abovePath.move(to: CGPoint(x: 0, y: -20))
        for p in tops { abovePath.addLine(to: p) }
        abovePath.addLine(to: CGPoint(x: 120, y: -20))
        abovePath.closeSubpath()
        var items: [DabbleItem] = [.line(tops, 3.6)]
        items += splash(t, te, 1.0, cols: true) + splash(t, tp, 0.45, cols: false)
        let surface = contour(items, 2.0)

        let (by, br) = bob(t)
        let (ph, env) = kick(t)
        let r = keys(t, rot) + br + 3 * sin(ph) * env
        let l = keys(t, lift) + by + 0.6 * sin(2 * ph) * env
        let s = keys(t, squash)
        let sx = s > 1 ? 1 / sqrt(s) : 2 - s
        var duck = dabbleChain([dabbleMove(dx + keys(t, shift), wy - l), dabbleMove(0, -8), dabbleSpin(r), dabbleMove(0, 8), dabbleScale(sx, s), dabbleScale(1.25, 1.25)])

        func put(_ path: CGPath, _ transform: CGAffineTransform = .identity) -> CGPath {
            var m = transform.concatenating(duck)
            return path.copy(using: &m) ?? path
        }

        let legs = CGMutablePath()
        let footStrokes = CGMutablePath()
        let footInteriors = CGMutablePath()
        for (hx, hy, off) in [(-14.0, 1.5, Double.pi), (-6.0, 3.8, 0.0)] {
            let a = 28 + 38 * sin(ph + off) * env
            let place = dabbleChain([dabbleMove(hx, hy), dabbleSpin(a)])
            var m = place
            if let legPath = leg.copy(strokingWithWidth: 3.2, lineCap: .round, lineJoin: .round, miterLimit: 10).copy(using: &m) { legs.addPath(legPath) }
            if let placedFoot = foot.copy(using: &m) {
                footInteriors.addPath(placedFoot)
                footStrokes.addPath(placedFoot.copy(strokingWithWidth: 3.2, lineCap: .butt, lineJoin: .round, miterLimit: 10))
            }
        }
        let interiorsGlobal = put(footInteriors)
        let footSolid = interiorsGlobal.union(put(footStrokes))
        let legsVisible = put(legs).subtracting(interiorsGlobal)

        let outer = put(outerLocal).subtracting(footSolid).intersection(abovePath)
        let tint = put(body).subtracting(footSolid).intersection(abovePath)
        let footTint = interiorsGlobal.intersection(abovePath)
        var details: CGPath = legsVisible.union(put(footStrokes))
        details = details.union(put(wingStroke)).union(put(eye))
        details = details.intersection(abovePath)

        return DabbleFrame(outer: outer, tint: tint, footTint: footTint, details: details, water: waterPath, surface: surface)
    }
}

extension FlairLayer {
    func buildDabble() {
        let unit = side
        let k = unit / 110
        let steps = DabbleModel.count
        let duration = DabbleModel.duration
        let frames = (0..<steps).map { DabbleModel.frame($0) }
        let map = CGAffineTransform(translationX: 0, y: unit).scaledBy(x: k, y: -k).translatedBy(x: -5, y: -5)
        let base = CATransform3DMakeAffineTransform(map)
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        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

        func layer(_ path: CGPath, opacity: Float = 1) -> CAShapeLayer {
            let part = shape(path, size: full, at: .zero, in: clipper)
            part.anchorPoint = .zero
            part.position = .zero
            part.transform = base
            part.opacity = opacity
            return part
        }

        let outer = layer(frames[0].outer)
        let tint = layer(frames[0].tint, opacity: 0.22)
        let footTint = layer(frames[0].footTint, opacity: 0.22)
        let details = layer(frames[0].details)
        let water = layer(frames[0].water, opacity: 0.12)
        let surface = layer(frames[0].surface)

        guard animating else { return }

        func paths(_ pick: (DabbleFrame) -> CGPath) -> CAKeyframeAnimation {
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", frames.map { pick($0) }, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }

        run(group([paths { $0.outer }], duration: duration), on: outer)
        run(group([paths { $0.tint }], duration: duration), on: tint)
        run(group([paths { $0.footTint }], duration: duration), on: footTint)
        run(group([paths { $0.details }], duration: duration), on: details)
        run(group([paths { $0.water }], duration: duration), on: water)
        run(group([paths { $0.surface }], duration: duration), on: surface)
    }
}
