#pragma once

#include "pxl8_types.h"

static inline i32 pxl8_bytes_per_pixel(pxl8_pixel_mode mode) {
    return (i32)mode;
}

static inline u16 pxl8_rgb565_pack(u8 r, u8 g, u8 b) {
    return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
}

static inline void pxl8_rgb565_unpack(u16 color, u8* r, u8* g, u8* b) {
    *r = (color >> 11) << 3;
    *g = ((color >> 5) & 0x3F) << 2;
    *b = (color & 0x1F) << 3;
}

static inline u16 pxl8_rgba32_to_rgb565(u32 rgba) {
    return pxl8_rgb565_pack(rgba & 0xFF, (rgba >> 8) & 0xFF, (rgba >> 16) & 0xFF);
}

static inline u32 pxl8_rgb565_to_rgba32(u16 color) {
    u8 r, g, b;
    pxl8_rgb565_unpack(color, &r, &g, &b);
    return r | ((u32)g << 8) | ((u32)b << 16) | 0xFF000000;
}

static inline void pxl8_rgba32_unpack(u32 color, u8* r, u8* g, u8* b, u8* a) {
    *r = color & 0xFF;
    *g = (color >> 8) & 0xFF;
    *b = (color >> 16) & 0xFF;
    *a = (color >> 24) & 0xFF;
}

static inline u32 pxl8_rgba32_pack(u8 r, u8 g, u8 b, u8 a) {
    return r | ((u32)g << 8) | ((u32)b << 16) | ((u32)a << 24);
}

static inline u32 pxl8_color_to_rgba(u32 abgr) {
    u8 r = abgr & 0xFF;
    u8 g = (abgr >> 8) & 0xFF;
    u8 b = (abgr >> 16) & 0xFF;
    u8 a = (abgr >> 24) & 0xFF;
    return ((u32)r << 24) | ((u32)g << 16) | ((u32)b << 8) | a;
}

static inline u32 pxl8_color_from_rgba(u32 rgba) {
    u8 r = (rgba >> 24) & 0xFF;
    u8 g = (rgba >> 16) & 0xFF;
    u8 b = (rgba >> 8) & 0xFF;
    u8 a = rgba & 0xFF;
    return r | ((u32)g << 8) | ((u32)b << 16) | ((u32)a << 24);
}

static inline u8 pxl8_color_lerp_channel(u8 c1, u8 c2, f32 t) {
    return c1 + (i32)((c2 - c1) * t);
}

static inline u8 pxl8_rgb332_pack(u8 r, u8 g, u8 b) {
    return ((r >> 5) << 5) | ((g >> 5) << 2) | (b >> 6);
}

static inline void pxl8_rgb332_unpack(u8 c, u8* r, u8* g, u8* b) {
    u8 ri = (c >> 5) & 0x07;
    u8 gi = (c >> 2) & 0x07;
    u8 bi = c & 0x03;
    *r = (ri << 5) | (ri << 2) | (ri >> 1);
    *g = (gi << 5) | (gi << 2) | (gi >> 1);
    *b = (bi << 6) | (bi << 4) | (bi << 2) | bi;
}
