// 28BYJ-48 stepper (through the ULN2003 board) that turns the pill carousel,
// plus the HOME limit switch.  No library needed.
#pragma once
#include <Arduino.h>

class Carousel {
 public:
  int stepsPerRev = 4096;   // half-steps for one full turn (some motors are 4076)
  int homeOffset = 0;       // extra steps after the switch clicks, to centre H over the hole
  bool reverse = false;     // tick this in the app if the carousel turns the wrong way

  void begin(int in1, int in2, int in3, int in4, int homePin) {
    pins_[0] = in1; pins_[1] = in2; pins_[2] = in3; pins_[3] = in4;
    for (int p : pins_) pinMode(p, OUTPUT);
    homePin_ = homePin;
    pinMode(homePin_, INPUT_PULLUP);
    off();
  }

  bool homePressed() { return digitalRead(homePin_) == LOW; }

  // Steps from HOME to slot k (rounded, so the error never adds up).
  long slotSteps(int k, int slots) { return lround((double)k * stepsPerRev / slots); }

  // Turn FORWARD (the dispensing direction) from slot `from` to slot `to`.
  void forwardSlots(int from, int to, int slots) {
    move(slotSteps(to, slots) - slotSteps(from, slots), 2);
  }

  // Turn BACKWARD until the HOME switch clicks, but never more than maxSteps.
  // From slot k, backward only passes slots k-1 ... 1 over the drop hole, and those are
  // already empty.  Going further would bring full slot 14 over the hole, so the limit matters.
  // Returns false if the switch never clicked.
  bool home(long maxSteps) {
    if (homePressed()) return true;      // already sitting on the switch: we are at H
    for (long i = 0; i < maxSteps; i++) {
      step(-1, 3);
      if (homePressed()) {
        move(homeOffset, 3);
        off();
        return true;
      }
    }
    off();
    return false;
  }

  // Full search, ONLY with an empty carousel (first setup and calibration).
  bool calibrate() {
    for (int i = 0; i < 800 && homePressed(); i++) step(+1, 3);   // get off the switch first
    return home(stepsPerRev + stepsPerRev / 6);
  }

  // Positive = forward.  msPerStep 2 is about 7 turns per minute.
  void move(long steps, int msPerStep) {
    int dir = steps >= 0 ? 1 : -1;
    for (long i = 0; i < labs(steps); i++) step(dir, msPerStep);
    off();
  }

  void off() { for (int p : pins_) digitalWrite(p, LOW); }   // no current = motor stays cool

 private:
  int pins_[4];
  int homePin_ = -1;
  int phase_ = 0;
  void step(int dir, int msPerStep) {
    static const uint8_t SEQ[8] = {0b1000, 0b1100, 0b0100, 0b0110, 0b0010, 0b0011, 0b0001, 0b1001};
    phase_ = (phase_ + ((dir > 0) != reverse ? 1 : 7)) % 8;
    for (int i = 0; i < 4; i++) digitalWrite(pins_[i], (SEQ[phase_] >> (3 - i)) & 1);
    delay(msPerStep);                   // delay() also lets WiFi keep working
  }
};
