#pragma once

#include "pxl8_dither.h"
#include "pxl8_types.h"

#ifdef __cplusplus
extern "C" {
#endif

#define PXL8_LIGHT_COLORS 8
#define PXL8_LIGHT_LEVELS 8
#define PXL8_LIGHT_ROWS (PXL8_LIGHT_COLORS * PXL8_LIGHT_LEVELS)
#define PXL8_BLEND_ROWS 256
#define PXL8_COLORMAP_ROWS (PXL8_LIGHT_ROWS + PXL8_BLEND_ROWS)
#define PXL8_COLORMAP_SIZE (256 * PXL8_COLORMAP_ROWS)

#define PXL8_FULLBRIGHT_START 240
#define PXL8_TRANSPARENT 0
#define PXL8_DYNAMIC_RANGE_START 144
#define PXL8_DYNAMIC_RANGE_COUNT 16

typedef enum {
    PXL8_LIGHT_WHITE = 0,
    PXL8_LIGHT_RED = 1,
    PXL8_LIGHT_ORANGE = 2,
    PXL8_LIGHT_YELLOW = 3,
    PXL8_LIGHT_GREEN = 4,
    PXL8_LIGHT_CYAN = 5,
    PXL8_LIGHT_BLUE = 6,
    PXL8_LIGHT_PURPLE = 7,
} pxl8_light_color;

typedef struct {
    u8 r, g, b;
} pxl8_rgb;

static const pxl8_rgb pxl8_light_colors[PXL8_LIGHT_COLORS] = {
    {255, 255, 255},
    {255, 64, 64},
    {255, 160, 64},
    {255, 255, 64},
    {64, 255, 64},
    {64, 255, 255},
    {64, 64, 255},
    {255, 64, 255},
};

typedef struct {
    u8 table[PXL8_COLORMAP_SIZE];
} pxl8_colormap;

void pxl8_colormap_generate(pxl8_colormap* cm, const u32* palette);
void pxl8_set_colormap(pxl8_colormap* cm, const u8* data, u32 size);

static inline u8 pxl8_colormap_lookup(const pxl8_colormap* cm, u8 pal_idx, pxl8_light_color light_color, u8 intensity) {
    u32 light_row = ((u32)light_color << 3) + (intensity >> 5);
    return cm->table[(light_row << 8) + pal_idx];
}

static inline u8 pxl8_colormap_lookup_dithered(const pxl8_colormap* cm, u8 pal_idx, pxl8_light_color light_color, u8 intensity, u32 x, u32 y) {
    u8 dithered = pxl8_dither_light(intensity, x, y);
    u32 light_row = ((u32)light_color << 3) + (dithered >> 5);
    return cm->table[(light_row << 8) + pal_idx];
}

static inline u8 pxl8_colormap_blend(const pxl8_colormap* cm, u8 src, u8 dst) {
    u32 blend_row = PXL8_LIGHT_ROWS + src;
    return cm->table[(blend_row << 8) + dst];
}

#ifdef __cplusplus
}
#endif
