import Foundation
import SwiftUI
import simd

struct Palette: Identifiable, Equatable, Hashable {
    let id: String
    let name: String
    let colors: [SIMD4<Float>]

    static func hex(_ value: UInt32) -> SIMD4<Float> {
        let r = Float((value >> 16) & 0xFF) / 255.0
        let g = Float((value >> 8) & 0xFF) / 255.0
        let b = Float(value & 0xFF) / 255.0
        return SIMD4<Float>(r, g, b, 1.0)
    }

    var swiftUIColors: [Color] {
        colors.map { Color(red: Double($0.x), green: Double($0.y), blue: Double($0.z)) }
    }
}

extension Palette {
    static let oneBit = Palette(
        id: "onebit",
        name: "1 Bit",
        colors: [
            hex(0x000000),
            hex(0xFFFFFF)
        ]
    )

    static let gameboy = Palette(
        id: "gameboy",
        name: "DMG",
        colors: [
            hex(0x0F380F),
            hex(0x306230),
            hex(0x8BAC0F),
            hex(0x9BBC0F)
        ]
    )

    static let amber = Palette(
        id: "amber",
        name: "Amber",
        colors: [
            hex(0x1A0F00),
            hex(0x5C3300),
            hex(0xB36B00),
            hex(0xFFB000)
        ]
    )

    static let ice = Palette(
        id: "ice",
        name: "Ice",
        colors: [
            hex(0x0B1026),
            hex(0x1B3A6B),
            hex(0x4A8FC7),
            hex(0xC8E9F5)
        ]
    )

    static let gray4 = Palette(
        id: "gray4",
        name: "Gray 4",
        colors: [
            hex(0x000000),
            hex(0x555555),
            hex(0xAAAAAA),
            hex(0xFFFFFF)
        ]
    )

    static let cga = Palette(
        id: "cga",
        name: "CGA",
        colors: [
            hex(0x000000),
            hex(0x55FFFF),
            hex(0xFF55FF),
            hex(0xFFFFFF)
        ]
    )

    static let ega = Palette(
        id: "ega",
        name: "EGA",
        colors: [
            hex(0x000000),
            hex(0x0000AA),
            hex(0x00AA00),
            hex(0x00AAAA),
            hex(0xAA0000),
            hex(0xAA00AA),
            hex(0xAA5500),
            hex(0xAAAAAA),
            hex(0x555555),
            hex(0x5555FF),
            hex(0x55FF55),
            hex(0x55FFFF),
            hex(0xFF5555),
            hex(0xFF55FF),
            hex(0xFFFF55),
            hex(0xFFFFFF)
        ]
    )

    static let sunset = Palette(
        id: "sunset",
        name: "Sunset",
        colors: [
            hex(0x1B0B2E),
            hex(0x5A1E52),
            hex(0xB33951),
            hex(0xEE6C4D),
            hex(0xF7C59F),
            hex(0xFFF3E6)
        ]
    )

    static let all: [Palette] = [
        .oneBit,
        .gray4,
        .gameboy,
        .amber,
        .ice,
        .cga,
        .sunset,
        .ega
    ]

    static let maximumColors = 16
}
