#include "ui/map_sim_frame.h"
#include <wx/sizer.h>
#include <wx/button.h>
#include <wx/webview.h>
#include <wx/msgdlg.h>
#include <thread>
#include <chrono>

wxBEGIN_EVENT_TABLE(MapSimFrame, wxFrame)
    EVT_WEBVIEW_NAVIGATED(wxID_ANY, MapSimFrame::OnWebViewEvent)
    EVT_BUTTON(wxID_ANY, MapSimFrame::OnPlay)
wxEND_EVENT_TABLE()

MapSimFrame::MapSimFrame(wxWindow* parent, double centerLat, double centerLon, const std::vector<std::pair<double, double>>& zoneCoords)
    : wxFrame(parent, wxID_ANY, "Karten-Simulation", wxDefaultPosition, wxSize(900, 700)), m_zoneCoords(zoneCoords) {
    auto* sizer = new wxBoxSizer(wxVERTICAL);
    m_webView = wxWebView::New(this, wxID_ANY);
    sizer->Add(m_webView, 1, wxEXPAND);
    auto* playBtn = new wxButton(this, wxID_ANY, "Simulation starten");
    sizer->Add(playBtn, 0, wxALL | wxALIGN_CENTER, 8);
    SetSizer(sizer);
    // Leaflet-Karte laden (dynamisch zentriert und Marker)
    wxString html;
    html << "<!DOCTYPE html><html><head><meta charset='utf-8'><title>MapSim</title>"
         "<link rel='stylesheet' href='https://unpkg.com/leaflet/dist/leaflet.css'/>"
         "<script src='https://unpkg.com/leaflet/dist/leaflet.js'></script>"
         "<style>html,body,#map{height:100%%;margin:0;padding:0;}#map{height:600px;}</style>"
         "</head><body><div id='map'></div>"
         "<script>"
         "var map = L.map('map').setView([" << wxString::Format("%.8f, %.8f", centerLat, centerLon) << "], 16);"
         "L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19}).addTo(map);"
         "var markers = [];";
    // Marker für alle Zonen
    for (const auto& z : zoneCoords) {
        html << wxString::Format("var m = L.marker([%.8f, %.8f]).addTo(map); markers.push(m);\n", z.first, z.second);
    }
    html <<
         "map.on('click', function(e) {"
         "  var marker = L.marker(e.latlng).addTo(map);"
         "  markers.push(marker);"
         "  window.wx.postMessage(JSON.stringify({lat: e.latlng.lat, lon: e.latlng.lng}));"
         "});"
         "</script></body></html>";
    m_webView->SetPage(html, "");
}

void MapSimFrame::OnWebViewEvent(wxWebViewEvent& event) {
    // Empfange Marker-Koordinaten von JS
    wxString msg = event.GetString();
    double lat = 0, lon = 0;
    if (msg.ToDouble(&lat)) {
        // Not used, see below
    }
    // In wxWidgets 3.1+ kann man wxWebView::RegisterHandler für JS->C++ nutzen
    // Hier: Marker werden über postMessage als JSON gesendet
    // TODO: JSON parsen und AddSimPoint aufrufen
}

void MapSimFrame::AddSimPoint(double lat, double lon) {
    m_route.push_back({lat, lon});
}

void MapSimFrame::OnPlay(wxCommandEvent&) {
    if (m_route.empty()) {
        wxMessageBox("Bitte zuerst Marker setzen.", "Hinweis", wxOK | wxICON_INFORMATION);
        return;
    }
    // Simuliere Bewegung entlang der Route
    for (const auto& pt : m_route) {
        SendPositionToEngine(pt.lat, pt.lon);
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    wxMessageBox("Simulation beendet.", "Info", wxOK | wxICON_INFORMATION);
}

void MapSimFrame::SendPositionToEngine(double lat, double lon) {
    // TODO: Engine-Integration: GPS-Position setzen
    // Beispiel: wxGetApp().setSimulatedPosition(lat, lon);
}
