#ifndef TOUCH_MANAGER_H
#define TOUCH_MANAGER_H

#include "Arduino.h"

class TouchManager {
public:
  TouchManager();
  void begin();
  void update();

private:
  void handleSingleTap();
  void handleDoubleTap();

  enum class TouchState {
    IDLE,
    PRESSED,
    RELEASED_WAIT,
    PRESSED_SECOND,
    HOLD_TRIGGERED     // Hold gesture fired (emergency stop); blocks further actions until release
  };

  TouchState _fsmState;
  unsigned long _pressStartTime;
  unsigned long _releaseTime;
  unsigned long _secondPressStart; // Timestamp for PRESSED_SECOND safety timeout

  bool _lastReading;    // Raw reading from previous loop
  bool _debouncedState; // Confirmed stable state
  unsigned long _lastChangeTime;
  
  static const unsigned long DEBOUNCE_DELAY = 50;         // ms — TTP223 debounce period
  static const unsigned long DOUBLE_TAP_TIMEOUT = 400;    // ms — window for detecting 2nd tap (increased from 200; debounce alone takes ~150ms)
  static const unsigned long HOLD_THRESHOLD = 1500;       // ms — hold duration to trigger emergency stop while moving
  static const unsigned long PRESSED_SECOND_TIMEOUT = 5000; // ms — safety timeout to escape stuck PRESSED_SECOND state
};

extern TouchManager touchManager;

#endif
