/*
    * app.cpp
    * Settings launcher and desktop integration entry points
    * Copyright (c) 2026 Daniel Hammer
*/

#include "settings_internal.hpp"

namespace settings_app {

static void settings_on_draw(Window* win, Framebuffer& fb) {
    SettingsState* st = (SettingsState*)win->app_data;
    if (!st) return;

    mtk::DesktopHost host(win);
    Canvas c = host.canvas();
    mtk::Theme theme = settings_theme(st);
    c.fill(theme.window_bg);
    mtk::draw_tab_bar(c, {0, 0, c.w, TAB_BAR_H}, tab_labels, TAB_COUNT, st->active_tab, theme);

    // Draw tab content below the tab bar
    Canvas content(win->content + TAB_BAR_H * win->content_w,
                   win->content_w, win->content_h - TAB_BAR_H);

    switch (st->active_tab) {
    case 0: settings_draw_appearance(content, st); break;
    case 1: settings_draw_display(content, st); break;
    case 2: settings_draw_about(content, st); break;
    }
}

static void settings_on_mouse(Window* win, MouseEvent& ev) {
    SettingsState* st = (SettingsState*)win->app_data;
    if (!st || !ev.left_pressed()) return;

    mtk::DesktopHost host(win);
    int mx = 0;
    int my = 0;
    if (!host.map_mouse(ev, &mx, &my)) return;

    // Tab bar click
    int tab = mtk::hit_tab_bar({0, 0, win->content_w, TAB_BAR_H}, TAB_COUNT, mx, my);
    if (tab >= 0) {
        st->active_tab = tab;
        return;
    }

    // Content area (offset by TAB_BAR_H)
    int cy = my - TAB_BAR_H;

    switch (st->active_tab) {
    case 0:
        settings_handle_appearance_click(win, st, mx, cy);
        break;
    case 1:
        settings_handle_display_click(st, mx, cy);
        break;
    default:
        break;
    }
}

static void settings_on_key(Window* win, const Montauk::KeyEvent& key) {
    // Settings main window no longer needs keyboard handling.
    (void)win;
    (void)key;
}

static void settings_on_close(Window* win) {
    if (win->app_data) {
        montauk::mfree(win->app_data);
        win->app_data = nullptr;
    }
}

} // namespace settings_app

void open_settings(DesktopState* ds) {
    int idx = desktop_create_window(ds, "Desktop Settings", 200, 100, 480, 420);
    if (idx < 0) return;

    Window* win = &ds->windows[idx];
    settings_app::SettingsState* st =
        (settings_app::SettingsState*)montauk::malloc(sizeof(settings_app::SettingsState));
    montauk::memset(st, 0, sizeof(settings_app::SettingsState));
    st->desktop = ds;
    st->active_tab = 0;
    montauk::get_info(&st->sys_info);
    st->uptime_ms = montauk::get_milliseconds();
    st->wp_scanned = false;
    st->wp_files.count = 0;
    st->status_msg[0] = '\0';

    win->app_data = st;
    win->on_draw = settings_app::settings_on_draw;
    win->on_mouse = settings_app::settings_on_mouse;
    win->on_key = settings_app::settings_on_key;
    win->on_close = settings_app::settings_on_close;
}
