import QuartzCore
import Foundation

private enum BrewItem {
    case circle(Double, Double, Double)
    case ellipse(Double, Double, Double, Double)
    case line([CGPoint], Double)
    case area(CGPath)
}

private struct BrewFrame {
    let tint: CGPath
    let ink: CGPath
}

private enum BrewModel {
    static let duration = 3.6
    static let count = 108
    static let sx = 60.0
    static let tip = 34.5
    static let tr = 0.25
    static let te = 2.05
    static let tdr = 2.36
    static let gravity = 2200.0
    static let bot = 97.0

    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: [BrewItem], _ 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 .area(p): let b = p.boundingBoxOfPath; grow(Double(b.midX), Double(b.midY), Double(max(b.width, b.height)) / 2 + 1)
            }
        }
        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 .area(p):
                ctx.addPath(p)
                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
    }

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

    nonisolated(unsafe) static let funnel: CGPath = {
        let p = CGMutablePath()
        func pt(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x + 11, y: y) }
        p.move(to: pt(36, 12))
        p.addCurve(to: pt(42, 8), control1: pt(36, 8), control2: pt(40, 8))
        p.addLine(to: pt(56, 8))
        p.addCurve(to: pt(62, 12), control1: pt(58, 8), control2: pt(62, 8))
        p.addCurve(to: pt(54, 32), control1: pt(62, 22), control2: pt(55, 26))
        p.addCurve(to: pt(44, 32), control1: pt(53, 36), control2: pt(45, 36))
        p.addCurve(to: pt(36, 12), control1: pt(43, 26), control2: pt(36, 22))
        p.closeSubpath()
        return p
    }()

    nonisolated(unsafe) static let body: CGPath = CGPath(roundedRect: CGRect(x: 37, y: 58, width: 46, height: 44), cornerWidth: 8, cornerHeight: 8, transform: nil)

    nonisolated(unsafe) static let ring: CGPath = {
        let p = CGMutablePath()
        p.addArc(center: CGPoint(x: 84, y: 80), radius: 14, startAngle: 0, endAngle: .pi * 2, clockwise: false)
        p.addArc(center: CGPoint(x: 84, y: 80), radius: 7, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        return p
    }()

    nonisolated(unsafe) static let bodyRegion: CGPath = body.union(stroked(body))
    nonisolated(unsafe) static let handleOutline: CGPath = {
        let outer = CGMutablePath()
        outer.addEllipse(in: CGRect(x: 70, y: 66, width: 28, height: 28))
        let inner = CGMutablePath()
        inner.addEllipse(in: CGRect(x: 77, y: 73, width: 14, height: 14))
        return stroked(outer).union(stroked(inner))
    }()
    nonisolated(unsafe) static let cupInk: CGPath = stroked(body).union(handleOutline.subtracting(bodyRegion))
    nonisolated(unsafe) static let cupTint: CGPath = body.union(ring.subtracting(bodyRegion))

    static func stroked(_ path: CGPath) -> CGPath {
        path.copy(strokingWithWidth: 4, lineCap: .butt, lineJoin: .round, miterLimit: 10)
    }

    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 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 modulo(_ a: Int, _ b: Int) -> Int { ((a % b) + b) % b }

    static func levelFull(_ t: Double) -> Double {
        let u = clamp((t - 0.49) / (2.2 - 0.49))
        let v = u * u * (3 - 2 * u) * 0.35 + u * 0.65
        return bot - 31 * v + keys(t, [(2.45, 0), (2.5, -1.2), (2.6, 0)])
    }

    static func surf(_ t: Double, _ x: Double, _ lv: Double, _ active: Double) -> Double {
        var y = lv
        if active > 0 {
            y -= 2.2 * active * exp(-pow((x - sx) / 4.5, 2))
            y += 0.9 * active * cos(0.55 * abs(x - sx) - 26 * t)
        }
        return y
    }

    static func flowAmt(_ t: Double) -> Double {
        clamp((t - 0.49) / 0.08) * (1 - clamp((t - 2.2) / 0.15))
    }

    static func coffee(_ t: Double, _ lv: Double, _ act: Double) -> CGPath {
        let p = CGMutablePath()
        if bot - lv < 0.6 { return p }
        p.move(to: CGPoint(x: 42, y: bot))
        for i in 0..<25 {
            let x = 42 + Double(i) * 1.5
            p.addLine(to: CGPoint(x: x, y: min(bot, surf(t, x, lv, act))))
        }
        p.addLine(to: CGPoint(x: 78, y: bot))
        p.closeSubpath()
        return p
    }

    static func cupTransform(_ dx: Double, _ rot: Double, _ scx: Double, _ scy: Double) -> CGAffineTransform {
        CGAffineTransform.identity
            .translatedBy(x: dx, y: 0)
            .translatedBy(x: 60, y: 102)
            .rotated(by: rot * .pi / 180)
            .scaledBy(x: scx, y: scy)
            .translatedBy(x: -60, y: -102)
    }

    static func fullCup(_ t: Double) -> (Double, Double, Double, Double) {
        (
            keys(t, [(2.62, 0), (2.74, -4), (3.04, 80)]),
            keys(t, [(2.62, 0), (2.74, 5), (2.86, -9), (3.04, -4)]),
            keys(t, [(0.45, 1), (0.5, 1.05), (0.6, 0.98), (0.7, 1), (2.62, 1), (2.74, 1.06), (2.84, 0.96), (3.04, 1)]),
            keys(t, [(0.45, 1), (0.5, 0.95), (0.6, 1.02), (0.7, 1), (2.62, 1), (2.74, 0.93), (2.84, 1.05), (3.04, 1)])
        )
    }

    static func newCup(_ t: Double) -> (Double, Double, Double, Double) {
        (
            keys(t, [(2.76, -80), (3.08, 3.5), (3.2, -1.2), (3.3, 0)]),
            keys(t, [(2.76, -6), (3.0, -4), (3.1, 7), (3.22, -2.5), (3.34, 0.8), (3.44, 0)]),
            keys(t, [(3.04, 1), (3.1, 1.09), (3.2, 0.96), (3.3, 1.02), (3.4, 1)]),
            keys(t, [(3.04, 1), (3.1, 0.91), (3.2, 1.04), (3.3, 0.99), (3.4, 1)])
        )
    }

    static func funnelDy(_ t: Double) -> Double {
        keys(t, [(0, 0), (0.18, 1), (tr, 1), (tr + 0.05, -1.6), (tr + 0.14, 0.5), (tr + 0.22, 0), (te - 0.05, 0), (te, 0.8), (te + 0.05, -1.8), (te + 0.14, 0.6), (te + 0.24, 0), (tdr, 0), (tdr + 0.05, -1.2), (tdr + 0.13, 0)])
    }

    static func circ(_ p: inout [BrewItem], _ x: Double, _ y: Double, _ r: Double) {
        if r > 0.15 { p.append(.circle(x, y, r)) }
    }

    static func ell(_ p: inout [BrewItem], _ x: Double, _ y: Double, _ rx: Double, _ ry: Double) {
        if rx > 0.15 { p.append(.ellipse(x, y, rx, ry)) }
    }

    static func stream(_ t: Double, _ tipy: Double, into p: inout [BrewItem]) {
        let lv = levelFull(t)
        var top = tipy
        if t < tr { return }
        let dt = t - tr
        let head = tipy + 6 + 50 * dt + 0.5 * gravity * dt * dt
        let bottom = min(head, lv)
        if t > te {
            let de = t - te
            top = tipy + 2 + 60 * de + 0.5 * gravity * de * de
        }
        if top >= bottom { return }
        var y = top
        while y < bottom {
            var w = 2.5 + 0.45 * sin((y - 340 * t) * 0.32)
            if t > te { w *= 1 - 0.35 * clamp((t - te) / 0.1) * clamp(1 - (y - top) / 14) }
            circ(&p, sx + 0.4 * sin(y * 0.2 - 30 * t), y, w)
            y += 1.3
        }
        if head < lv {
            let v = 50 + gravity * dt
            let k = 1 + v / 1100
            ell(&p, sx, head, 3.3 / k.squareRoot(), 3.3 * k)
        }
    }

    static func bud(_ t: Double, _ tipy: Double, into p: inout [BrewItem]) {
        circ(&p, sx, tipy, 3 + keys(t, [(tr, 0), (tr + 0.05, 0.8), (tr + 0.12, 0), (te, 0), (te + 0.05, 0.8), (te + 0.13, 0)]))
        if t >= 3.2 || t < tr {
            let tt = t >= 3.2 ? t - duration : t
            let r = keys(tt, [(-0.4, 0), (0, 1.8), (tr, 3.6)])
            ell(&p, sx, tipy + 1 + r, r * 0.95, r * 1.08)
        } else if te + 0.12 < t && t < tdr {
            let r = keys(t, [(te + 0.12, 0), (tdr - 0.05, 3.2)])
            ell(&p, sx, tipy + 1 + r, r * 0.92, r * 1.12)
        } else if tdr <= t && t < tdr + 0.2 {
            let dt = t - tdr
            let y = tipy + 4 + 40 * dt + 0.5 * gravity * dt * dt
            let lv = levelFull(t)
            if y < lv + 2 {
                let k = 1 + (40 + gravity * dt) / 1100
                ell(&p, sx, y, 3.0 / k.squareRoot(), 3.0 * k)
            }
        }
    }

    static func splashes(_ t: Double, into p: inout [BrewItem]) {
        let base = Int((t - 0.49) / 0.09)
        for i in (base - 2)..<(base + 1) {
            let t0 = 0.49 + Double(i) * 0.09
            if t0 < 0.49 || t0 > 2.15 { continue }
            let u = t - t0
            if u < 0 || u > 0.32 { continue }
            let side = modulo(i, 2) == 1 ? 1.0 : -1.0
            let vx = side * (20 + 7 * Double(modulo(i * 7, 3)))
            let vy = -95 - 25 * Double(modulo(i * 5, 3))
            let lv0 = levelFull(t0)
            let x = sx + side * 3 + vx * u
            let y = lv0 - 1 + vy * u + 0.5 * 1100 * u * u
            let lv = levelFull(t)
            var r = 1.9
            if vy + 1100 * u > 0 && y > lv - 1 { r *= 1 - clamp((y - lv + 1) / 3) }
            circ(&p, x, y, r)
        }
        if 0.49 <= t && t < 0.75 {
            let u = t - 0.49
            for side in [-1.0, 1.0] {
                let x = sx + side * (4 + 45 * u)
                let y = bot - 3 - 120 * u + 0.5 * 1100 * u * u
                let r = 2.6 * (1 - clamp((u - 0.12) / 0.12))
                circ(&p, x, min(y, bot - 1), r)
            }
        }
    }

    static func wisp(_ t: Double, _ x0: Double, _ side: Double, _ t0: Double, _ dxc: Double, into p: inout [BrewItem]) {
        let hs = eout((t - t0) / 0.45)
        let ts = ease((t - t0 - 0.35) / 0.5)
        if hs <= 0 || ts >= 1 { return }
        let lift = 10 * ts
        let n = 22
        for i in 0...n {
            let s = Double(i) / Double(n)
            if s > hs || s < ts { continue }
            let ph = 2 * Double.pi * (1.1 * s) - 8 * (t - t0)
            let amp = 2.6 * clamp(s / 0.35)
            let x = x0 + dxc + side * amp * sin(ph)
            let y = 66 - lift - 22 * s
            var r = 2.3 * (1 - 0.3 * s)
            r *= clamp((hs - s) / 0.12 + 0.4)
            r *= 1 - ease((ts - 0.4) / 0.6)
            r *= 1 - ease((t - 2.72) / 0.16)
            circ(&p, x, y, r)
        }
    }

    static func build(_ t: Double) -> BrewFrame {
        let fy = funnelDy(t)
        let tipy = tip + fy
        let (fdx, frot, fsx, fsy) = fullCup(t)
        let ftf = cupTransform(fdx, frot, fsx, fsy)
        let tint = CGMutablePath()
        let ink = CGMutablePath()
        var goo: [BrewItem] = []
        if t < 3.1 {
            var tf = ftf
            tint.addPath(cupTint, transform: tf)
            ink.addPath(cupInk, transform: tf)
            tf = ftf
            let c = coffee(t, levelFull(t), flowAmt(t))
            if !c.isEmpty { goo.append(.area(c.copy(using: &tf) ?? c)) }
        }
        if t > 2.7 {
            let (ndx, nrot, nsx, nsy) = newCup(t)
            let tf = cupTransform(ndx, nrot, nsx, nsy)
            tint.addPath(cupTint, transform: tf)
            ink.addPath(cupInk, transform: tf)
        }
        stream(t, tipy, into: &goo)
        bud(t, tipy, into: &goo)
        splashes(t, into: &goo)
        wisp(t, 51, 1, 2.05, fdx, into: &goo)
        wisp(t, 69, -1, 2.13, fdx, into: &goo)
        return BrewFrame(tint: tint, ink: ink.union(contour(goo, 2.0), using: .winding))
    }
}

