#include "styles.h"
#include "clay_renderer_raylib.c"
#include "raylib.h"
#include "library.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define CLAY_IMPLEMENTATION
#include "clay.h"

Clay_LayoutConfig const APPLICATION_LAYOUT = {
    .sizing={
        .width=CLAY_SIZING_GROW(),
        .height=CLAY_SIZING_GROW()
    },
    .childGap=16,
    .layoutDirection=CLAY_LEFT_TO_RIGHT
};

Color const BACKGROUND_COLOR = {220.f, 226.f, 233.f, 255.f};

bool static clay_debug_enabled = false;

void handle_clay_errors(Clay_ErrorData error) {
    printf("Clay Error: %s\n", error.errorText.chars);
    abort();
}

void init_clay(Clay_Arena *o_arena) {
    uint64_t memory_required = Clay_MinMemorySize();
    *o_arena = Clay_CreateArenaWithCapacityAndMemory(memory_required, malloc(memory_required));
    Clay_SetMeasureTextFunction(Raylib_MeasureText);
    Clay_Initialize(*o_arena,
                    (Clay_Dimensions){
                        (float)GetScreenWidth(),
                        (float)GetScreenHeight()},
                    (Clay_ErrorHandler){handle_clay_errors});
    Clay_Raylib_Initialize(1920, 1080, "DataComp", FLAG_VSYNC_HINT | FLAG_WINDOW_RESIZABLE | FLAG_WINDOW_HIGHDPI | FLAG_MSAA_4X_HINT);
    Raylib_fonts[0] = (Raylib_Font){
        .font = LoadFontEx("resources/Inter-Regular.ttf", 48, NULL, 400),
        .fontId = 0
    };
    SetTextureFilter(Raylib_fonts[0].font.texture, TEXTURE_FILTER_BILINEAR);
}

Clay_RenderCommandArray create_layout() {
    Clay_BeginLayout();
    CLAY(CLAY_ID("ApplicationContainer"),
        CLAY_LAYOUT(APPLICATION_LAYOUT)) {
        render_composit_library();
    }
    return Clay_EndLayout();
}

void update_ui() {
    if(IsKeyPressed(KEY_D) && IsKeyDown(KEY_LEFT_CONTROL))
        Clay_SetDebugModeEnabled(clay_debug_enabled = !clay_debug_enabled);
    Vector2 const scroll_delta = GetMouseWheelMoveV();
    Vector2 const mouse_position = GetMousePosition();
    Clay_SetPointerState((Clay_Vector2){mouse_position.x, mouse_position.y}, IsMouseButtonDown(0));
    Clay_SetLayoutDimensions((Clay_Dimensions){.width=(float)GetScreenWidth(), .height=(float)GetScreenHeight()});
    Clay_UpdateScrollContainers(true, (Clay_Vector2){scroll_delta.x, scroll_delta.y}, GetFrameTime());
}

int main(void) {
    Clay_Arena clay_mem;
    init_clay(&clay_mem);
    while(!WindowShouldClose()) {
        update_ui();
        Clay_RenderCommandArray commands = create_layout();
        BeginDrawing();
        ClearBackground(BACKGROUND_COLOR);
        Clay_Raylib_Render(commands);
        EndDrawing();
    }
    return 0;
}
