#ifndef GAME_ENGINE_H
#define GAME_ENGINE_H

#include <wx/wx.h>
#include <wx/timer.h>
#include <wx/event.h>
#include <vector>
#include <memory>
#include <functional>

extern "C" {
struct lua_State;
}

namespace wherigo {

// Custom event for game state changes
class GameStateEvent : public wxEvent {
public:
  GameStateEvent(wxEventType eventType = wxEVT_NULL, int id = 0)
      : wxEvent(id, eventType) {}

  wxEvent* Clone() const override { return new GameStateEvent(*this); }
};

wxDECLARE_EVENT(EVT_GAME_STATE_CHANGED, GameStateEvent);

class GameEngine : public wxEvtHandler {
public:
  static GameEngine& getInstance();

  void init(lua_State *L, int cartridgeRef);
  void shutdown();

  void start();
  void stop();

  void updatePlayerPosition(double lat, double lng, double alt = 0.0);

  // Notify listeners that game state has changed
  void notifyStateChanged();
  void rebuildPlayerInventory();

  lua_State* getLuaState() const { return m_luaState; }
  int getCartridgeRef() const { return m_cartridgeRef; }

private:
  GameEngine();
  ~GameEngine();

  GameEngine(const GameEngine&) = delete;
  GameEngine& operator=(const GameEngine&) = delete;

  void onGameTick(wxTimerEvent& event);
  void checkTimers();
  void checkZones();

  lua_State* m_luaState = nullptr;
  int m_cartridgeRef = -1;

  wxTimer m_gameTimer;
  bool m_running = false;

  double m_playerLat = 0.0;
  double m_playerLng = 0.0;
  double m_playerAlt = 0.0;

  bool m_isProcessing = false;

  wxDECLARE_EVENT_TABLE();
};

} // namespace wherigo

#endif // GAME_ENGINE_H

