import QuartzCore
import Foundation

private enum JigsawModel {
    static let duration = 2.6
    static let count = 78
    static let stagger = 0.09
    static let dirs: [(Double, Double)] = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
    static let signs: [Double] = [-1, 1, -1, 1]

    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 eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }
    static func back(_ u: Double) -> Double { let c = clamp(u) - 1; return 1 + 2.7 * c * c * c + 1.7 * c * c }
    static func land(_ i: Int) -> Double { 1.66 + stagger * Double(i) }

    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
    }

    nonisolated(unsafe) static let piece: CGPath = {
        let path = CGMutablePath()
        func arc(_ cx: Double, _ cy: Double, _ r: Double, _ from: Double, _ to: Double) {
            path.addArc(center: CGPoint(x: cx, y: cy), radius: r, startAngle: from, endAngle: to, clockwise: to < from)
        }
        let pi = Double.pi
        path.move(to: CGPoint(x: -30, y: -20))
        arc(-20, -20, 10, pi, 1.5 * pi)
        path.addLine(to: CGPoint(x: -2.5, y: -30))
        arc(-2.5, -27.5, 2.5, 1.5 * pi, 2 * pi)
        path.addLine(to: CGPoint(x: 0, y: -19.5))
        let knobStart = atan2(-4.5, -3.9686)
        arc(3.9686, -15, 6, knobStart + 2 * pi, atan2(4.5, -3.9686) + 2 * pi)
        path.addLine(to: CGPoint(x: 0, y: -2.5))
        arc(-2.5, -2.5, 2.5, 0, 0.5 * pi)
        path.addLine(to: CGPoint(x: -10.5, y: 0))
        let notchStart = atan2(3.9686, 4.5)
        arc(-15, -3.9686, 6, notchStart, atan2(3.9686, -4.5) - 2 * pi)
        path.addLine(to: CGPoint(x: -27.5, y: 0))
        arc(-27.5, -2.5, 2.5, 0.5 * pi, pi)
        path.closeSubpath()
        return path
    }()

    static func global(_ t: Double) -> CGAffineTransform {
        let gu = keys(t, [(0, 1), (0.48, 1), (0.6, 0.9), (0.7, 1.04), (0.8, 1)])
        let tf = land(3)
        let gx = keys(t, [(0, 1), (tf, 1), (tf + 0.06, 1.1), (tf + 0.17, 0.95), (tf + 0.27, 1.03), (tf + 0.37, 0.99), (tf + 0.45, 1)])
        let gy = keys(t, [(0, 1), (tf, 1), (tf + 0.06, 0.88), (tf + 0.17, 1.06), (tf + 0.27, 0.98), (tf + 0.37, 1.01), (tf + 0.45, 1)])
        var m = CGAffineTransform(scaleX: gu, y: gu)
        m = m.concatenating(CGAffineTransform(translationX: 0, y: -30))
        m = m.concatenating(CGAffineTransform(scaleX: gx, y: gy))
        return m.concatenating(CGAffineTransform(translationX: 60, y: 90))
    }

    static func local(_ t: Double, _ i: Int) -> CGAffineTransform {
        let s = stagger * Double(i)
        let d0 = keys(t, [(0, 0), (0.5, 0), (0.6, -1.5), (0.8, 12), (0.95, 10), (1.1, 11), (1.4 + s, 10.5), (1.52 + s, 13.5), (1.66 + s, 0)])
        let r0 = keys(t, [(0, 0), (0.6, 0), (0.85, 16), (1, 11), (1.4 + s, 13), (1.52 + s, 18), (1.66 + s, 0)])
        let st = keys(t, [(0, 1), (0.6, 1), (0.68, 1.14), (0.85, 0.94), (0.98, 1.02), (1.1, 1), (1.52 + s, 1), (1.6 + s, 1.14), (1.66 + s, 1.1), (1.72 + s, 0.86), (1.82 + s, 1.05), (1.92 + s, 1)])
        let env = clamp((t - 0.85) / 0.12) * (1 - clamp((t - 1.38 - s) / 0.1))
        let ph = 2 * Double.pi * (t - 0.85) / 0.55 + Double(i) * 1.6
        let d = d0 + 1.3 * sin(ph) * env
        let r = r0 + 2.5 * sin(ph + 0.8) * env
        let (dx, dy) = dirs[i]
        let ox = dx * d / 2.0.squareRoot()
        let oy = dy * d / 2.0.squareRoot()
        let cx = 15 * dx
        let cy = 15 * dy
        let a = (dx == dy ? 45.0 : -45.0) * Double.pi / 180
        var m = CGAffineTransform(rotationAngle: Double(90 * i) * Double.pi / 180)
        m = m.concatenating(CGAffineTransform(translationX: -cx, y: -cy))
        m = m.concatenating(CGAffineTransform(rotationAngle: -a))
        m = m.concatenating(CGAffineTransform(scaleX: st, y: 1 / st))
        m = m.concatenating(CGAffineTransform(rotationAngle: a))
        m = m.concatenating(CGAffineTransform(rotationAngle: signs[i] * r * Double.pi / 180))
        m = m.concatenating(CGAffineTransform(translationX: cx, y: cy))
        return m.concatenating(CGAffineTransform(translationX: ox, y: oy))
    }

    static func puffs(_ t: Double) -> CGPath {
        let path = CGMutablePath()
        let seams: [((Double, Double), (Double, Double), Double)] = [((0, -31), (0, -1), land(1)), ((31, 0), (1, 0), land(2)), ((0, 31), (0, 1), land(3)), ((-31, 0), (-1, 0), land(3))]
        for ((x0, y0), (nx, ny), t0) in seams {
            let px = -ny
            let py = nx
            for (side, sp, rr, dl) in [(-1.0, 9.0, 3.4, 0.0), (1.0, 9.0, 3.4, 0.0), (0.0, 0.0, 2.8, 0.03)] {
                let u = (t - t0 - dl) / 0.4
                guard u > 0 && u < 1 else { continue }
                let e = eout(u)
                let out = side != 0 ? 7.0 : 13.0
                let x = 60 + x0 + (nx * out + px * side * sp) * e
                let y = 60 + y0 + (ny * out + py * side * sp) * e
                let r = rr * back(u / 0.3) * (1 - ease((u - 0.45) / 0.55))
                if r > 0.15 { path.addEllipse(in: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2)) }
            }
        }
        return path
    }
}

