import QuartzCore
import Foundation

private struct CorkFrame {
    let froth: CGPath
    let fill: CGPath
    let rings: CGPath
    let thunk: CGPath
    let thunkWidth: Double
    let thunkOpacity: Double
    let shake: Double
    let sx: Double
    let sy: Double
    let corkY: Double
    let corkRot: Double
    let corkSx: Double
    let corkSy: Double
}

private enum CorkModel {
    static let duration = 2.8
    static let count = 84
    static let tw = 0.15
    static let tp = 0.70
    static let td = 1.72
    static let tl = 1.92
    static let base = 106.0
    static let rim = 47.0

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }

    static func ease(_ value: Double) -> Double {
        let u = clamp(value)
        return u * u * (3 - 2 * u)
    }

    static func eout(_ value: Double) -> Double {
        let u = clamp(value)
        return 1 - pow(1 - u, 3)
    }

    static func bottle(_ t: Double) -> Double {
        var s = 0.0
        if tw <= t && t < tp { s = 0.10 * ease((t - 0.35) / (tp - 0.35)) }
        if t >= tp {
            let tau = t - tp
            s = 0.10 * exp(-40 * tau) - 0.10 * exp(-6 * tau) * sin(2 * Double.pi * 2.6 * tau + 0.2) * (1 - exp(-40 * tau)) * 1.3
        }
        if t >= tl {
            let b = t - tl
            s += 0.09 * exp(-8 * b) * cos(2 * Double.pi * 3 * b)
        }
        return s
    }

    static func cork(_ t: Double) -> (Double, Double, Double, Double) {
        if t <= tw { return (0, 0, 1, 1) }
        if tw < t && t < tp {
            let r = ease((t - tw) / (tp - tw))
            return (-3.0 * ease((t - 0.35) / (tp - 0.35)), 8 * r * sin(2 * Double.pi * 8 * t), 1, 1)
        }
        if tp <= t && t < td {
            let tau = t - tp
            let y = -3.0 - 420 * tau - 300 * tau * tau
            let sy = 1.45
            return (max(y, -140), 0, 1 / sqrt(sy), sy)
        }
        if td <= t && t < tl {
            let u = (t - td) / (tl - td)
            let sy = 1 + 0.4 * u
            return (-110 * (1 - u * u), 0, 1 / sqrt(sy), sy)
        }
        let b = t - tl
        let y = 3.2 * exp(-11 * b) * cos(2 * Double.pi * 2.6 * b)
        let q = 0.3 * exp(-9 * b) * cos(2 * Double.pi * 3.2 * b)
        return (y, 0, 1 + q * 0.9, 1 - q)
    }

    static let bubbles: [(Double, Double, Double, Double, Double)] = {
        var state: UInt64 = 0x9E3779B97F4A7C15
        func random(_ lo: Double, _ hi: Double) -> Double {
            state = state &* 6364136223846793005 &+ 1442695040888963407
            return lo + (hi - lo) * Double(state >> 11) / Double(1 << 53)
        }
        return (0..<60).map { i in
            let b0 = 0.62 * pow(Double(i) / 60, 1.6)
            return (b0, random(-1, 1), random(40, 85), random(1.2, 2.8), random(0.35, 0.6))
        }
    }()
    static let drips: [(Double, Double, Double)] = [(0.03, -1, 2.2), (0.10, 1, 2.0), (0.22, -1, 1.6), (0.30, 1, 1.8), (0.42, -1, 1.4)]
    static let frothSpec: [(Double, Double, Double)] = [(0, -4, 3.0), (-3.2, -2, 2.6), (3.2, -2.2, 2.6), (-1.6, -6.5, 2.4), (1.8, -6.8, 2.3), (0, -9, 2.0), (-4.4, 0.5, 2.0), (4.4, 0.4, 2.0)]

    static func foam(_ t: Double, _ top: Double) -> ([(Double, Double, Double)], [(Double, Double, Double)]) {
        let tau = t - tp - 0.04
        if tau < 0 || tau > 1.1 { return ([], []) }
        var froth: [(Double, Double, Double)] = []
        var bubs: [(Double, Double, Double)] = []
        let k = eout(tau / 0.12) * (1 - ease((tau - 0.55) / 0.45))
        if k > 0.02 {
            for (dx, dy, r) in frothSpec {
                froth.append((60 + dx * (0.6 + 0.4 * k), top + 1 + dy * k, r * (0.5 + 0.5 * k)))
            }
        }
        for (b0, d, v, r, life) in bubbles {
            let a = tau - b0
            if 0 < a && a < life {
                let u = a / life
                let x = 60 + d * 7 + d * 34 * a
                let y = top - 6 * k - v * a + 55 * a * a
                bubs.append((x, y, r * (1 - ease((u - 0.6) / 0.4))))
            }
        }
        for (b0, sd, r) in drips {
            let a = tau - b0
            if 0 < a && a < 0.55 {
                let p = eout(a / 0.55)
                let yy = top + 3 + 24 * p
                let xo = yy < 68 ? 6.6 : 6.6 + 9.5 * ease((yy - 68) / 9)
                bubs.append((60 + sd * xo, yy, r * (1 - ease((a - 0.35) / 0.2))))
            }
        }
        return (froth, bubs)
    }

    static func thunk(_ t: Double, _ top: Double) -> (CGPath, Double, Double) {
        let path = CGMutablePath()
        let b = t - tl
        if b < 0 || b > 0.3 { return (path, 3.2, 0) }
        let u = b / 0.3
        for sd in [-1.0, 1.0] {
            for (ang, ln) in [(15.0, 7.0), (45.0, 6.0)] {
                let a = ang * Double.pi / 180
                let r0 = 10 + 9 * eout(u)
                let r1 = r0 + ln * (1 - u)
                path.move(to: CGPoint(x: 60 + sd * cos(a) * r0, y: top - 4 - sin(a) * r0))
                path.addLine(to: CGPoint(x: 60 + sd * cos(a) * r1, y: top - 4 - sin(a) * r1))
            }
        }
        return (path, 3.2 * (1 - 0.5 * u), 1 - ease((u - 0.5) / 0.5))
    }

    static func shake(_ t: Double) -> Double {
        if !(tw < t && t < tp + 0.08) { return 0 }
        let r = t < tp ? ease((t - tw) / (tp - tw)) : 1 - ease((t - tp) / 0.08)
        return 4.5 * r * sin(2 * Double.pi * 7.5 * (t - tw))
    }

    static func frame(_ t: Double) -> CorkFrame {
        let s = bottle(t)
        let sy = 1 - s
        let sx = 1 + 0.8 * s
        let top = base - (base - rim) * sy
        let (frothItems, bubs) = foam(t, top)
        let fill = CGMutablePath()
        let rings = CGMutablePath()
        for (i, bub) in bubs.enumerated() where bub.2 >= 0.3 {
            let box = CGRect(x: bub.0 - bub.2, y: bub.1 - bub.2, width: 2 * bub.2, height: 2 * bub.2)
            if i % 3 == 1 && bub.2 > 1.6 { rings.addEllipse(in: box) } else { fill.addEllipse(in: box) }
        }
        let (thunkPath, width, opacity) = thunk(t, top)
        let (cy, rot, csx, csy) = cork(t)
        return CorkFrame(
            froth: CorkGoo.contour(frothItems.filter { $0.2 > 0.2 }, 2.0),
            fill: fill,
            rings: rings,
            thunk: thunkPath,
            thunkWidth: width,
            thunkOpacity: opacity,
            shake: shake(t),
            sx: sx,
            sy: sy,
            corkY: top + 3 + cy,
            corkRot: rot,
            corkSx: csx,
            corkSy: csy
        )
    }

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

    static var outline: CGPath {
        let p = CGMutablePath()
        p.move(to: CGPoint(x: 54.5, y: rim))
        p.addLine(to: CGPoint(x: 65.5, y: rim))
        p.addLine(to: CGPoint(x: 65.5, y: 68))
        p.addCurve(to: CGPoint(x: 75, y: 83), control1: CGPoint(x: 65.5, y: 74), control2: CGPoint(x: 75, y: 75))
        p.addLine(to: CGPoint(x: 75, y: 100))
        p.addQuadCurve(to: CGPoint(x: 69, y: 106), control: CGPoint(x: 75, y: 106))
        p.addLine(to: CGPoint(x: 51, y: 106))
        p.addQuadCurve(to: CGPoint(x: 45, y: 100), control: CGPoint(x: 45, y: 106))
        p.addLine(to: CGPoint(x: 45, y: 83))
        p.addCurve(to: CGPoint(x: 54.5, y: 68), control1: CGPoint(x: 45, y: 75), control2: CGPoint(x: 54.5, y: 74))
        p.closeSubpath()
        return p
    }

    static var neck: CGPath {
        let p = CGMutablePath()
        p.move(to: CGPoint(x: 53, y: rim + 3.5))
        p.addLine(to: CGPoint(x: 67, y: rim + 3.5))
        return p
    }

    static var label: CGPath {
        CGPath(roundedRect: CGRect(x: 50, y: 87, width: 20, height: 13), cornerWidth: 3.5, cornerHeight: 3.5, transform: nil)
    }

    static var plug: CGPath {
        CGPath(roundedRect: CGRect(x: 54.5, y: 40, width: 11, height: 13), cornerWidth: 3.2, cornerHeight: 3.2, transform: nil)
    }
}

