import QuartzCore
import Foundation

private struct BookPart {
    let stroke: CGPath
    let strong: CGPath
    let weak: CGPath
    let weakOpacity: Float
}

private struct BookFrame {
    let baseRing: CGPath
    let leftCover: CGPath
    let baseCoverStroke: CGPath
    let leftCoverStroke: CGPath
    let parts: [BookPart]
    let burst: CGPath
    let hideBase: CGPath
    let hideLeft: CGPath
}

private enum BookModel {
    static let duration = 3.6
    static let count = 120
    static let span = 38.0
    static let depth = 0.72
    static let riffleStarts = [0.98, 1.07, 1.16, 1.25]
    static let manualStarts = [1.52, 1.92]
    nonisolated(unsafe) static let frames: [BookFrame] = (0..<count).map { build(Double($0) * duration / Double(count)) }

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let c = clamp(u); return c * c * (3 - 2 * c) }
    static func eio(_ u: Double) -> Double { let c = clamp(u); return c * c * c * (c * (6 * c - 15) + 10) }
    static func ytop(_ u: Double) -> Double { 46.5 - 4 * u + 2.5 * u * u }
    static func ybot(_ u: Double) -> Double { 84.5 - 3 * u + 2.5 * u * u }

    static func compose(_ steps: [CGAffineTransform]) -> CGAffineTransform {
        var result = CGAffineTransform.identity
        for item in steps.reversed() { result = result.concatenating(item) }
        return result
    }

    static func place(_ d: Double, _ y: Double, _ phi: Double, _ dy: Double) -> CGPoint {
        CGPoint(x: 50 + d * cos(phi), y: y + dy - d * sin(phi) * depth)
    }

    static func bez(_ p: [CGPoint], _ t: Double) -> CGPoint {
        let m = 1 - t
        return CGPoint(
            x: m * m * m * p[0].x + 3 * m * m * t * p[1].x + 3 * m * t * t * p[2].x + t * t * t * p[3].x,
            y: m * m * m * p[0].y + 3 * m * m * t * p[1].y + 3 * m * t * t * p[2].y + t * t * t * p[3].y
        )
    }

    static func sheet(_ th: Double, _ lead: Double, wd: Double = span, top: Double = 0, bot: Double = 0, dy: Double = 0, rad: Double = 4.5) -> CGPath {
        func edge(_ f: (Double) -> Double) -> [CGPoint] {
            [place(0, f(0), th, dy), place(wd * 0.4, f(0.4), th + lead, dy), place(wd * 0.8, f(0.8), th + lead * 0.5, dy), place(wd, f(1), th, dy)]
        }
        let a = edge { ytop($0) - top }
        let b = edge { ybot($0) + bot }
        let n = 18
        let tp = (0...n).map { bez(a, Double($0) / Double(n)) }
        let bp = (0...n).map { bez(b, Double($0) / Double(n)) }
        let poly = tp + bp.reversed()
        let corners: [Int: Double] = [0: 1.5, n: rad, n + 1: rad, 2 * n + 1: 1.5]
        func toward(_ p: CGPoint, _ q: CGPoint, _ r: Double) -> CGPoint {
            let dx = Double(q.x - p.x), dy2 = Double(q.y - p.y)
            let l = hypot(dx, dy2)
            let rr = min(r, l * 0.45)
            return CGPoint(x: Double(p.x) + dx / l * rr, y: Double(p.y) + dy2 / l * rr)
        }
        let m = poly.count
        let path = CGMutablePath()
        for (i, p) in poly.enumerated() {
            if let r = corners[i] {
                let s = toward(p, poly[(i - 1 + m) % m], r)
                let e = toward(p, poly[(i + 1) % m], r)
                if i == 0 { path.move(to: s) } else { path.addLine(to: s) }
                path.addQuadCurve(to: e, control: p)
            } else {
                path.addLine(to: p)
            }
        }
        path.closeSubpath()
        return path
    }

    static func lines(_ th: Double, _ dy: Double) -> CGPath {
        let path = CGMutablePath()
        for (fr, a0, a1) in [(0.22, 0.18, 0.8), (0.4, 0.18, 0.74), (0.58, 0.18, 0.8), (0.76, 0.18, 0.6)] {
            let p = [a0, (a0 + a1) / 2, a1].map { u in place(span * u, ytop(u) + (ybot(u) - ytop(u)) * fr, th, dy) }
            let control = CGPoint(x: 2 * p[1].x - (p[0].x + p[2].x) / 2, y: 2 * p[1].y - (p[0].y + p[2].y) / 2)
            path.move(to: p[0])
            path.addQuadCurve(to: p[2], control: control)
        }
        return path
    }

    static func ring(_ outer: CGPath, _ inner: CGPath) -> CGPath {
        let path = CGMutablePath()
        path.addPath(outer)
        path.addPath(inner)
        return path
    }

    static func spring(_ t: Double, _ t0: Double, _ amp: Double, _ f: Double = 2.8, _ k: Double = 6.0) -> Double {
        let tau = t - t0
        return tau >= 0 ? amp * exp(-k * tau) * cos(2 * .pi * f * tau) : 0
    }

    static func leftUnit(_ t: Double) -> (Double, Double) {
        if t < 0.20 { return (0, 0) }
        if t < 0.34 { let u = ease((t - 0.20) / 0.14); return (0.18 * u, -0.2 * u) }
        if t < 0.74 {
            let u = (t - 0.34) / 0.40
            let e = 0.55 * eio(u) + 0.45 * (1 - (1 - u) * (1 - u))
            return (0.18 + (.pi - 0.18) * e, 0.7 * sin(.pi * u) - 0.2 * (1 - u))
        }
        if t < 2.66 {
            let b = t - 0.74
            return (.pi - 0.16 * exp(-8 * b) * abs(sin(2 * .pi * 2.4 * b)), 0)
        }
        if t < 2.94 {
            let u = (t - 2.66) / 0.28
            let e = pow(u, 2.2)
            return (.pi * (1 - e), -0.75 * sin(.pi * u))
        }
        let b = t - 2.94
        return (0.07 * exp(-9 * b) * abs(sin(2 * .pi * 3 * b)), 0)
    }

    static func riffle(_ t: Double, _ t0: Double) -> (Double, Double)? {
        let u = (t - t0) / 0.27
        if u < 0 || u > 1 { return nil }
        let e = 0.5 * eio(u) + 0.5 * (1 - (1 - u) * (1 - u))
        return (.pi * e, 0.8 * sin(.pi * u))
    }

    static func manual(_ t: Double, _ t0: Double) -> (Double, Double)? {
        let tau = t - t0
        if tau < 0 { return nil }
        if tau < 0.18 { let u = ease(tau / 0.18); return (0.22 * u, -0.28 * u) }
        if tau < 0.54 {
            let u = (tau - 0.18) / 0.36
            let e = 0.55 * eio(u) + 0.45 * (1 - (1 - u) * (1 - u))
            return (0.22 + (.pi - 0.22) * e, 0.7 * sin(.pi * u) - 0.28 * (1 - u) * (1 - u))
        }
        let b = tau - 0.54
        if b > 0.2 { return nil }
        return (.pi - 0.14 * exp(-8 * b) * abs(sin(2 * .pi * 2.6 * b)), 0)
    }

    static func bodySquash(_ t: Double) -> Double {
        var s = 0.0
        if t >= 0.2 && t < 0.34 { s += 0.05 * ease((t - 0.2) / 0.14) } else if t >= 0.34 && t < 0.5 { s += 0.05 * (1 - ease((t - 0.34) / 0.16)) }
        s += spring(t, 0.74, 0.06)
        for r in riffleStarts { s += spring(t, r + 0.27, 0.018, 4, 9) }
        for m in manualStarts { s += spring(t, m + 0.54, 0.04) }
        if t >= 2.5 && t < 2.66 { s += 0.13 * ease((t - 2.5) / 0.16) }
        if t >= 2.66 && t < 3.22 {
            let tau = t - 2.66
            let u = tau / 0.56
            s += 0.13 * (1 - ease(tau / 0.06)) - 0.16 * exp(-7 * tau) * ease(tau / 0.06) - 0.09 * ease((u - 0.55) / 0.45)
        }
        if t >= 3.22 { s += 0.3 * exp(-6.5 * (t - 3.22)) * cos(2 * .pi * 2.6 * (t - 3.22)) }
        return s
    }

    static func air(_ t: Double) -> (Double, Double) {
        if t >= 2.66 && t < 3.22 {
            let u = (t - 2.66) / 0.56
            return (-4 * 17 * u * (1 - u), -9 * sin(.pi * u) + 3 * sin(2 * .pi * u))
        }
        return (0, 0)
    }

    static func burst(_ t: Double) -> CGPath {
        let path = CGMutablePath()
        let tau = t - 2.93
        guard tau >= 0 && tau <= 0.26 else { return path }
        let u = tau / 0.26
        let r0 = 27 + 16 * ease(u)
        let r1 = r0 + 9 * sin(.pi * min(1, u * 1.2))
        for side in [-1.0, 1.0] {
            for a in [-32.0, 0, 32] {
                let th = a * .pi / 180
                let dx = side * cos(th), dyy = sin(th)
                path.move(to: CGPoint(x: 70 + dx * r0, y: 62 + dyy * r0 * 0.9))
                path.addLine(to: CGPoint(x: 70 + dx * r1, y: 62 + dyy * r1 * 0.9))
            }
        }
        return path
    }

    static func build(_ t: Double) -> BookFrame {
        let (thL, leadL) = leftUnit(t)
        let closed = 1 - thL / .pi
        let dyc = -7 * closed
        let cb = 4.5 - 3.5 * closed
        let sq = bodySquash(t)
        let (jy, rot) = air(t)
        let shift = 20.5 * closed
        let body = compose([CGAffineTransform(translationX: 60, y: 92 + jy), CGAffineTransform(rotationAngle: rot * .pi / 180), CGAffineTransform(scaleX: 1 + 0.8 * sq, y: 1 - sq), CGAffineTransform(translationX: -(50 + shift), y: -86)])

        let baseOuter = sheet(0, 0, wd: span + 3.5, top: 1.5, bot: 4.5, rad: 6)
        let basePage = sheet(0, 0)
        let baseRing = ring(baseOuter, basePage)
        let leftOuter = sheet(thL, leadL, wd: span + 3.5, top: 1.5, bot: cb, dy: dyc, rad: 6)
        let leftCover = CGMutablePath()
        let strokes = (0..<3).map { _ in CGMutablePath() }
        let strongs = (0..<3).map { _ in CGMutablePath() }
        let weaks = (0..<3).map { _ in CGMutablePath() }
        var weakAlphas = [0.0, 0.0, 0.0]
        func addLines(_ part: Int, _ th: Double, _ dy: Double, _ alpha: Double) {
            if alpha < 0.02 { return }
            if alpha >= 0.99 { strongs[part].addPath(lines(th, dy)) } else {
                weaks[part].addPath(lines(th, dy))
                weakAlphas[part] = max(weakAlphas[part], alpha)
            }
        }
        strokes[0].addPath(basePage)
        addLines(0, 0, 0, thL > 1.2 ? 1 : 0)
        if thL > .pi / 2 {
            let page = sheet(thL, leadL, dy: dyc)
            leftCover.addPath(ring(leftOuter, page))
            strokes[1].addPath(page)
            addLines(1, thL, dyc, clamp((abs(cos(thL)) - 0.75) / 0.2))
        } else {
            leftCover.addPath(leftOuter)
            let a = place(7, ytop(7 / span) - 0.5, thL, dyc)
            let b = place(7, ybot(7 / span) + cb - 1.5, thL, dyc)
            let len = max(hypot(Double(b.x - a.x), Double(b.y - a.y)), 0.001)
            let nx = -Double(b.y - a.y) / len * 1.3, ny = Double(b.x - a.x) / len * 1.3
            leftCover.move(to: CGPoint(x: Double(a.x) + nx, y: Double(a.y) + ny))
            leftCover.addLine(to: CGPoint(x: Double(b.x) + nx, y: Double(b.y) + ny))
            leftCover.addLine(to: CGPoint(x: Double(b.x) - nx, y: Double(b.y) - ny))
            leftCover.addLine(to: CGPoint(x: Double(a.x) - nx, y: Double(a.y) - ny))
            leftCover.closeSubpath()
        }
        for r in riffleStarts {
            guard let s = riffle(t, r) else { continue }
            strokes[2].addPath(sheet(s.0, s.1))
            addLines(2, s.0, 0, max(clamp((cos(s.0) - 0.8) / 0.2), clamp((-cos(s.0) - 0.9) / 0.1)))
        }
        for m in manualStarts {
            guard let s = manual(t, m) else { continue }
            strokes[2].addPath(sheet(s.0, s.1))
            addLines(2, s.0, 0, clamp((abs(cos(s.0)) - 0.75) / 0.2))
        }
        var hideTop: CGPath = CGMutablePath()
        func cover(_ path: CGPath, _ into: inout CGPath) { into = into.union(path) }
        for r in riffleStarts { if let s = riffle(t, r) { cover(sheet(s.0, s.1), &hideTop) } }
        for m in manualStarts { if let s = manual(t, m) { cover(sheet(s.0, s.1), &hideTop) } }
        var hideBase = hideTop
        cover(leftOuter, &hideBase)
        func moved(_ path: CGPath) -> CGPath {
            var m = body
            return path.copy(using: &m) ?? path
        }
        return BookFrame(
            baseRing: moved(baseRing),
            leftCover: moved(leftCover),
            baseCoverStroke: moved(baseOuter),
            leftCoverStroke: moved(leftOuter),
            parts: (0..<3).map { BookPart(stroke: moved(strokes[$0]), strong: moved(strongs[$0]), weak: moved(weaks[$0]), weakOpacity: Float(weakAlphas[$0])) },
            burst: moved(burst(t)),
            hideBase: moved(hideBase),
            hideLeft: moved(hideTop)
        )
    }
}

