#ifndef STEPPER_MANAGER_H
#define STEPPER_MANAGER_H

#include "config.h"
#include <AccelStepper.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <stdint.h>

class StepperManager {
public:
  StepperManager();

  void begin();
  void update();

  // Moves the blind to a specific percentage (0 = closed, 100 = open)
  void setTargetPercentage(int percentage, uint32_t overrideSpeed = 0);
  int getCurrentPercentage();
  int getTargetPercentage();
  long getCurrentAbsolutePosition();

  // High level open/close
  void open();
  void close();
  void stop();
  void emergencyStop(); // FEAT-7: Immediate halt, no deceleration
  void instantStop();   // Lightweight instant halt for touch reversal (no motor disable/save)
  void stopRelax();     // Cancel tension relief and restore full speed

  void setMaxSpeed(int speed);
  void setAcceleration(int accel);

  // Jogging for calibration
  void jog(int8_t direction); // +1 = UP/OPEN, -1 = DOWN/CLOSED, 0 = STOP

  bool isMoving();
  bool isRelaxing() const { return _isRelaxing; }
  bool isCalibrated() const;

private:
  static void timerCallback(void *arg);

  AccelStepper _stepper;

  unsigned long _lastPublishTime;
  unsigned long _lastSaveTime;
  unsigned long _idleStartTime;
  int8_t _jogDirection;
  long _lastSavedPosition;
  bool _isMotorEnabled;
  bool _lastMoveWasUp;
  bool _hasRelaxed;
  bool _isRelaxing;      // True during tension relief micro-movement

  esp_timer_handle_t _stepperTimer;
  SemaphoreHandle_t _stepperMutex;

  void enableMotor();
  void disableMotor();
};

extern StepperManager stepperManager;

#endif
