import QuartzCore
import Foundation

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

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

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

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

private func avocadoEllipse(_ cx: Double, _ cy: Double, _ rx: Double, _ ry: Double, turn: Double = 0) -> CGPath {
    var place = avocadoChain([avocadoMove(cx, cy), CGAffineTransform(rotationAngle: turn)])
    return CGPath(ellipseIn: CGRect(x: -rx, y: -ry, width: rx * 2, height: ry * 2), transform: &place)
}

private struct AvocadoFrame {
    let stem: CGPath
    let leaves: CGPath
    let whole: CGPath
    let wholeMatrix: CGAffineTransform
    let pitMatrix: CGAffineTransform
    let halfLeft: CGAffineTransform
    let halfRight: CGAffineTransform
    let puffs: CGPath
}

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

    static let duration = 4.6
    static let count = 138
    static let floorY = 88.0
    static let height = 40.0
    static let pitRX = 9.0
    static let pitRY = 9.7
    static let pitY = floorY - pitRY
    static let top = floorY - height
    static let hang = 0.75
    static let detach = 2.31
    static let land = 2.62
    static let cutStart = 3.05
    static let cutEnd = 3.17
    static let popStart = 3.74
    static let popEnd = 4.04
    static let hidden = CGAffineTransform(scaleX: 0.0005, y: 0.0005)

    static let squeeze: Keys = [(0, 0), (0.45, 0), (0.7, 1), (0.78, 1), (0.86, -0.3), (0.96, 0.08), (1.05, 0)]
    static let wiggle: Keys = [(0, 0), (0.12, 0), (0.2, -5), (0.28, 5), (0.36, -2.5), (0.44, 0)]
    static let pitShrink: Keys = [(0, 1), (2.5, 1), (2.62, 1.15), (2.8, 0)]
    static let grow: Keys = [(0, 0), (0.76, 0), (1.06, 1.1), (1.16, 0.95), (1.26, 1.0), (2.36, 1.0), (2.7, 0.0)]
    static let leafGrow: Keys = [(0, 0), (0.92, 0), (1.08, 1.3), (1.18, 0.88), (1.28, 1.05), (1.36, 1.0), (2.3, 1.0), (2.55, 0.0)]
    static let sway: Keys = [(0, 0), (1.0, 0), (1.12, 8), (1.26, -5), (1.4, 2), (1.5, 0), (1.95, 0), (2.2, 14), (2.31, -16), (2.44, 6), (2.56, 0)]
    static let fruitGrow: Keys = [(0, 0), (1.3, 0), (1.78, 1.12), (1.9, 0.95), (2.0, 1.0)]
    static let landSquash: Keys = [(0, 0), (land, 0), (land + 0.06, 0.55), (land + 0.16, -0.18), (land + 0.26, 0.06), (land + 0.34, 0)]
    static let split: Keys = [(0, 0), (cutEnd, 0), (3.36, 1.08), (3.46, 0.97), (3.54, 1.0)]
    static let halfShrink: Keys = [(0, 1), (3.78, 1), (3.82, 1.08), (4.02, 0)]
    static let popSquash: Keys = [(0, 0), (popEnd, 0), (popEnd + 0.06, 0.5), (popEnd + 0.16, -0.2), (popEnd + 0.26, 0.06), (popEnd + 0.34, 0)]

    static let ys: [Double] = (0...60).map { height * (1 - cos(.pi * Double($0) / 60)) / 2 }

    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 easeOut(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }
    static func easeIn(_ u: Double) -> Double { clamp(u) * clamp(u) }

    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 width(_ y: Double) -> Double {
        let c = max(-1, min(1, 1 - 2 * y / height))
        return 14.5 * sqrt(1 - c * c) * (1 - 0.36 * c) * (1 + 0.12 * (1 - c * c))
    }

    static func avocado(_ k: Double = 1, cy: Double = 25) -> CGPath {
        let right = ys.map { (width($0), $0) }
        let all = right + right.reversed().map { (-$0.0, $0.1) }
        let path = CGMutablePath()
        path.addLines(between: all.map { CGPoint(x: $0.0 * k, y: cy + ($0.1 - cy) * k) })
        path.closeSubpath()
        return path
    }

    static func expanded(_ path: CGPath, by amount: Double) -> CGPath {
        path.union(path.copy(strokingWithWidth: amount, lineCap: .butt, lineJoin: .round, miterLimit: 10))
    }

    nonisolated(unsafe) static let solid = expanded(avocado(), by: 3)
    nonisolated(unsafe) static let inner = avocado(0.8)
    nonisolated(unsafe) static let ringShape = solid.subtracting(inner)
    nonisolated(unsafe) static let socket = avocadoEllipse(0, 25, pitRX + 0.5, pitRY + 0.5)
    nonisolated(unsafe) static let tintLeft = inner
    nonisolated(unsafe) static let tintRight = inner.subtracting(socket)
    nonisolated(unsafe) static let pitShape = avocadoEllipse(0, 0, pitRX + 1, pitRY + 1)

    static func stemPoints(_ t: Double) -> [CGPoint]? {
        let g = keys(t, grow)
        if g < 0.02 { return nil }
        let length = 76.0 * g
        let c = 1 - clamp(g)
        let swing = keys(t, sway) * .pi / 180
        var x = 60.0
        var y = pitY - 2
        var points = [CGPoint(x: x, y: y)]
        let n = 36
        for i in 1...n {
            let f = Double(i) / Double(n)
            let angle = (-90 - 10 * (1 - c) + 8 * sin(2 * .pi * f) + (215 + 180 * c) * pow(f, 3)) * .pi / 180 + swing * (0.3 + f)
            x += length / Double(n) * cos(angle)
            y += length / Double(n) * sin(angle)
            points.append(CGPoint(x: x, y: y))
        }
        return points
    }

    nonisolated(unsafe) static let tip: CGPoint = stemPoints(detach)!.last!

    static func life(_ t: Double, _ t0: Double, _ duration: Double, _ rmax: Double) -> Double {
        let u = (t - t0) / duration
        if u <= 0 || u >= 1 { return 0 }
        return rmax * pow(sin(.pi * pow(u, 0.6)), 1.2)
    }

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

        var stem: CGPath = CGMutablePath()
        if let points {
            let line = CGMutablePath()
            line.addLines(between: points)
            stem = line.copy(strokingWithWidth: 4, lineCap: .round, lineJoin: .round, miterLimit: 10)
        }

        var leafPath: CGPath = CGMutablePath()
        if let points {
            let leaves = CGMutablePath()
            for (f, angle, k, d) in [(0.32, -112.0, 1.0, 0.0), (0.12, -150.0, 0.85, 0.08)] {
                let node = points[Int(Double(points.count) * f)]
                let sk = keys(t - d, leafGrow) * k
                if sk < 0.03 { continue }
                let a = angle + 30 * (1 - min(sk / k, 1)) + keys(t, sway) * 0.5
                let r = a * .pi / 180
                let cx = node.x + 9 * sk * cos(r)
                let cy = node.y + 9 * sk * sin(r)
                leaves.addPath(avocadoEllipse(cx, cy, 9.5 * sk + 1.5, 5.5 * sk + 1.5, turn: r))
            }
            leafPath = leaves
        }

        var whole: CGPath = CGMutablePath()
        var wholeMatrix = hidden
        var halves: [CGAffineTransform] = [hidden, hidden]

        if t >= 1.3 {
            if t < detach {
                let s = keys(t, fruitGrow) * hang
                if s >= 0.03, let points {
                    let tip = points[points.count - 1]
                    wholeMatrix = avocadoChain([avocadoMove(tip.x, tip.y - 1), avocadoSpin(keys(t, sway) * 0.6), avocadoScale(s, s)])
                    whole = solid
                    var place = wholeMatrix
                    if let shape = avocado().copy(using: &place) {
                        let halo = expanded(shape, by: 3 * s + 5 / max(s, 0.1) * s)
                        leafPath = leafPath.subtracting(halo)
                        stem = stem.subtracting(halo)
                    }
                }
            } else if t < cutEnd + 0.02 {
                let u = clamp((t - detach) / (land - detach))
                let x = tip.x + (60 - tip.x) * u
                let y0 = tip.y - 1 + (top - (tip.y - 1)) * easeIn(u) - 10 * sin(.pi * u) * (1 - u)
                let s = hang + (1 - hang) * easeOut(u)
                let rotation = keys(detach, sway) * 0.6 * (1 - u) - 12 * sin(.pi * u)
                let q = keys(t, landSquash)
                wholeMatrix = avocadoChain([avocadoMove(x, y0), avocadoSpin(rotation, 0, height / 2), avocadoMove(0, height), avocadoScale((1 + 0.22 * q) * s, (1 - 0.22 * q) * s), avocadoMove(0, -height)])
                whole = solid
                if t >= cutStart {
                    let v = easeOut((t - cutStart) / (cutEnd - cutStart))
                    let cut = CGMutablePath()
                    cut.move(to: CGPoint(x: 0, y: -2))
                    cut.addLine(to: CGPoint(x: 0, y: -2 + (height + 2) * v))
                    whole = solid.subtracting(cut.copy(strokingWithWidth: 3, lineCap: .round, lineJoin: .round, miterLimit: 10))
                }
            } else {
                let o = keys(t, split)
                let sh = keys(t, halfShrink)
                if sh >= 0.02 {
                    for (slot, side) in [-1.0, 1.0].enumerated() {
                        let cx = 60 + side * (7 + 17 * o)
                        let sx = (0.5 + 0.5 * o) * sh
                        let sy = (1 + 0.1 * (1 - min(o, 1)) * (o > 0 ? 1 : 0)) * sh
                        let rotation = side * 8 * sin(.pi * clamp(o))
                        halves[slot] = avocadoChain([avocadoMove(cx, top), avocadoSpin(rotation, 0, height), avocadoMove(0, 25), avocadoScale(sx, sy), avocadoMove(0, -25)])
                    }
                }
            }
        }

        var pit = hidden
        if t < cutEnd {
            let q = keys(t, squeeze)
            let s = keys(t, pitShrink)
            if s >= 0.02 {
                pit = avocadoChain([avocadoMove(60, pitY), avocadoSpin(keys(t, wiggle), 0, -6), avocadoMove(0, pitRY), avocadoScale((1 + 0.24 * q) * s, (1 - 0.22 * q) * s), avocadoMove(0, -pitRY)])
            }
        } else {
            let o = keys(t, split)
            let hx = 60 - (7 + 17 * o)
            let hy = top + 25
            if t < popStart {
                let sx = 0.5 + 0.5 * o
                let rotation = -8 * sin(.pi * clamp(o))
                pit = avocadoChain([avocadoMove(hx, top), avocadoSpin(rotation, 0, height), avocadoMove(0, 25), avocadoScale(sx, 1), avocadoMove(0, -25), avocadoMove(0, 25)])
            } else {
                let u = clamp((t - popStart) / (popEnd - popStart))
                let x = hx + (60 - hx) * u
                let y = hy + (pitY - hy) * u - 22 * sin(.pi * u)
                let q = keys(t, popSquash)
                pit = avocadoChain([avocadoMove(x, y), avocadoMove(0, pitRY), avocadoScale(1 + 0.24 * q, 1 - 0.22 * q), avocadoMove(0, -pitRY), avocadoSpin(-200 * easeOut(u))])
            }
        }

        let puffs = CGMutablePath()
        for side in [-1.0, 1.0] {
            for (t0, rr) in [(0.78, 4.0), (land, 4.2), (popEnd, 3.4)] {
                let u = clamp((t - t0) / 0.36)
                let a = life(t, t0, 0.38, rr)
                if a > 0.05 {
                    puffs.addEllipse(in: CGRect(x: 60 + side * (11 + 12 * easeOut(u)) - a, y: floorY - 3 - 5 * easeOut(u) - a, width: a * 2, height: a * 2))
                }
                let b = life(t, t0 + 0.03, 0.32, rr * 0.62)
                if b > 0.05 {
                    puffs.addEllipse(in: CGRect(x: 60 + side * (7 + 7 * easeOut(u)) - b, y: floorY - 8 - 8 * easeOut(u) - b, width: b * 2, height: b * 2))
                }
            }
        }

        return AvocadoFrame(stem: stem, leaves: leafPath, whole: whole, wholeMatrix: wholeMatrix, pitMatrix: pit, halfLeft: halves[0], halfRight: halves[1], puffs: puffs)
    }
}