extension FlairLayer {
    func buildJigsaw() {
        let unit = side
        let k = unit / 110
        let duration = JigsawModel.duration
        let steps = JigsawModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        let unmap = map.inverted()
        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 origin = CGPoint(x: 0, y: 0).applying(map)
        let shapePath = placed(JigsawModel.piece)

        func place(_ a: CGAffineTransform) -> (CGPoint, NSValue) {
            let layerA = unmap.concatenating(a).concatenating(map)
            let linear = CGAffineTransform(a: layerA.a, b: layerA.b, c: layerA.c, d: layerA.d, tx: 0, ty: 0)
            return (origin.applying(layerA), NSValue(caTransform3D: CATransform3DMakeAffineTransform(linear)))
        }
        func total(_ t: Double, _ i: Int) -> CGAffineTransform {
            JigsawModel.local(t, i).concatenating(JigsawModel.global(t))
        }

        var holders: [CALayer] = []
        for i in 0..<4 {
            let holder = container()
            holder.bounds = CGRect(origin: .zero, size: full)
            holder.anchorPoint = CGPoint(x: origin.x / unit, y: origin.y / unit)
            let start = place(total(0, i))
            holder.position = start.0
            holder.transform = start.1.caTransform3DValue
            let fill = shape(shapePath, size: full, at: mid, in: holder)
            fill.opacity = i % 2 == 0 ? 1 : 0.22
            let edge = shape(shapePath, size: full, at: mid, stroke: 3.5 * k, in: holder)
            edge.lineJoin = .round
            holders.append(holder)
        }
        let dust = shape(placed(JigsawModel.puffs(0)), size: full, at: mid)

        guard animating else { return }
        let stepTimes = (0...steps).map { Double($0) * duration / Double(steps) }
        for (i, holder) in holders.enumerated() {
            let moves = keyframes("position", stepTimes.map { flairPoint(place(total($0, i)).0) }, timing: .linear)
            let turns = keyframes("transform", stepTimes.map { place(total($0, i)).1 }, timing: .linear)
            run(group([moves, turns], duration: duration), on: holder)
        }
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        let frames = (0..<steps).map { placed(JigsawModel.puffs(Double($0) * duration / Double(steps))) }
        let animation = keyframes("path", frames, times: times, timing: .linear)
        animation.calculationMode = .discrete
        run(group([animation], duration: duration), on: dust)
    }
}