extension FlairLayer {
    func buildBrew() {
        let unit = side
        let k = unit / 110
        let frames = BrewModel.frames
        let duration = BrewModel.duration
        let steps = BrewModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 2 * k)
        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)
        func paths(_ pick: (BrewFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { placed(pick(frames[$0])) }
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", values, 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 tint = shape(placed(frames[0].tint), size: full, at: mid, in: clipper)
        tint.opacity = 0.22

        let funnelTint = shape(placed(BrewModel.funnel), size: full, at: mid, in: clipper)
        funnelTint.opacity = 0.22
        let funnelInk = shape(placed(BrewModel.funnel), size: full, at: mid, stroke: 4 * k, in: clipper)
        funnelInk.lineJoin = .round

        let ink = shape(placed(frames[0].ink), size: full, at: mid, in: clipper)

        guard animating else { return }
        run(group([paths { $0.tint }], duration: duration), on: tint)
        run(group([paths { $0.ink }], duration: duration), on: ink)
        let moves = (0..<steps).map { flairPoint(CGPoint(x: mid.x, y: mid.y - BrewModel.funnelDy(Double($0) * duration / Double(steps)) * k)) }
        for layer in [funnelTint, funnelInk] {
            run(group([keyframes("position", moves, timing: .linear)], duration: duration), on: layer)
        }
    }
}
