import QuartzCore
import Foundation

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

private struct StampFrame {
    let ink: CGPath
    let sticky: CGPath
}

private struct StampPose {
    let body: CGAffineTransform
    let oldPaper: CGAffineTransform
    let newPaper: CGAffineTransform
}

private enum StampModel {
    static let fps = 60.0
    static let duration = 2.2
    static let goo = 66
    static let count = 132
    static let mx = 62.0
    static let my = 89.0
    static let hover = 58.0
    static let rx = 22.0
    static let ry = 7.0
    static let ct = 0.9
    static let lt = 1.32

    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 ein(_ u: Double) -> Double { pow(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 oy(_ t: Double) -> Double {
        if t < 0.8 {
            return keys(t, [(0, hover), (0.5, hover), (0.58, hover + 2), (0.8, hover - 5)]) + 1.2 * sin(2 * .pi * t / 1.1) * (1 - clamp(t / 0.5))
        }
        if t < ct {
            let u = (t - 0.8) / (ct - 0.8)
            return hover - 5 + (my - hover + 10) * u * u
        }
        if t < lt { return my }
        if t < 1.5 { return my + (hover - 3 - my) * eout((t - lt) / 0.18) }
        return keys(t, [(1.5, hover - 3), (1.72, hover + 1), (1.9, hover)]) + 1.2 * sin(2 * .pi * (t - 1.9) / 1.1) * clamp((t - 1.9) / 0.3)
    }

    static func sy(_ t: Double) -> Double {
        keys(t, [(0, 1), (0.5, 1), (0.58, 0.92), (0.78, 1.1), (0.84, 1.06), (0.89, 1.2), (ct, 1.2), (0.95, 0.66), (1.03, 1.1), (1.11, 0.95), (1.19, 1.02), (1.24, 1), (lt, 1.16), (1.4, 0.9), (1.5, 1.05), (1.6, 0.98), (1.68, 1)])
    }

    static func tilt(_ t: Double) -> Double {
        keys(t, [(0, 0), (0.5, 0), (0.62, 3), (0.8, -5), (0.88, 0), (1.42, 0), (1.52, 4), (1.66, -2), (1.8, 0)])
    }

    static func paperDy(_ t: Double) -> Double {
        keys(t, [(ct, 0), (0.94, 1.8), (1.02, -0.6), (1.1, 0.3), (1.18, 0)])
    }

    static func markScale(_ t: Double) -> Double {
        if t < ct { return 0 }
        return 0.82 + 0.4 * back((t - ct) / 0.16) - 0.1 * ease((t - ct - 0.16) / 0.2)
    }

    static func envOut(_ t: Double) -> (Double, Double) {
        let u = (t - 1.5) / 0.3
        return (120 * ein(u), -9 * sin(.pi * clamp(u)) - 6 * clamp(u))
    }

    static func envIn(_ t: Double) -> (Double, Double) {
        let u = (t - 1.76) / 0.32
        let x = -120 * (1 - eout(u))
        let k = keys(t, [(1.76, -8), (2.0, -8), (2.08, 7), (2.15, -2.5), (2.2, 0)])
        return (x, k)
    }

    static func envTf(_ x: Double, _ k: Double) -> CGAffineTransform {
        let skew = CGAffineTransform(a: 1, b: 0, c: tan(k * .pi / 180), d: 1, tx: 0, ty: 0)
        return CGAffineTransform(translationX: -62, y: -106).concatenating(skew).concatenating(CGAffineTransform(translationX: 62 + x, y: 106))
    }

    static func pose(_ t: Double) -> StampPose {
        let s = sy(t)
        let sx = pow(s, -0.75)
        let body = CGAffineTransform(scaleX: 0.86 * sx, y: 0.86 * s)
            .concatenating(CGAffineTransform(rotationAngle: tilt(t) * .pi / 180))
            .concatenating(CGAffineTransform(translationX: mx, y: oy(t)))
        let pd = paperDy(t)
        let (ox, ok) = t >= 1.5 ? envOut(t) : (0, 0)
        let old = envTf(ox, ok).concatenating(CGAffineTransform(translationX: 0, y: pd))
        let (nx, nk) = envIn(t)
        return StampPose(body: body, oldPaper: old, newPaper: envTf(nx, nk))
    }

    static func ring(_ cx: Double, _ cy: Double, _ rx: Double, _ ry: Double) -> [CGPoint] {
        (0..<48).map { i in
            let a = 2 * Double.pi * Double(i) / 48
            return CGPoint(x: cx + rx * cos(a), y: cy + ry * sin(a))
        }
    }

    static func inkItems(_ t: Double) -> [StampItem] {
        var items: [StampItem] = []
        let pd = paperDy(t)
        let (ox, ok) = t >= 1.5 ? envOut(t) : (0, 0)
        let m = envTf(ox, ok).concatenating(CGAffineTransform(translationX: 0, y: pd))
        let k = markScale(t)
        if k > 0.03 {
            let w = 3.2 * min(1, k + 0.2)
            var ringPts = ring(mx, my, rx * k, ry * k).map { $0.applying(m) }
            ringPts.append(ringPts[0])
            items.append(.line(ringPts, w))
            items.append(.polygon(ring(mx, my, 7.5 * k, 2.6 * k).map { $0.applying(m) }))
        }
        for (side, dl, vx, vy, r) in [(-1.0, 0.0, 12.0, 30.0, 2.8), (1.0, 0.03, 9.0, 33.0, 2.4)] {
            let u = t - ct - 0.02 - dl
            if u <= 0 || u > 0.5 { continue }
            let x = mx + side * (24 + vx * u)
            let y = my - 1 - vy * 9 * u + 0.5 * 1500 * u * u
            if y > my + 1 && u > 0.1 { continue }
            let rr = r * (0.6 + 0.4 * back(u / 0.08))
            if rr > 0.2 {
                let p = CGPoint(x: x, y: y).applying(m)
                items.append(.circle(Double(p.x), Double(p.y), rr))
            }
        }
        return items
    }

    static func stickyItems(_ t: Double) -> [StampItem] {
        var items: [StampItem] = []
        let y0 = oy(t)
        if t < lt || y0 >= my - 0.3 { return items }
        let pd = paperDy(t)
        let s = sy(t)
        let sx = pow(s, -0.75)
        func add(_ x: Double, _ y: Double, _ r: Double) { if r > 0.2 { items.append(.circle(x, y + pd, r)) } }
        for (x0, w, dl) in [(-13.0, 1.2, 0.0), (1.0, 1.6, 0.03), (14.0, 1.0, -0.02)] {
            let brk = 1.43 + dl
            let top = y0 + 5.6 * s
            let len = my - top
            if len <= 0 { continue }
            let xa = mx + 0.86 * x0 * sx
            let xb = mx + x0 * 0.9
            if t < brk {
                let n = Int(len) + 2
                for i in 0...n {
                    let f = Double(i) / Double(n)
                    let th = sin(.pi * f)
                    let r = w * (2.4 - 1.6 * th * clamp((t - lt) / (brk - lt) + 0.3))
                    add(xa + (xb - xa) * f, top + len * f, r)
                }
            } else {
                let v = ease((t - brk) / 0.1)
                let la = len * 0.4 * (1 - v)
                let na = Int(la) + 1
                for i in 0...na {
                    let f = Double(i) / Double(na)
                    add(xa, top + la * f, w * (2.2 - 1.2 * f) * (1 - 0.5 * v))
                }
                let lb = len * 0.45 * (1 - v)
                let nb = Int(lb) + 1
                for i in 0...nb {
                    let f = Double(i) / Double(nb)
                    add(xb, my - lb * f, w * (2.4 - 1.2 * f) * (1 - 0.6 * v))
                }
            }
        }
        return items
    }

    nonisolated(unsafe) static let frames: [StampFrame] = (0..<goo).map { i in
        let t = Double(i) * duration / Double(goo)
        return StampFrame(ink: contour(inkItems(t), 2.0), sticky: contour(stickyItems(t), 2.0))
    }

    nonisolated(unsafe) static let poses: [StampPose] = (0..<count).map { pose(Double($0) * duration / Double(count)) }

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

    nonisolated(unsafe) static let body: CGPath = {
        let base = CGMutablePath()
        base.addRect(CGRect(x: -22, y: -12, width: 44, height: 12))
        base.addPath(ellipsePath(0, 0, 22, 7))
        base.addPath(ellipsePath(0, -12, 22, 7))
        let flat = base.union(base)
        let arc = CGMutablePath()
        arc.addArc(center: .zero, radius: 1, startAngle: 0.3, endAngle: .pi - 0.3, clockwise: false, transform: CGAffineTransform(a: 22, b: 0, c: 0, d: 7, tx: 0, ty: -12))
        let rim = arc.copy(strokingWithWidth: 2.4, lineCap: .round, lineJoin: .round, miterLimit: 10)
        let cut = flat.subtracting(rim)
        let handle = CGPath(roundedRect: CGRect(x: -4.5, y: -33, width: 9, height: 23), cornerWidth: 3, cornerHeight: 3, transform: nil)
        return cut.union(handle).union(ellipsePath(0, -38, 11, 11))
    }()

    nonisolated(unsafe) static let paper: CGPath = {
        let p = CGMutablePath()
        p.move(to: CGPoint(x: 38, y: 74))
        p.addLine(to: CGPoint(x: 102, y: 74))
        p.addQuadCurve(to: CGPoint(x: 106, y: 80), control: CGPoint(x: 108, y: 74))
        p.addLine(to: CGPoint(x: 96, y: 100))
        p.addQuadCurve(to: CGPoint(x: 88, y: 106), control: CGPoint(x: 94, y: 106))
        p.addLine(to: CGPoint(x: 24, y: 106))
        p.addQuadCurve(to: CGPoint(x: 20, y: 100), control: CGPoint(x: 18, y: 106))
        p.addLine(to: CGPoint(x: 30, y: 80))
        p.addQuadCurve(to: CGPoint(x: 38, y: 74), control: CGPoint(x: 32, y: 74))
        p.closeSubpath()
        return p
    }()

    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: [StampItem], _ 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) }
            case let .polygon(ps): ps.forEach { grow(Double($0.x), Double($0.y), 0) }
            }
        }
        let pad = sigma * 3.5 + 1
        let x0 = max(minX - pad, -20)
        let y0 = max(minY - pad, -20)
        let x1 = min(maxX + pad, 140)
        let y1 = min(maxY + pad, 140)
        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, angle):
                ctx.saveGState()
                ctx.translateBy(x: x, y: y)
                ctx.rotate(by: angle * .pi / 180)
                ctx.fillEllipse(in: CGRect(x: -rx, y: -ry, width: 2 * rx, height: 2 * ry))
                ctx.restoreGState()
            case let .polygon(ps):
                ctx.addLines(between: ps)
                ctx.closePath()
                ctx.fillPath()
            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
    }
}

