#include "guecs/sfml/backend.hpp"
#include "guecs/sfml/components.hpp"
#include "guecs/ui.hpp"
#include <fmt/xchar.h>
#include <deque>
#include <iostream>
#include <nlohmann/json.hpp>

constexpr const int WINDOW_WIDTH=1280;
constexpr const int WINDOW_HEIGHT=720;
constexpr const int FRAME_LIMIT=60;
constexpr const bool VSYNC=true;

using std::string, std::wstring;
using nlohmann::json;

struct SlidesUI {
  guecs::UI $gui;

  SlidesUI() {
    $gui.position(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    $gui.layout(
        "[t_left|t_center|t_right]"
        "[m_left|*%(300,200)title|_|_|m_right]"
        "[_|_|_|_|_]"
        "[_|*%(300,300)content|_|_|_]"
        "[_|_|_|_|_]"
        "[_|_|_|_|_]"
        "[b_left|b_center|b_right]"
    );
  }

  void init() {
    guecs::Background bg{$gui.$parser, };
    bg.set_color(guecs::THEME.BG_COLOR_DARK);
    $gui.set<guecs::Background>($gui.MAIN, bg);

    auto title = $gui.entity("title");
    $gui.set<guecs::Text>(title, {
        L"Title Thing\n", 124});

    auto content = $gui.entity("content");
    $gui.set<guecs::Text>(content, {
        L"* Sample 2\n"
        L"* Sample 3\n",
        56, guecs::THEME.TEXT_COLOR, 20});

    $gui.init();
  }

  void set_data(json& data) {
    (void)data;
  }

  void render(sf::RenderWindow& window) {
    $gui.render(window);
    // $gui.debug_layout(window);
  }

  void mouse(float x, float y, guecs::Modifiers mods) {
    $gui.mouse(x, y, mods);
  }
};


json parse_slides(const std::string& md_file) {
  (void)md_file;
  return {};
}

int main() {
  sfml::Backend backend;
  guecs::init(&backend);

  sf::RenderWindow window(sf::VideoMode({WINDOW_WIDTH, WINDOW_HEIGHT}), "Besos Loves Slides");
  window.setFramerateLimit(FRAME_LIMIT);
  window.setVerticalSyncEnabled(VSYNC);

  auto data = parse_slides("some_bullshit.md");
  SlidesUI slides;
  slides.init();
  slides.set_data(data);

  while(window.isOpen()) {
    while (const auto event = window.pollEvent()) {
      if(event->is<sf::Event::Closed>()) {
        window.close();
      }

      if(const auto* mouse = event->getIf<sf::Event::MouseButtonPressed>()) {
        if(mouse->button == sf::Mouse::Button::Left) {
          sf::Vector2f pos = window.mapPixelToCoords(mouse->position);
          slides.mouse(pos.x, pos.y, {});
        }
      }
    }

    slides.render(window);
    window.display();
  }
}