extension FlairLayer {
    func buildAvocado() {
        let unit = side
        let k = unit / 110
        let steps = AvocadoModel.count
        let duration = AvocadoModel.duration
        let frames = (0..<steps).map { AvocadoModel.frame($0) }
        let map = avocadoChain([avocadoMove(0, unit), avocadoScale(k, -k), avocadoMove(-5, -5), avocadoMove(60, 60), avocadoScale(1.1, 1.1), avocadoMove(-60, -58)])
        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, stroke: CGFloat = 0, opacity: Float = 1) -> CAShapeLayer {
            let part = shape(path, size: full, at: .zero, stroke: stroke, in: clipper)
            part.anchorPoint = .zero
            part.position = .zero
            part.transform = base
            part.opacity = opacity
            if stroke > 0 {
                part.lineCap = .round
                part.lineJoin = .round
            }
            return part
        }

        func matrix(_ m: CGAffineTransform) -> CATransform3D {
            CATransform3DMakeAffineTransform(map.isIdentity ? m : avocadoChain([map, m]))
        }

        let pit = layer(AvocadoModel.pitShape)
        let leaves = layer(frames[0].leaves)
        let whole = layer(frames[0].whole)
        let ringLeft = layer(AvocadoModel.ringShape)
        let tintLeft = layer(AvocadoModel.tintLeft, opacity: 0.3)
        let ringRight = layer(AvocadoModel.ringShape)
        let tintRight = layer(AvocadoModel.tintRight, opacity: 0.3)
        let stem = layer(frames[0].stem)
        let puffs = layer(frames[0].puffs)

