enum DoorState { closed, opening, open, closing }

class Door {
  final int x;
  final int y;
  final int mapId; // To differentiate between regular doors and elevator doors

  DoorState state = DoorState.closed;
  double offset = 0.0;
  int openTime = 0; // When did the door fully open?

  // How long a door stays open before auto-closing
  static const int openDurationMs = 3000;

  Door({
    required this.x,
    required this.y,
    required this.mapId,
  });

  // Returns true if the door state changed this frame (useful for playing sounds later)
  bool update(int currentTimeMs) {
    bool stateChanged = false;

    if (state == DoorState.opening) {
      offset += 0.02; // Slide speed
      if (offset >= 1.0) {
        offset = 1.0;
        state = DoorState.open;
        openTime = currentTimeMs;
        stateChanged = true;
      }
    } else if (state == DoorState.open) {
      if (currentTimeMs - openTime > openDurationMs) {
        state = DoorState.closing;
        stateChanged = true;
      }
    } else if (state == DoorState.closing) {
      // Note: We don't check for entities blocking the door yet!
      offset -= 0.02;
      if (offset <= 0.0) {
        offset = 0.0;
        state = DoorState.closed;
        stateChanged = true;
      }
    }

    return stateChanged;
  }

  void interact() {
    if (state == DoorState.closed || state == DoorState.closing) {
      state = DoorState.opening;
    }
  }
}
