#pragma once

#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/timeCode.h>
#include "IconManager.h"
#include <functional>

namespace UsdLayerManager {

/// Bottom-docked playback timeline.
///
/// Owns the current frame, playback state, and the Auto-Key toggle, and fires
/// OnTimeChanged whenever the time changes:
///   displayTime — the current frame; used for all reads/evaluation
///   editTime    — the current frame when Auto-Key is ON, otherwise Default()
///
/// Supports:
///   Loop         — playback wraps from end back to start (or vice-versa).
///   Bounce       — playback reverses direction at each boundary (ping-pong).
///   Rewind       — reverse-direction playback (m_reversed).
class TimelinePanel {
public:
    void SetStage(pxr::UsdStageRefPtr stage);
    void SetIconManager(IconManager* icons) { m_iconManager = icons; }

    /// Advance playback by deltaTime seconds; called once per app frame.
    void Update(float deltaTime);
    void Render();

    std::function<void(pxr::UsdTimeCode displayTime,
                       pxr::UsdTimeCode editTime)> OnTimeChanged;

private:
    /// Clamp to [startFrame, endFrame]; fires OnTimeChanged when the frame changes.
    void SetCurrentFrame(double frame);
    void NotifyTimeChanged();
    pxr::UsdTimeCode EditTime() const;

    IconManager*        m_iconManager = nullptr;
    pxr::UsdStageRefPtr m_stage;

    // Stage range (written back to stage metadata on edit).
    double m_startFrame   = 1.0;
    double m_endFrame     = 100.0;
    double m_fps          = 24.0;

    // Playback state.
    double m_currentFrame = 1.0;
    bool   m_playing      = false;
    enum class LoopMode { None, Loop, Bounce };

    bool     m_reversed = false;           // play backward when true
    LoopMode m_loopMode = LoopMode::Loop;  // boundary behaviour

    // Auto-Key.
    bool   m_autoKey      = false;
};

} // namespace UsdLayerManager
