import QuartzCore
import Foundation

private struct SimmerFrame {
    let puffs: CGPath
    let rim: CGPath
    let pot: CGPath
    let lid: CGPath
    let knob: CGPath
}

private enum SimmerModel {
    static let duration = 2.4
    static let count = 80
    static let lidDrop = 0.85

    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 lid(_ t: Double) -> (Double, Double) {
        var lift = 0.0
        var tilt = 0.0
        if 0.15 < t && t < lidDrop {
            let r = ease((t - 0.15) / (lidDrop - 0.15))
            let ph = 2 * Double.pi * 11 * t
            tilt = 3.2 * r * sin(ph)
            lift = 1.6 * r * max(0, sin(ph * 2))
        }
        let tau = t - lidDrop
        let tf = 0.42
        if tau >= 0 && tau < tf {
            let v = 2 * 25 / (tf / 2)
            let g = 2 * 25 / pow(tf / 2, 2)
            lift = v * tau - 0.5 * g * tau * tau
            tilt = -13 * sin(Double.pi * tau / tf)
        } else if tau >= tf {
            let b = tau - tf
            let hops: [(Double, Double)] = [(0.16, 5.0), (0.09, 1.6)]
            var tt = b
            for (d, h) in hops {
                if tt < d {
                    lift = h * 4 * (tt / d) * (1 - tt / d)
                    break
                }
                tt -= d
            }
            tilt = 7 * exp(-4.5 * b) * sin(2 * Double.pi * 7 * b)
        }
        return (lift, tilt)
    }

    static func pot(_ t: Double) -> (Double, Double) {
        var sx = 1.0
        var sy = 1.0
        if 0.55 < t && t < lidDrop {
            let u = ease((t - 0.55) / (lidDrop - 0.55))
            sy -= 0.09 * u
            sx += 0.06 * u
        }
        let tau = t - lidDrop
        if tau >= 0 {
            let d = exp(-6 * tau)
            let w = 2 * Double.pi * 3
            sy += 0.11 * d * cos(w * tau - 0.4)
            sx -= 0.07 * d * cos(w * tau - 0.4)
        }
        let land = lidDrop + 0.42
        if t > land {
            let b = t - land
            let e = 0.05 * exp(-10 * b) * cos(2 * Double.pi * 4 * b)
            sy -= e
            sx += e * 0.7
        }
        return (sx, sy)
    }

    static let puffSpecs: [(Double, Double, Double, Double, Double)] = [(-7, 0.00, -36, 32, 10.5), (8, 0.03, 36, 36, 9.5), (0, 0.07, 0, 44, 8.5)]
    static let leaks: [(Double, Double)] = [(0.35, -18), (0.48, 20), (0.6, -22), (0.7, 16), (0.78, -14)]

    static func puffs(_ t: Double, _ rimY: Double) -> [(Double, Double, Double)] {
        var out: [(Double, Double, Double)] = []
        for (x0, d0, vx, vy, big) in puffSpecs {
            let tau = t - lidDrop - d0
            if tau <= 0 { continue }
            let grow = 1 - pow(1 - clamp(tau / 0.18), 3)
            let fade = 1 - ease((tau - 0.6) / 0.8)
            let r = big * grow * fade * (1 + 0.12 * sin(tau * 9 + x0))
            if r < 0.3 { continue }
            let x = 50 + x0 + vx * (1 - exp(-3 * tau)) / 3
            let y = rimY - 6 - vy * (1 - exp(-4.5 * tau)) - 5 * tau
            out.append((x, y, r))
        }
        for (t0, x0) in leaks {
            let tau = t - t0
            if 0 < tau && tau < 0.45 {
                let r = 3.2 * sin(Double.pi * tau / 0.45)
                out.append((50 + x0 + 4 * (x0 < 0 ? -1 : 1) * tau, rimY - 2 - 40 * tau, r))
            }
        }
        return out
    }

    static func frame(_ t: Double) -> SimmerFrame {
        let (sx, sy) = pot(t)
        let (lift, tilt) = lid(t)
        let height = 40.0
        let top = 88 - height * sy
        let puffPath = SimmerGoo.contour(puffs(t, top), 2.4)
        let w = 64 * sx
        let x0 = 50 - w / 2
        let rim = CGMutablePath()
        rim.move(to: CGPoint(x: x0 - 8 * sx, y: top + 9 * sy))
        rim.addLine(to: CGPoint(x: x0 + 2, y: top + 9 * sy))
        rim.move(to: CGPoint(x: x0 + w - 2, y: top + 9 * sy))
        rim.addLine(to: CGPoint(x: x0 + w + 8 * sx, y: top + 9 * sy))
        let pot = CGPath(roundedRect: CGRect(x: x0, y: top, width: w, height: height * sy), cornerWidth: 8, cornerHeight: 8, transform: nil)
        let lw = 60 * sx
        let lidPath = CGMutablePath()
        lidPath.move(to: CGPoint(x: -lw / 2, y: 0))
        lidPath.addCurve(to: CGPoint(x: lw / 2, y: 0), control1: CGPoint(x: -lw / 2 + 4, y: -13), control2: CGPoint(x: lw / 2 - 4, y: -13))
        lidPath.closeSubpath()
        let knob = CGPath(roundedRect: CGRect(x: -5, y: -16.5, width: 10, height: 7), cornerWidth: 3, cornerHeight: 3, transform: nil)
        let angle = tilt * Double.pi / 180
        var place = CGAffineTransform(translationX: 50, y: top - 1 - lift).rotated(by: angle)
        return SimmerFrame(
            puffs: puffPath,
            rim: rim,
            pot: pot,
            lid: lidPath.copy(using: &place) ?? lidPath,
            knob: knob.copy(using: &place) ?? knob
        )
    }

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

private enum SimmerGoo {
    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 buildSimmer() {
        let unit = side
        let k = unit / 110
        let frames = SimmerModel.frames
        let duration = SimmerModel.duration
        let steps = SimmerModel.count
        var map = CGAffineTransform(a: 0.88 * k, b: 0, c: 0, d: -0.88 * k, tx: 11 * k, ty: unit - 15 * 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: (SimmerFrame) -> 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 width = 4 * 0.88 * k
        let puffs = shape(placed(frames[0].puffs), size: full, at: mid, in: clipper)
        let rim = shape(placed(frames[0].rim), size: full, at: mid, stroke: width, in: clipper)
        rim.lineCap = .round
        let potFill = shape(placed(frames[0].pot), size: full, at: mid, in: clipper)
        potFill.opacity = 0.22
        let pot = shape(placed(frames[0].pot), size: full, at: mid, stroke: width, in: clipper)
        pot.lineJoin = .round
        let lidFill = shape(placed(frames[0].lid), size: full, at: mid, in: clipper)
        lidFill.opacity = 0.22
        let lid = shape(placed(frames[0].lid), size: full, at: mid, stroke: width, in: clipper)
        lid.lineJoin = .round
        let knob = shape(placed(frames[0].knob), size: full, at: mid, in: clipper)

        guard animating else { return }
        run(group([paths { $0.puffs }], duration: duration), on: puffs)
        run(group([paths { $0.rim }], duration: duration), on: rim)
        run(group([paths { $0.pot }], duration: duration), on: potFill)
        run(group([paths { $0.pot }], duration: duration), on: pot)
        run(group([paths { $0.lid }], duration: duration), on: lidFill)
        run(group([paths { $0.lid }], duration: duration), on: lid)
        run(group([paths { $0.knob }], duration: duration), on: knob)
    }
}
