#pragma once

#include "CoreMinimal.h"
//#include "HAL/Thread.h"
#include "HAL/Runnable.h"
#include "HAL/ThreadSafeBool.h"
#include "TimerManager.h"

class CRASHSIGHT_API FCrashSightAnrMonitor : FRunnable
{
public:
    static void Initialize();
    static void Shutdown();
    static void StartMonitor(int32 TimeoutMs = 5000);
    static void StopMonitor();

private:
    // Singleton instance
    static FCrashSightAnrMonitor* Instance;

    // Thread control
    FRunnableThread* Thread = nullptr;
    FThreadSafeBool bRunning;
    FThreadSafeBool bPaused;

    // Timing parameters
    FThreadSafeCounter TicksSinceUiUpdate;
    int32 AnrTimeoutMs;
    int32 DetectionTimeoutMs;
    FTimerHandle UiUpdateTimerHandle;
    FThreadSafeBool bReported;

    // Thread safe exit
    FCriticalSection CriticalSection;

    FCrashSightAnrMonitor();
    virtual ~FCrashSightAnrMonitor();

    // FRunnable interface
    virtual uint32 Run() override;
    virtual void Stop() override {}
    virtual void Exit() override {}

    void ReportANR();
    void UpdateUiStatus();
    void HandleApplicationPause(bool bIsPaused);
    void HandleApplicationWillEnterBackground();
    void HandleApplicationWillEnterForeground();
};