#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Tabs.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Box.H>
#include <vector>
#include <string>
#include <map>

// straightbrowser 003

// to build
//   get deps
//     e.g apt install libfltk1.3-dev fluid
//   and run
//     fltk-config --compile straightbrowser.cpp

// Global widgets
Fl_Tabs *tabs = nullptr;
Fl_Input *url_input = nullptr;
Fl_Button *go_button = nullptr;
Fl_Box *content_area = nullptr;
std::vector<Fl_Button*> engine_buttons;
std::map<std::string, int> engine_map; // Map engine names to indices
std::vector<std::string> engines = {
    "WebKitGTK", "CEF", "Gecko", "Servo", "Ladybird",
    "Dillo", "Lynx", "Links2", "w3m", "NetSurf"
};
int active_engine = 0; // Default to WebKitGTK

void update_engine_buttons() {
    for (size_t i = 0; i < engine_buttons.size(); ++i) {
        if (i == active_engine) {
            engine_buttons[i]->color(FL_YELLOW); // Highlight active engine
            engine_buttons[i]->redraw();
        } else {
            engine_buttons[i]->color(FL_GRAY);
            engine_buttons[i]->redraw();
        }
    }
}

void engine_callback(Fl_Widget *w, void *data) {
    active_engine = std::stoi((const char*)data);
    update_engine_buttons();
    content_area->copy_label(("Switched to " + engines[active_engine]).c_str());
    content_area->redraw();
}

void go_callback(Fl_Widget *w, void *data) {
    const char *url = url_input->value();
    content_area->copy_label(("Loading " + std::string(url) + " with " + engines[active_engine]).c_str());
    content_area->redraw();
    // TODO: Send URL and active_engine to backend via IPC
}

int main() {
    Fl_Window *window = new Fl_Window(800, 600, "Straight Browser");
    window->begin();

    // Engine switching buttons (top row)
    Fl_Group *engine_group = new Fl_Group(0, 0, 800, 30);
    for (size_t i = 0; i < engines.size(); ++i) {
        Fl_Button *btn = new Fl_Button(10 + i * 80, 0, 75, 25, engines[i].c_str());
        btn->callback(engine_callback, (void*)std::to_string(i).c_str());
        engine_buttons.push_back(btn);
        engine_map[engines[i]] = i; // Map engine name to index
    }
    engine_group->end();
    update_engine_buttons(); // Highlight default engine

    // Tab bar
    tabs = new Fl_Tabs(0, 30, 800, 30);
    {
        Fl_Group *tab1 = new Fl_Group(0, 60, 800, 540, "New Tab");
        tab1->end();
        tabs->end();
    }

    // Address bar
    url_input = new Fl_Input(50, 65, 600, 25, "URL:");
    go_button = new Fl_Button(660, 65, 100, 25, "Go");
    go_button->callback(go_callback);

    // Content area
    content_area = new Fl_Box(50, 100, 700, 450, "Content will appear here.");
    content_area->align(FL_ALIGN_INSIDE | FL_ALIGN_CENTER);

    window->end();
    window->show();
    return Fl::run();
}
