#include <extra2d/scene/transition_scale_scene.h>
#include <extra2d/graphics/camera/camera.h>
#include <extra2d/graphics/core/render_backend.h>
#include <algorithm>

namespace extra2d {

/**
 * @brief 构造函数，初始化缩放过渡场景
 * @param duration 过渡持续时间（秒）
 * @param inScene 要进入的目标场景
 */
TransitionScaleScene::TransitionScaleScene(float duration, Ptr<Scene> inScene)
    : TransitionScene(duration, inScene) {}

/**
 * @brief 创建缩放过渡场景的静态工厂方法
 * @param duration 过渡持续时间（秒）
 * @param inScene 要进入的目标场景
 * @return 过渡场景智能指针
 */
Ptr<TransitionScaleScene> TransitionScaleScene::create(float duration,
                                                       Ptr<Scene> inScene) {
  return makePtr<TransitionScaleScene>(duration, inScene);
}

/**
 * @brief 启动过渡动画
 *
 * 缩放过渡不需要特殊的初始化
 */
void TransitionScaleScene::onTransitionStart() {
}

/**
 * @brief 更新过渡进度
 * @param dt 帧间隔时间（秒）
 */
void TransitionScaleScene::updateTransition(float dt) {
  TransitionScene::updateTransition(dt);
}

/**
 * @brief 渲染过渡内容
 * @param renderer 渲染后端引用
 *
 * 根据进度控制新旧场景的缩放比例
 */
void TransitionScaleScene::renderContent(RenderBackend &renderer) {
  float easeProgress = progress_ < 0.5f ? 2.0f * progress_ * progress_
                                        : -1.0f + (4.0f - 2.0f * progress_) * progress_;

  if (outScene_) {
    float scale = std::max(0.01f, 1.0f - easeProgress);

    Camera *camera = outScene_->getActiveCamera();
    float originalZoom = camera ? camera->getZoom() : 1.0f;

    if (camera) {
      camera->setZoom(originalZoom * scale);
    }

    outScene_->renderContent(renderer);

    if (camera) {
      camera->setZoom(originalZoom);
    }
  }

  if (inScene_) {
    float scale = std::max(0.01f, easeProgress);

    Camera *camera = inScene_->getActiveCamera();
    float originalZoom = camera ? camera->getZoom() : 1.0f;

    if (camera) {
      camera->setZoom(originalZoom * scale);
    }

    inScene_->renderContent(renderer);

    if (camera) {
      camera->setZoom(originalZoom);
    }
  }

}

} // namespace extra2d
