#include <extra2d/scene/transition_fade_scene.h>
#include <extra2d/app/application.h>
#include <extra2d/graphics/core/render_backend.h>
#include <extra2d/platform/iwindow.h>
#include <extra2d/utils/logger.h>
#include <algorithm>
#include <glm/gtc/matrix_transform.hpp>

namespace extra2d {

/**
 * @brief 构造函数，初始化淡入淡出过渡场景
 * @param duration 过渡持续时间（秒）
 * @param inScene 要进入的目标场景
 * @param color 遮罩颜色
 */
TransitionFadeScene::TransitionFadeScene(float duration, Ptr<Scene> inScene,
                                         const Color &color)
    : TransitionScene(duration, inScene), maskColor_(color) {}

/**
 * @brief 创建淡入淡出过渡场景的静态工厂方法
 * @param duration 过渡持续时间（秒）
 * @param inScene 要进入的目标场景
 * @param color 遮罩颜色
 * @return 过渡场景智能指针
 */
Ptr<TransitionFadeScene> TransitionFadeScene::create(float duration,
                                                     Ptr<Scene> inScene,
                                                     const Color &color) {
  return makePtr<TransitionFadeScene>(duration, inScene, color);
}

/**
 * @brief 启动过渡动画
 *
 * 使用定时器来更新进度，实际进度更新由 SceneManager 的 update 驱动
 */
void TransitionFadeScene::onTransitionStart() {
  E2D_LOG_DEBUG("TransitionFadeScene::onTransitionStart - 启动淡入淡出过渡");
}

void TransitionFadeScene::updateTransition(float dt) {
  // 调用基类更新进度
  TransitionScene::updateTransition(dt);

  // 检查是否需要切换场景显示
  if (!hasSwitched_ && progress_ >= 0.5f) {
    hideOutShowIn();
  }
}

void TransitionFadeScene::renderContent(RenderBackend &renderer) {
  auto &app = Application::get();
  float windowWidth = static_cast<float>(app.window()->width());
  float windowHeight = static_cast<float>(app.window()->height());

  // 根据进度选择渲染哪个场景
  if (progress_ < 0.5f) {
    drawOutScene(renderer);
  } else {
    drawInScene(renderer);
  }

  // 计算遮罩透明度
  float maskAlpha;
  if (progress_ < 0.5f) {
    maskAlpha = progress_ * 2.0f;
  } else {
    maskAlpha = (1.0f - progress_) * 2.0f;
  }

  renderer.setViewport(0, 0, static_cast<int>(windowWidth),
                       static_cast<int>(windowHeight));

  glm::mat4 overlayVP =
      glm::ortho(0.0f, windowWidth, windowHeight, 0.0f, -1.0f, 1.0f);
  renderer.setViewProjection(overlayVP);

  Color maskColor = maskColor_;
  maskColor.a = maskAlpha;
  renderer.fillRect(Rect(0.0f, 0.0f, windowWidth, windowHeight), maskColor);
}

/**
 * @brief 切换场景显示
 *
 * 标记已切换场景
 */
void TransitionFadeScene::hideOutShowIn() {
  hasSwitched_ = true;
  E2D_LOG_DEBUG("TransitionFadeScene::hideOutShowIn - 切换场景显示");
}

} // namespace extra2d
