import KHMeshGradient
import SwiftUI
import UIKit

// Fixed sRGB values match the article's captured fixtures. UIColor semantic
// palettes can resolve differently across OS versions and appearances.
enum MeshExamples {
	static let purple: UIColor = UIColor(red: 0.686, green: 0.322, blue: 0.871, alpha: 1)
	static let mint: UIColor = UIColor(red: 0, green: 0.78, blue: 0.745, alpha: 1)
	static let orange: UIColor = UIColor(red: 1, green: 0.584, blue: 0, alpha: 1)
	static let blue: UIColor = UIColor(red: 0, green: 0.478, blue: 1, alpha: 1)
	static let pink: UIColor = UIColor(red: 1, green: 0.176, blue: 0.333, alpha: 1)
	static let yellow: UIColor = UIColor(red: 1, green: 0.8, blue: 0, alpha: 1)
	static let indigo: UIColor = UIColor(red: 0.345, green: 0.337, blue: 0.839, alpha: 1)
	static let corners: [UIColor] = [purple, mint, orange, blue]
	static let rainbow: [UIColor] = [UIColor.red, purple, indigo, orange, UIColor.white, blue, yellow, UIColor.green, mint]
	static let organicColors: [UIColor] = [
		purple, indigo, purple, yellow,
		pink, purple, pink, yellow,
		orange, pink, yellow, orange,
		yellow, orange, pink, purple,
	]
	static let grid: [SIMD2<Float>] = [
		[0, 0], [0.5, 0], [1, 0],
		[0, 0.5], [0.5, 0.5], [1, 0.5],
		[0, 1], [0.5, 1], [1, 1],
	]
	static let organicPoints: [SIMD2<Float>] = [
		[0, 0], [0.3, 0], [0.7, 0], [1, 0],
		[0, 0.3], [0.2, 0.4], [0.7, 0.2], [1, 0.3],
		[0, 0.7], [0.3, 0.8], [0.7, 0.6], [1, 0.7],
		[0, 1], [0.3, 1], [0.7, 1], [1, 1],
	]

	static func makeUIKitGradient(points: [SIMD2<Float>], colors: [UIColor], width: Int, height: Int) -> KHMeshGradientView {
		let gradient: KHMeshGradientView = KHMeshGradientView()
		gradient.meshSize = KHMeshGradientView.MeshSize(width: width, height: height)
		gradient.points = points.map({ (point: SIMD2<Float>) -> CGPoint in CGPoint(x: CGFloat(point.x), y: CGFloat(point.y)) })
		gradient.colors = colors
		gradient.colorSpace = KHMeshGradientView.ColorSpace.device
		return gradient
	}

	static func makeUIKitRainbow() -> KHMeshGradientView {
		return self.makeUIKitGradient(points: self.grid, colors: self.rainbow, width: 3, height: 3)
	}

	static func makeUIKitOrganic() -> KHMeshGradientView {
		return self.makeUIKitGradient(points: self.organicPoints, colors: self.organicColors, width: 4, height: 4)
	}

	static func explicitHandles() -> [KHMeshGradientView.BezierPoint] {
		let points: [CGPoint] = [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 1), CGPoint(x: 1, y: 1)]
		var handles: [KHMeshGradientView.BezierPoint] = points.map({ (point: CGPoint) -> KHMeshGradientView.BezierPoint in
			KHMeshGradientView.BezierPoint(position: point, leadingControlPoint: point, topControlPoint: point, trailingControlPoint: point, bottomControlPoint: point)
		})
		handles[2].topControlPoint = CGPoint(x: 0, y: 0.4)
		handles[2].trailingControlPoint = CGPoint(x: 0.9, y: 1)
		return handles
	}

	static func makeUIKitBezier() -> KHMeshGradientView {
		let gradient: KHMeshGradientView = KHMeshGradientView()
		gradient.meshSize = KHMeshGradientView.MeshSize(width: 2, height: 2)
		gradient.bezierPoints = self.explicitHandles()
		gradient.colors = self.corners
		return gradient
	}
}

@available(iOS 18.0, *)
struct FourCornerMesh: View {
	var body: some View {
		MeshGradient(width: 2, height: 2, points: [[0, 0], [1, 0], [0, 1], [1, 1]], colors: MeshExamples.corners.map({ (color: UIColor) -> Color in Color(uiColor: color) }), colorSpace: Gradient.ColorSpace.device)
	}
}