private enum CorkGoo {
    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(_ circles: [(Double, Double, Double)], _ sigma: Double) -> CGPath {
        let path = CGMutablePath()
        guard !circles.isEmpty else { return path }
        let res = 2.0
        var minX = Double.infinity
        var minY = Double.infinity
        var maxX = -Double.infinity
        var maxY = -Double.infinity
        for (x, y, r) in circles {
            minX = min(minX, x - r)
            maxX = max(maxX, x + r)
            minY = min(minY, y - r)
            maxY = max(maxY, y + r)
        }
        let pad = sigma * 3.5 + 1
        let x0 = max(minX - pad, -40)
        let y0 = max(minY - pad, -40)
        let x1 = min(maxX + pad, 160)
        let y1 = min(maxY + pad, 160)
        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)
        for (x, y, r) in circles {
            ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
        }
        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 buildCork() {
        let unit = side
        let k = unit / 110
        let frames = CorkModel.frames
        let duration = CorkModel.duration
        let steps = CorkModel.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 }
        func spot(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: (x - 5) * k, y: unit - (y - 5) * k) }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        func discrete(_ keyPath: String, _ values: [Any]) -> CAKeyframeAnimation {
            let animation = keyframes(keyPath, values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func paths(_ pick: (CorkFrame) -> CGPath) -> CAKeyframeAnimation {
            discrete("path", (0..<steps).map { placed(pick(frames[$0])) })
        }
        func holder(in parent: CALayer, anchor: CGPoint) -> CALayer {
            let layer = CALayer()
            layer.bounds = CGRect(origin: .zero, size: full)
            layer.anchorPoint = CGPoint(x: anchor.x / unit, y: anchor.y / unit)
            layer.position = anchor
            parent.addSublayer(layer)
            return layer
        }
        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 pivot = spot(60, 106)
        let shaker = holder(in: clipper, anchor: pivot)
        let base = spot(60, CorkModel.base)
        let body = holder(in: shaker, anchor: base)
        shape(placed(CorkModel.outline), size: full, at: mid, in: body).opacity = 0.22
        let outline = shape(placed(CorkModel.outline), size: full, at: mid, stroke: 4 * k, in: body)
        outline.lineJoin = .round
        let neck = shape(placed(CorkModel.neck), size: full, at: mid, stroke: 3.4 * k, in: body)
        neck.lineCap = .round
        shape(placed(CorkModel.label), size: full, at: mid, stroke: 2.6 * k, in: body)

        let froth = shape(placed(frames[0].froth), size: full, at: mid, in: shaker)
        let fill = shape(placed(frames[0].fill), size: full, at: mid, in: shaker)
        let rings = shape(placed(frames[0].rings), size: full, at: mid, stroke: 1.2 * k, in: shaker)
        let thunk = shape(placed(frames[0].thunk), size: full, at: mid, stroke: 3.2 * k, in: shaker)
        thunk.lineCap = .round
        thunk.opacity = 0

        let plugAnchor = spot(60, 50)
        let plug = holder(in: shaker, anchor: plugAnchor)
        shape(placed(CorkModel.plug), size: full, at: mid, in: plug)

        guard animating else { return }
        let turns = (0..<steps).map { NSValue(caTransform3D: CATransform3DMakeRotation(-frames[$0].shake * .pi / 180, 0, 0, 1)) }
        run(group([discrete("transform", turns)], duration: duration), on: shaker)
        run(group([discrete("transform", (0..<steps).map { Self.scaled(frames[$0].sx, frames[$0].sy) })], duration: duration), on: body)
        run(group([paths { $0.froth }], duration: duration), on: froth)
        run(group([paths { $0.fill }], duration: duration), on: fill)
        run(group([paths { $0.rings }], duration: duration), on: rings)
        let thunkWidth = discrete("lineWidth", (0..<steps).map { NSNumber(value: frames[$0].thunkWidth * k) })
        let thunkOpacity = discrete("opacity", (0..<steps).map { NSNumber(value: frames[$0].thunkOpacity) })
        run(group([paths { $0.thunk }, thunkWidth, thunkOpacity], duration: duration), on: thunk)
        let moves = discrete("position", (0..<steps).map { flairPoint(spot(60, frames[$0].corkY)) })
        let turn = discrete("transform", (0..<steps).map { Self.oriented(-frames[$0].corkRot * .pi / 180, frames[$0].corkSx, frames[$0].corkSy) })
        run(group([moves, turn], duration: duration), on: plug)
    }
}
