import QuartzCore
import Foundation

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

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

private struct EclipseCanvas {
    var tint = CGMutablePath() as CGPath
    var ink = CGMutablePath() as CGPath

    mutating func put(fill: CGPath, outline: CGPath, covered: Bool = false) {
        let region = fill.union(outline)
        tint = tint.subtracting(region).union(fill)
        ink = ink.subtracting(region).union(covered ? outline.subtracting(fill) : outline)
    }

    mutating func line(_ path: CGPath) {
        ink = ink.union(path)
    }
}

private enum EclipseModel {
    static let duration = 5.5
    static let count = 165
    static let hy = 95.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: [EclipseItem], _ 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: [EclipseFrame] = (0..<count).map { build(Double($0) * duration / Double(count)) }

    static let scy: [(Double, Double)] = [(0, 50), (1.7, 50), (1.92, 44), (2.24, 124), (4.74, 124), (4.94, 40), (5.1, 53), (5.26, 48.5), (5.42, 50)]
    static let ssx: [(Double, Double)] = [(0, 1), (1.7, 1), (1.92, 0.9), (2.06, 0.84), (2.14, 1.34), (2.24, 1.15), (4.74, 0.78), (4.86, 0.8), (4.94, 0.86), (5.1, 1.16), (5.26, 0.95), (5.42, 1)]
    static let ssy: [(Double, Double)] = [(0, 1), (1.7, 1), (1.92, 1.12), (2.06, 1.22), (2.14, 0.74), (2.24, 0.85), (4.74, 1.3), (4.86, 1.25), (4.94, 1.16), (5.1, 0.84), (5.26, 1.05), (5.42, 1)]
    static let mcy: [(Double, Double)] = [(0, 125), (2.24, 125), (2.4, 37), (2.56, 52), (2.7, 46), (2.84, 49), (4.48, 49), (4.56, 44), (4.76, 125)]
    static let msx: [(Double, Double)] = [(0, 0.75), (2.24, 0.75), (2.36, 0.8), (2.46, 0.9), (2.56, 1.18), (2.7, 0.95), (2.84, 1.0), (4.48, 1.0), (4.56, 0.9), (4.64, 0.84), (4.7, 1.26), (4.76, 1.1)]
    static let msy: [(Double, Double)] = [(0, 1.3), (2.24, 1.3), (2.36, 1.3), (2.46, 1.15), (2.56, 0.82), (2.7, 1.06), (2.84, 1.0), (4.48, 1.0), (4.56, 1.1), (4.64, 1.2), (4.7, 0.78), (4.76, 0.9)]
    static let mr: [(Double, Double)] = [(0, -15), (2.4, -15), (2.56, 6), (2.7, -3), (2.84, 0), (4.48, 0), (4.76, 8)]

    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 back(_ u: Double) -> Double {
        let v = clamp(u) - 1
        return 1 + 2.7 * v * v * v + 1.7 * v * v
    }

    static func modulo(_ a: Double, _ b: Double) -> Double {
        let r = a.truncatingRemainder(dividingBy: b)
        return r < 0 ? r + b : r
    }

    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 stroked(_ path: CGPath, _ width: Double, cap: CGLineCap = .butt) -> CGPath {
        path.copy(strokingWithWidth: width, lineCap: cap, lineJoin: .round, miterLimit: 10)
    }

