#pragma once
#include <wx/wx.h>
#include <wx/listbox.h>
#include <wx/notebook.h>
#include <wx/choice.h>
#include <vector>
#include <string>
#include "panels/PiecePreviewPopup.h"
#include "canvas/CanvasState.h"

class MainFrame;
class TrackIconGrid;   // defined in PalettePanel.cpp

class PalettePanel : public wxPanel {
public:
    PalettePanel(wxWindow* parent, MainFrame* frame);
    void Populate();
    void LoadLibrary();
    void SelectSystemForLayout(const MC::CanvasState& state);
    wxString CurrentLibraryFolder() const;

    // Called by TrackIconGrid
    void NotifySelectionChanged(const std::string& catNum);
    void NotifyDoubleClick(const std::string& catNum);
    void NotifyHover(const std::string& catNum, const wxPoint& clientPt, wxWindow* gridWin);
    void NotifyDrag(const std::string& catNum);

private:
    void BuildUI();
    void AddSection(wxListBox* list, std::vector<std::string>& cats,
                    const wxString& label,
                    const std::vector<std::string>& catNums);
    void AddHelixSection(wxListBox* list, std::vector<std::string>& cats,
                         const wxString& label,
                         const std::vector<std::pair<std::string,std::string>>& helixes);
    void PopulateForSystem(int sysIdx);
    void PopulateScenery();
    void PopulateSignals();
    void UpdateSceneryTabVisibility(int sysIdx);

    void OnSystemChanged(wxCommandEvent&);
    void OnItemActivated(wxCommandEvent&);
    void OnLibraryActivated(wxCommandEvent&);
    void OnLibraryRightClick(wxContextMenuEvent&);
    void OnSceneryActivated(wxCommandEvent&);
    void OnListMouseDown(wxMouseEvent&);
    void OnListMouseMove(wxMouseEvent&);
    void OnListMouseHover(wxMouseEvent&);
    void OnSceneryMouseDown(wxMouseEvent&);
    void OnSceneryMouseMove(wxMouseEvent&);

    std::string SelectedCatalogNumber() const;
    std::string SelectedSceneryId() const;

    MainFrame*      m_frame       = nullptr;
    wxChoice*       m_sysChoice   = nullptr;
    wxNotebook*     m_notebook    = nullptr;
    TrackIconGrid*  m_iconGrid    = nullptr;   // replaces m_listTrack
    wxListBox*      m_listTrack   = nullptr;   // kept as nullptr; some call sites reference it
    wxListBox*      m_listLib     = nullptr;
    wxListBox*      m_listScenery = nullptr;
    wxListBox*      m_listSignals = nullptr;

    std::vector<std::string> m_catTrack;
    std::vector<std::string> m_libFiles;
    std::vector<std::string> m_sceneryIds;
    std::vector<std::string> m_signalIds;

    bool m_scenerySheetAttached = true;
    bool               m_justDoubleClicked = false;
    PiecePreviewPopup* m_preview           = nullptr;
    int                m_lastHoverIdx      = -1;

    wxDECLARE_EVENT_TABLE();
};