        pit.transform = matrix(frames[0].pitMatrix)
        whole.transform = matrix(frames[0].wholeMatrix)
        for part in [ringLeft, tintLeft] { part.transform = matrix(frames[0].halfLeft) }
        for part in [ringRight, tintRight] { part.transform = matrix(frames[0].halfRight) }

        guard animating else { return }

        func paths(_ pick: (AvocadoFrame) -> 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
        }

        func moves(_ pick: (AvocadoFrame) -> CGAffineTransform) -> CAKeyframeAnimation {
            var values = frames.map { NSValue(caTransform3D: matrix(pick($0))) }
            values.append(values[0])
            let times = (0...steps).map { NSNumber(value: Double($0) / Double(steps)) }
            return keyframes("transform", values, times: times, timing: .linear)
        }

        run(group([paths { $0.leaves }], duration: duration), on: leaves)
        run(group([paths { $0.stem }], duration: duration), on: stem)
        run(group([paths { $0.puffs }], duration: duration), on: puffs)
        run(group([paths { $0.whole }, moves { $0.wholeMatrix }], duration: duration), on: whole)
        run(group([moves { $0.pitMatrix }], duration: duration), on: pit)
        for part in [ringLeft, tintLeft] { run(group([moves { $0.halfLeft }], duration: duration), on: part) }
        for part in [ringRight, tintRight] { run(group([moves { $0.halfRight }], duration: duration), on: part) }
    }
}
