#include <frostbite2D/graphics/camera.h>
#include <glm/gtc/matrix_transform.hpp>

namespace frostbite2D {

Camera::Camera() : position_(0, 0), zoom_(1.0f) {}

void Camera::setPosition(const Vec2 &pos) { position_ = pos; }

void Camera::setZoom(float zoom) { zoom_ = zoom; }

void Camera::setViewport(int width, int height) {
  viewportWidth_ = width;
  viewportHeight_ = height;
}

void Camera::lookAt(const Vec2 &target) { position_ = target; }

void Camera::move(const Vec2 &delta) { position_ = position_ + delta; }

void Camera::zoomAt(float factor, const Vec2 &screenPos) {
  Vec2 worldBefore = screenPos - position_;
  zoom_ *= factor;
  Vec2 worldAfter = screenPos - position_;
  position_ = position_ + (worldBefore - worldAfter);
}

glm::mat4 Camera::getViewMatrix() const {
  glm::mat4 view = glm::mat4(1.0f);
  view[3][0] = -position_.x;
  view[3][1] = -position_.y;
  view[0][0] = zoom_;
  view[1][1] = zoom_;
  return view;
}

glm::mat4 Camera::getProjectionMatrix() const {
  float left = 0.0f;
  float right = static_cast<float>(viewportWidth_);
  float bottom, top;
  
  if (flipY_) {
    // Y 轴向下：(0,0) 在左上角（2D 游戏常用）
    // glm::ortho(left, right, bottom, top, ...)
    // 这里 bottom 是屏幕底部（值大），top 是屏幕顶部（值小）
    bottom = static_cast<float>(viewportHeight_);
    top = 0.0f;
  } else {
    // Y 轴向上：(0,0) 在左下角（OpenGL 默认）
    bottom = 0.0f;
    top = static_cast<float>(viewportHeight_);
  }

  return glm::ortho(left, right, bottom, top, -1.0f, 1.0f);
}

} // namespace frostbite2D