@available(iOS 18.0, *)
struct RainbowMesh: View {
	var body: some View {
		MeshGradient(width: 3, height: 3, points: MeshExamples.grid, colors: MeshExamples.rainbow.map({ (color: UIColor) -> Color in Color(uiColor: color) }), colorSpace: Gradient.ColorSpace.device)
	}
}

@available(iOS 18.0, *)
struct OrganicMesh: View {
	var body: some View {
		MeshGradient(width: 4, height: 4, points: MeshExamples.organicPoints, colors: MeshExamples.organicColors.map({ (color: UIColor) -> Color in Color(uiColor: color) }), colorSpace: Gradient.ColorSpace.device)
	}
}

@available(iOS 18.0, *)
struct ExplicitBezierMesh: View {
	var body: some View {
		MeshGradient(width: 2, height: 2, bezierPoints: MeshExamples.explicitHandles().map({ (point: KHMeshGradientView.BezierPoint) -> MeshGradient.BezierPoint in
			MeshGradient.BezierPoint(position: Self.vector(point.position), leadingControlPoint: Self.vector(point.leadingControlPoint), topControlPoint: Self.vector(point.topControlPoint), trailingControlPoint: Self.vector(point.trailingControlPoint), bottomControlPoint: Self.vector(point.bottomControlPoint))
		}), colors: MeshExamples.corners.map({ (color: UIColor) -> Color in Color(uiColor: color) }), colorSpace: Gradient.ColorSpace.device)
	}
	private static func vector(_ point: CGPoint) -> SIMD2<Float> { SIMD2<Float>(Float(point.x), Float(point.y)) }
}

// Time-driven motion, evaluated from absolute time rather than a fixed frame step.
// Apply a suitable .frame(...) where this view is used.
@available(iOS 18.0, *)
struct FlowingMesh: View {
	var body: some View {
		TimelineView(AnimationTimelineSchedule(), content: { (context: TimelineViewDefaultContext) in
			let t: Double = context.date.timeIntervalSinceReferenceDate
			let center: SIMD2<Float> = SIMD2<Float>(0.5 + 0.18 * Float(sin(t * 0.7)), 0.5 + 0.18 * Float(cos(t * 0.9)))
			MeshGradient(width: 3, height: 3, points: [
				[0, 0], [0.5, 0], [1, 0],
				[0, 0.5], center, [1, 0.5],
				[0, 1], [0.5, 1], [1, 1],
			], colors: MeshExamples.rainbow.map({ (color: UIColor) -> Color in Color(uiColor: color) }), colorSpace: Gradient.ColorSpace.device)
		})
	}
}

// Pass a configured 3 × 3 view, such as MeshExamples.makeUIKitRainbow().
// Store it and lay it out in the owning UIView's layoutSubviews().
func startUIKitPulse(_ gradient: KHMeshGradientView) {
	UIView.animate(withDuration: 4, delay: 0, options: [UIView.AnimationOptions.autoreverse, UIView.AnimationOptions.repeat, UIView.AnimationOptions.curveEaseInOut], animations: {
		gradient.points[4] = CGPoint(x: 0.68, y: 0.32)
		gradient.colors[4] = MeshExamples.pink
	}, completion: nil)
}

// Standalone functions shown in the side-by-side comparison.
@available(iOS 18.0, *)
func makeSwiftUIMesh(
    palette: [UIColor]
) -> some View {
    let points: [SIMD2<Float>] = [
        [0, 0], [1, 0],
        [0, 1], [1, 1]
    ]
    let colors: [Color] = palette.map({
        (color: UIColor) -> Color in
        Color(uiColor: color)
    })
    return MeshGradient(
        width: 2, height: 2,
        points: points,
        colors: colors,
        colorSpace: Gradient.ColorSpace.device
    )
    .frame(width: 360, height: 240)
}

func makeUIKitMesh(
    palette: [UIColor]
) -> KHMeshGradientView {
    let gradient: KHMeshGradientView =
        KHMeshGradientView()
    gradient.meshSize =
        KHMeshGradientView.MeshSize(
            width: 2, height: 2
        )
    gradient.points = [
        CGPoint(x: 0, y: 0),
        CGPoint(x: 1, y: 0),
        CGPoint(x: 0, y: 1),
        CGPoint(x: 1, y: 1)
    ]
    gradient.colors = palette
    gradient.colorSpace =
        KHMeshGradientView.ColorSpace.device
    gradient.frame = CGRect(
        x: 0, y: 0,
        width: 360, height: 240
    )
    return gradient
}