extension FlairLayer {
    func buildStamp() {
        let unit = side
        let k = unit / 110
        let frames = StampModel.frames
        let poses = StampModel.poses
        let duration = StampModel.duration
        let flip = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        let unflip = flip.inverted()
        func screen(_ path: CGPath) -> CGPath {
            var m = flip
            return path.copy(using: &m) ?? path
        }
        func place(_ t: CGAffineTransform) -> CATransform3D {
            CATransform3DMakeAffineTransform(unflip.concatenating(t).concatenating(flip))
        }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func holder(in parent: CALayer, _ t: CGAffineTransform) -> CALayer {
            let layer = container()
            layer.removeFromSuperlayer()
            parent.addSublayer(layer)
            layer.bounds = CGRect(origin: .zero, size: full)
            layer.anchorPoint = .zero
            layer.position = .zero
            layer.transform = place(t)
            return layer
        }
        func moves(_ pick: @escaping (StampPose) -> CGAffineTransform) -> CAKeyframeAnimation {
            let times = (0..<poses.count).map { NSNumber(value: Double($0) / Double(poses.count)) }
            let values = poses.map { NSValue(caTransform3D: place(pick($0))) }
            let animation = keyframes("transform", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func paths(_ pick: @escaping (StampFrame) -> CGPath) -> CAKeyframeAnimation {
            let times = (0..<frames.count).map { NSNumber(value: Double($0) / Double(frames.count)) }
            let animation = keyframes("path", frames.map { screen(pick($0)) }, 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 paperPath = screen(StampModel.paper)
        let oldHolder = holder(in: clipper, poses[0].oldPaper)
        shape(paperPath, size: full, at: mid, in: oldHolder).opacity = 0.22
        let oldEdge = shape(paperPath, size: full, at: mid, stroke: 3.5 * k, in: oldHolder)
        oldEdge.lineJoin = .round
        let newHolder = holder(in: clipper, poses[0].newPaper)
        shape(paperPath, size: full, at: mid, in: newHolder).opacity = 0.22
        let newEdge = shape(paperPath, size: full, at: mid, stroke: 3.5 * k, in: newHolder)
        newEdge.lineJoin = .round

        let ink = shape(screen(frames[0].ink), size: full, at: mid, in: clipper)
        ink.fillRule = .evenOdd
        let bodyHolder = holder(in: clipper, poses[0].body)
        shape(screen(StampModel.body), size: full, at: mid, in: bodyHolder).fillRule = .evenOdd
        let sticky = shape(screen(frames[0].sticky), size: full, at: mid, in: clipper)
        sticky.fillRule = .evenOdd

        guard animating else { return }
        run(group([paths { $0.ink }], duration: duration), on: ink)
        run(group([paths { $0.sticky }], duration: duration), on: sticky)
        run(group([moves { $0.body }], duration: duration), on: bodyHolder)
        run(group([moves { $0.oldPaper }], duration: duration), on: oldHolder)
        run(group([moves { $0.newPaper }], duration: duration), on: newHolder)
    }
}
