#!/usr/bin/gjs
const { Gtk, Gdk, Gio, GLib, GObject, St } = imports.gi;

Gtk.init(null);

// --- CONFIGURATIE ---
const CSS_PATH = '/usr/share/crystal-de/styles/crystal.css';

// --- CSS LADEN ---
const cssProvider = new Gtk.CssProvider();
try {
    cssProvider.load_from_path(CSS_PATH);
    Gtk.StyleContext.add_provider_for_screen(
        Gdk.Screen.get_default(),
        cssProvider,
        Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
    );
} catch (e) { log("CSS Error: " + e); }

// ============================================================
// COMPONENT 1: HET START MENU (Native Grid)
// ============================================================
class StartMenu {
    constructor() {
        this.window = new Gtk.Window({
            type: Gtk.WindowType.POPUP, // Popup, geen randen
            title: "Crystal Start"
        });
        this.window.set_name("crystal-start-menu");
        this.window.set_default_size(500, 400);
        this.window.set_position(Gtk.WindowPosition.CENTER); // Wordt later verplaatst
        
        // Container
        this.scroll = new Gtk.ScrolledWindow();
        this.scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC);
        this.grid = new Gtk.FlowBox({ 
            valign: Gtk.Align.START,
            max_children_per_line: 5,
            selection_mode: Gtk.SelectionMode.NONE 
        });
        this.grid.set_column_spacing(10);
        this.grid.set_row_spacing(10);
        
        this.scroll.add(this.grid);
        this.window.add(this.scroll);
        
        this.populate();
    }

    populate() {
        // Haal alle geïnstalleerde apps op
        let appInfo = Gio.AppInfo.get_all();
        
        appInfo.forEach(app => {
            if (app.should_show()) {
                let btn = new Gtk.Button();
                btn.get_style_context().add_class("app-grid-item");
                
                let box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL, spacing: 5 });
                
                // Icoon ophalen
                let icon = app.get_icon();
                let image = new Gtk.Image({ pixel_size: 48 });
                if (icon) {
                    image.set_from_gicon(icon, Gtk.IconSize.DIALOG);
                } else {
                    image.set_from_icon_name("application-x-executable", Gtk.IconSize.DIALOG);
                }
                
                let label = new Gtk.Label({ label: app.get_name(), max_width_chars: 10, ellipsize: 3 });
                label.get_style_context().add_class("app-label");
                
                box.add(image);
                box.add(label);
                btn.add(box);
                
                btn.connect("clicked", () => {
                    app.launch([], null);
                    this.toggle();
                });
                
                this.grid.add(btn);
            }
        });
        this.grid.show_all();
    }

    toggle(panelWindow) {
        if (this.window.is_visible()) {
            this.window.hide();
        } else {
            // Positioneer links onderaan, boven de startknop
            if (panelWindow) {
                let [x, y] = panelWindow.get_position();
                let [w, h] = panelWindow.get_size();
                // Plaats menu 10px boven de balk
                this.window.move(10, y - 410); 
            }
            this.window.show_all();
        }
    }
}

// ============================================================
// COMPONENT 2: DE TAAKBALK (Windows Style Panel)
// ============================================================
let menu = new StartMenu();

let win = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL, title: "Crystal Panel" });
win.set_type_hint(Gdk.WindowTypeHint.DOCK);
win.set_name("crystal-panel-window");
win.set_decorated(false);
win.set_keep_above(true);

// Full width layout
let screen = win.get_screen();
let monitor = screen.get_primary_monitor();
let geo = screen.get_monitor_geometry(monitor);
win.set_default_size(geo.width, 48);
win.move(0, geo.height - 48); // Onderaan het scherm

// Main Box: Left (Start), Center (Tasks), Right (Status)
let mainBox = new Gtk.Box({ orientation: Gtk.Orientation.HORIZONTAL, spacing: 0 });
mainBox.get_style_context().add_class("crystal-panel-container");

// --- 1. START KNOP ---
let startBtn = new Gtk.Button();
startBtn.set_name("start-button");
let startIcon = new Gtk.Image({ icon_name: "alinux-crystal", pixel_size: 24 }); // Zorg dat dit icoon bestaat!
startBtn.set_image(startIcon);
startBtn.connect("clicked", () => {
    menu.toggle(win);
});

// --- 2. TASK LIST (Pinned Apps) ---
let taskBox = new Gtk.Box({ orientation: Gtk.Orientation.HORIZONTAL, spacing: 5 });
taskBox.get_style_context().add_class("task-box");

function createLauncher(icon, cmd) {
    let btn = new Gtk.Button();
    btn.set_image(new Gtk.Image({ icon_name: icon, pixel_size: 24 }));
    btn.get_style_context().add_class("task-btn");
    btn.connect("clicked", () => {
        try { GLib.spawn_command_line_async(cmd); } catch(e) { log(e); }
    });
    return btn;
}

taskBox.add(createLauncher("firefox-esr", "firefox"));
taskBox.add(createLauncher("utilities-terminal", "gnome-terminal"));
taskBox.add(createLauncher("system-file-manager", "thunar"));
taskBox.add(createLauncher("preferences-system", "gnome-control-center"));

// --- 3. STATUS TRAY (Rechts) ---
let statusBox = new Gtk.Box({ orientation: Gtk.Orientation.HORIZONTAL, spacing: 10 });
statusBox.get_style_context().add_class("status-box");

// Klok
let clockLabel = new Gtk.Label({ label: "..." });
clockLabel.get_style_context().add_class("clock-label");
GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1000, () => {
    clockLabel.set_text(new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}));
    return true;
});
statusBox.add(clockLabel);

// Layout samenvoegen
// Gebruik Box packing: Start (Links), Center (Leeg/Spacer), End (Rechts)
mainBox.pack_start(startBtn, false, false, 0);
mainBox.pack_start(taskBox, false, false, 10); // 10px spacing na startknop
mainBox.pack_end(statusBox, false, false, 0);

win.add(mainBox);
win.show_all();

// Zorg dat het panel op alle monitoren breedte pakt bij resize
screen.connect("monitors-changed", () => {
    let newGeo = screen.get_monitor_geometry(screen.get_primary_monitor());
    win.resize(newGeo.width, 48);
    win.move(0, newGeo.height - 48);
});

Gtk.main();
