#pragma once

#include "lumacs/ui_interface.hpp"
#include "lumacs/gtk_renderer.hpp"
#include "lumacs/window.hpp"
#include "lumacs/editor_core.hpp"
#include "lumacs/face.hpp"
#include "lumacs/completion_common.hpp" // For CompletionCandidate

#include <chrono> // For std::chrono
#include <gtkmm.h>
#include <pangomm.h>
#include <memory>
#include <vector>
#include <map>

namespace lumacs {

// Forward declarations
class EditorCore;
class Window;
class GtkCompletionPopup; // Forward declaration

// Custom Gtk::ApplicationWindow to make constructor public
class LumacsWindow : public Gtk::ApplicationWindow {
public:
    explicit LumacsWindow(const Glib::RefPtr<Gtk::Application>& application);
};

class GtkEditor : public IEditorView {
public:
    GtkEditor();
    ~GtkEditor() override;

    void init() override;
    void run() override;
    void handle_editor_event(EditorEvent event) override;
    void set_core(EditorCore* core) override;

    void queue_redraw_all_windows(Gtk::Widget* widget);

private:
    EditorCore* core_;
    std::shared_ptr<Window> cached_active_window_;

    Glib::RefPtr<Gtk::Application> app_;
    Gtk::Window* window_ = nullptr;
    Gtk::DrawingArea* drawing_area_ = nullptr; // Raw pointer to the main drawing area if single window
    Gtk::Widget* content_widget_ = nullptr; // The root widget of the editor content (Paned or DrawingArea)
    
    // For cursor blinking logic
    bool cursor_visible_ = true;
    sigc::connection cursor_timer_connection_;
    std::chrono::steady_clock::time_point last_cursor_move_time_;
    static constexpr std::chrono::milliseconds BLINK_INTERVAL = std::chrono::milliseconds(500);
    static constexpr std::chrono::milliseconds BLINK_STATIONARY_THRESHOLD = std::chrono::milliseconds(1000); // 1 second

    std::unique_ptr<GtkRenderer> gtk_renderer_;
    std::unique_ptr<GtkCompletionPopup> completion_popup_; // Completion popup


protected:
    void on_activate();
    void on_draw(const Cairo::RefPtr<Cairo::Context>& cr, int width, int height);
    bool on_cursor_blink();
    void rebuild_layout();
    Gtk::Widget* create_widget_for_layout_node(std::shared_ptr<LayoutNode> node);

    // Completion popup helpers
    void show_completion_popup();
    void hide_completion_popup();
    void on_completion_selected(CompletionCandidate candidate);
    void on_completion_cancelled();

    // Global key event handler
    std::string get_lumacs_key_name(guint keyval, Gdk::ModifierType state);
    bool on_global_key_pressed(guint keyval, guint keycode, Gdk::ModifierType state);
};

std::unique_ptr<IEditorView> create_gtk_editor();

} // namespace lumacs