    static func circle(_ x: Double, _ y: Double, _ r: Double) -> CGPath {
        CGPath(ellipseIn: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2), transform: nil)
    }

    static func raysLength(_ t: Double) -> Double {
        if t < 3.5 { return 1 - ease((t - 1.9) / 0.2) }
        return back((t - 5.0) / 0.24)
    }

    static func sun(_ t: Double, into canvas: inout EclipseCanvas) {
        let cy = keys(t, scy)
        let sx = keys(t, ssx)
        let sy = keys(t, ssy)
        let br = 1 + 0.03 * sin(2 * .pi * t / 1.1) * (1 - clamp((t - 1.5) / 0.2)) * clamp((t - 5.4) / 0.3 + (t < 3 ? 1 : 0))
        let el = CGPath(ellipseIn: CGRect(x: 60 - 15 * sx * br, y: cy - 15 * sy * br, width: 30 * sx * br, height: 30 * sy * br), transform: nil)
        let lr = raysLength(t)
        var rays = CGMutablePath() as CGPath
        if lr > 0.01 {
            let w = 4 * min(1, lr / 0.3)
            let rot = 360 * t / duration
            for k in 0..<12 {
                let a = (rot + 30 * Double(k)) * .pi / 180
                let pul = 1 + 0.25 * sin(2 * .pi * t / (duration / 5) + 1.1 * Double(k))
                let ln = (k % 2 == 0 ? 6.5 : 3.2) * pul
                let r0 = 21.5 * br
                let r1 = (21.5 + ln * lr) * br
                let p = CGMutablePath()
                p.move(to: CGPoint(x: 60 + r0 * cos(a) * sx, y: cy + r0 * sin(a) * sy))
                p.addLine(to: CGPoint(x: 60 + r1 * cos(a) * sx, y: cy + r1 * sin(a) * sy))
                rays = rays.union(stroked(p, w, cap: .round))
            }
        }
        canvas.put(fill: el, outline: stroked(el, 4))
        canvas.line(rays)
    }

    nonisolated(unsafe) static let crescent: CGPath = {
        let r = 21.0
        let c2 = CGPoint(x: 0.42 * r, y: -0.38 * r)
        let r2 = 0.86 * r
        var pts: [(Double, CGPoint)] = []
        for i in 0..<90 {
            let a = 2 * Double.pi * Double(i) / 90
            let p = CGPoint(x: r * cos(a), y: r * sin(a))
            if hypot(p.x - c2.x, p.y - c2.y) > r2 { pts.append((a, p)) }
        }
        var i0 = 0
        var best = -1.0
        for i in 0..<pts.count {
            let gap = modulo(pts[(i + 1) % pts.count].0 - pts[i].0, 2 * .pi)
            if gap > best { best = gap; i0 = i }
        }
        let outer = Array(pts[(i0 + 1)...] + pts[...i0]).map { $0.1 }
        let pe = outer[outer.count - 1]
        let ps = outer[0]
        let a1 = atan2(pe.y - c2.y, pe.x - c2.x)
        let a0 = atan2(ps.y - c2.y, ps.x - c2.x)
        var da = modulo(a0 - a1, 2 * .pi)
        if da > .pi { da -= 2 * .pi }
        var all = outer
        for i in 1..<40 {
            let a = a1 + da * Double(i) / 40
            all.append(CGPoint(x: c2.x + r2 * cos(a), y: c2.y + r2 * sin(a)))
        }
        let p = CGMutablePath()
        p.addLines(between: all)
        p.closeSubpath()
        return p
    }()

    static func moon(_ t: Double, into canvas: inout EclipseCanvas) {
        guard t > 2.24 && t < 4.78 else { return }
        let cy = keys(t, mcy)
        let sx = keys(t, msx)
        let sy = keys(t, msy)
        let r = keys(t, mr)
        var tf = CGAffineTransform.identity.translatedBy(x: 60, y: cy).rotated(by: r * .pi / 180).scaledBy(x: sx, y: sy)
        let body = crescent.copy(using: &tf) ?? crescent
        let width = 4.0
        var local = crescent
        let stroke = stroked(crescent, width / ((sx + sy) / 2))
        local = stroke
        let outline = local.copy(using: &tf) ?? local
        canvas.put(fill: body, outline: outline)
    }

    static let stars: [(Double, Double, Double, Double)] = [(27, 44, 3.6, 2.5), (93, 34, 3.2, 2.62), (88, 72, 2.6, 2.74), (33, 76, 2.4, 2.68), (79, 15, 2.2, 2.8)]

    static func sparkle(_ x: Double, _ y: Double, _ r: Double, _ a: Double) -> CGPath {
        var p: [CGPoint] = []
        for i in 0..<4 {
            let b = (a + 90 * Double(i)) * .pi / 180
            p.append(CGPoint(x: x + r * cos(b), y: y + r * sin(b)))
        }
        let path = CGMutablePath()
        path.move(to: p[0])
        for i in 0..<4 { path.addQuadCurve(to: p[(i + 1) % 4], control: CGPoint(x: x, y: y)) }
        path.closeSubpath()
        return path.union(stroked(path, min(2.0, r * 0.5)))
    }

    static func starsPath(_ t: Double) -> CGPath {
        var out = CGMutablePath() as CGPath
        for (j, s) in stars.enumerated() {
            let sc = back((t - s.3) / 0.28) * (1 - ease((t - 4.4 - 0.03 * Double(j)) / 0.2))
            if sc <= 0.02 { continue }
            let tw = 1 + 0.28 * sin(2 * .pi * (t - s.3) * 1.8 + Double(j) * 1.7)
            out = out.union(sparkle(s.0, s.1, s.2 * 1.6 * sc * tw, 12 * sin(2 * .pi * (t - s.3) * 0.9 + Double(j))))
        }
        return out
    }

    static func cometAt(_ t: Double) -> (Double, Double) {
        var u = (t - 3.4) / 0.5
        u = u * (0.75 + 0.25 * u)
        let q = 1 - u
        let a = (-14.0, 34.0)
        let b = (60.0, -6.0)
        let e = (134.0, 24.0)
        return (q * q * a.0 + 2 * q * u * b.0 + u * u * e.0, q * q * a.1 + 2 * q * u * b.1 + u * u * e.1)
    }

    static func comet(_ t: Double) -> CGPath {
        var items: [EclipseItem] = []
        guard t > 3.38 && t < 4.2 else { return CGMutablePath() }
        for j in 0..<16 {
            let tj = t - Double(j) * 0.014
            if tj >= 3.4 && tj <= 3.9 {
                let (x, y) = cometAt(tj)
                let r = 3.8 * pow(1 - Double(j) / 16, 1.3) + 0.4
                if r > 0.15 { items.append(.circle(x, y, r)) }
            }
        }
        return contour(items, 1.6)
    }

    static let clouds: [(Double, Double, Double, Double, [(Double, Double, Double)], (Double, Double))] = [
        (20, 27, 1.0, 0.0, [(-9, 0, 7), (1, -6, 9), (11, -1, 6.5)], (-16, 17)),
        (74, 80, 0.8, 0.12, [(-7, 0, 5.5), (3, -4, 7.5), (11, 1, 4.5)], (-13, 15))
    ]

    static func cloud(_ t: Double, _ i: Int, into canvas: inout EclipseCanvas) {
        let (x0, y0, sc, dl, parts, span) = clouds[i]
        let p = modulo(t - 5.1 - dl, duration)
        guard p < 2.6 else { return }
        let s = back(p / 0.4) * (1 - ease((p - 1.78 + dl) / 0.3))
        guard s > 0.02 else { return }
        let x = x0 + 7 * p + 1.5 * sin(2 * .pi * p / 2.7 + Double(i))
        let y = y0 + 1.3 * sin(2 * .pi * p / 2.1 + 2 * Double(i))
        let f = 2 * Double.pi / duration
        var fill = CGMutablePath() as CGPath
        for (j, part) in parts.enumerated() {
            let jj = Double(j)
            let rr = part.2 * (1 + 0.07 * sin(f * (5 + jj) * t + 2.1 * jj + Double(i)))
            let cx = x + (part.0 + 0.8 * sin(f * 3 * t + 1.7 * jj + Double(i))) * sc
            let cy = y + (part.1 + 0.6 * cos(f * 4 * t + 1.3 * jj + Double(i))) * sc
            fill = fill.union(circle(cx, cy, rr * sc))
        }
        let rect = CGRect(x: x + span.0 * sc, y: y, width: (span.1 - span.0) * sc, height: 7 * sc)
        fill = fill.union(CGPath(roundedRect: rect, cornerWidth: 3.5 * sc, cornerHeight: 3.5 * sc, transform: nil))
        let outline = stroked(fill, 8)
        var tf = CGAffineTransform.identity.translatedBy(x: x, y: y + 4).scaledBy(x: s, y: s).translatedBy(x: -x, y: -y - 4)
        let f2 = fill.copy(using: &tf) ?? fill
        let o2 = outline.copy(using: &tf) ?? outline
        canvas.put(fill: f2, outline: o2, covered: true)
    }

    static func build(_ t: Double) -> EclipseFrame {
        var canvas = EclipseCanvas()
        let clip = CGPath(rect: CGRect(x: -10, y: -10, width: 140, height: hy + 10), transform: nil)
        canvas.line(starsPath(t))
        canvas.line(comet(t))
        var sky = EclipseCanvas()
        moon(t, into: &sky)
        sun(t, into: &sky)
        canvas.tint = canvas.tint.union(sky.tint.intersection(clip))
        canvas.ink = canvas.ink.subtracting(sky.tint.intersection(clip)).union(sky.ink.intersection(clip))
        for i in 0..<clouds.count { cloud(t, i, into: &canvas) }
        let h = CGMutablePath()
        h.move(to: CGPoint(x: 18, y: hy))
        h.addLine(to: CGPoint(x: 102, y: hy))
        canvas.line(stroked(h, 4, cap: .round))
        return EclipseFrame(tint: canvas.tint, ink: canvas.ink)
    }
}

extension FlairLayer {
    func buildEclipse() {
        let unit = side
        let k = unit / 110
        let frames = EclipseModel.frames
        let duration = EclipseModel.duration
        let steps = EclipseModel.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 }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func paths(_ pick: (EclipseFrame) -> 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 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)
    }
}
