const std = @import("std");
const dvui = @import("dvui");
const SDLBackend = @import("sdl-backend");
const WindowContext = @import("WindowContext.zig");
const ui = @import("ui/frame.zig");

pub fn main() !void {
    // std.heap.GeneralPurposeAllocator was renamed to DebugAllocator recently.
    var gpa: std.heap.DebugAllocator(.{}) = .init;
    defer _ = gpa.deinit();

    const allocator = gpa.allocator();

    var backend = try SDLBackend.initWindow(.{
        .allocator = allocator,
        .size = .{ .w = 800.0, .h = 600.0 },
        .title = "My DVUI App",
        .vsync = true,
    });
    defer backend.deinit();

    var win = try dvui.Window.init(@src(), allocator, backend.backend(), .{
        .theme = switch (backend.preferredColorScheme() orelse .light) {
            .light => dvui.Theme.builtin.adwaita_light,
            .dark => dvui.Theme.builtin.adwaita_dark,
        },
    });
    defer win.deinit();

    var ctx = try WindowContext.init(allocator);
    defer ctx.deinit();

    var interrupted = false;
    main_loop: while (true) {
        const nstime = win.beginWait(interrupted);
        try win.begin(nstime);
        try backend.addAllEvents(&win);

        _ = SDLBackend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
        _ = SDLBackend.c.SDL_RenderClear(backend.renderer);

        if (!ui.guiFrame(&ctx)) break :main_loop;

        const end_micros = try win.end(.{});
        try backend.setCursor(win.cursorRequested());
        try backend.textInputRect(win.textInputRequested());
        try backend.renderPresent();

        const wait_event_micros = win.waitTime(end_micros);
        interrupted = try backend.waitEventTimeout(wait_event_micros);
    }
}