extension FlairLayer {
    func buildBook() {
        let unit = side
        let k = unit / 110
        let frames = BookModel.frames
        let duration = BookModel.duration
        let steps = BookModel.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)
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        func paths(_ pick: (BookFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { placed(pick(frames[$0])) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func opacities(_ pick: (BookFrame) -> Float) -> CAKeyframeAnimation {
            let values = (0..<steps).map { NSNumber(value: pick(frames[$0])) }
            let animation = keyframes("opacity", 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

        func underlay(_ pick: @escaping (BookFrame) -> CGPath) -> (CALayer, CAShapeLayer, () -> CAKeyframeAnimation) {
            let holder = container()
            holder.removeFromSuperlayer()
            clipper.addSublayer(holder)
            let mask = CAShapeLayer()
            mask.bounds = CGRect(origin: .zero, size: full)
            mask.position = mid
            mask.fillColor = CGColor(gray: 0, alpha: 1)
            func visible(_ frame: BookFrame) -> CGPath {
                CGPath(rect: CGRect(origin: .zero, size: full), transform: nil).subtracting(placed(pick(frame)), using: .evenOdd)
            }
            mask.path = visible(frames[0])
            holder.mask = mask
            return (holder, mask, {
                let animation = self.keyframes("path", (0..<steps).map { visible(frames[$0]) }, times: times, timing: .linear)
                animation.calculationMode = .discrete
                return animation
            })
        }
        let baseGroup = underlay { $0.hideBase }
        let leftGroup = underlay { $0.hideLeft }
        let baseRing = shape(placed(frames[0].baseRing), size: full, at: mid, in: baseGroup.0)
        baseRing.fillRule = .evenOdd
        let leftCover = shape(placed(frames[0].leftCover), size: full, at: mid, in: leftGroup.0)
        leftCover.fillRule = .evenOdd
        let baseCoverStroke = shape(placed(frames[0].baseCoverStroke), size: full, at: mid, stroke: 3 * k, in: baseGroup.0)
        baseCoverStroke.lineJoin = .round
        let leftCoverStroke = shape(placed(frames[0].leftCoverStroke), size: full, at: mid, stroke: 3 * k, in: leftGroup.0)
        leftCoverStroke.lineJoin = .round
        let hosts = [baseGroup.0, leftGroup.0, clipper]
        var partLayers: [(CAShapeLayer, CAShapeLayer, CAShapeLayer)] = []
        for index in 0..<3 {
            let pageStroke = shape(placed(frames[0].parts[index].stroke), size: full, at: mid, stroke: 3.5 * k, in: hosts[index])
            pageStroke.lineJoin = .round
            let strong = shape(placed(frames[0].parts[index].strong), size: full, at: mid, stroke: 2.6 * k, in: hosts[index])
            strong.lineCap = .round
            let weak = shape(placed(frames[0].parts[index].weak), size: full, at: mid, stroke: 2.6 * k, in: hosts[index])
            weak.lineCap = .round
            weak.opacity = frames[0].parts[index].weakOpacity
            partLayers.append((pageStroke, strong, weak))
        }
        let burst = shape(placed(frames[0].burst), size: full, at: mid, stroke: 3 * k, in: clipper)
        burst.lineCap = .round

        guard animating else { return }
        run(group([baseGroup.2()], duration: duration), on: baseGroup.1)
        run(group([leftGroup.2()], duration: duration), on: leftGroup.1)
        run(group([paths { $0.baseRing }], duration: duration), on: baseRing)
        run(group([paths { $0.leftCover }], duration: duration), on: leftCover)
        run(group([paths { $0.baseCoverStroke }], duration: duration), on: baseCoverStroke)
        run(group([paths { $0.leftCoverStroke }], duration: duration), on: leftCoverStroke)
        for index in 0..<3 {
            run(group([paths { $0.parts[index].stroke }], duration: duration), on: partLayers[index].0)
            run(group([paths { $0.parts[index].strong }], duration: duration), on: partLayers[index].1)
            run(group([paths { $0.parts[index].weak }, opacities { $0.parts[index].weakOpacity }], duration: duration), on: partLayers[index].2)
        }
        run(group([paths { $0.burst }], duration: duration), on: burst)
    }
}
