#ifndef STORAGE_H
#define STORAGE_H

#include "config.h"
#include <EEPROM.h>

class StorageManager {
public:
  StorageManager() : _lastSaveTime(0), _lastWrittenChecksum(0), _pendingSave(false) {}
  void begin();
  void load();
  void save();
  void reset();

  // Call from main loop to flush deferred writes (throttled)
  void flushPending();

  // Setup Wizard Helpers
  bool isSetupComplete() const;
  void markSetupComplete();

private:
  uint32_t calculateChecksum(const ConfigData &data);

  unsigned long _lastSaveTime;
  uint32_t _lastWrittenChecksum;
  bool _pendingSave;
};

// Power-loss protection memory layout constants.
// These are used by both begin() (boot recovery) and save() (atomic writes).
#define WRITE_FLAG_ADDR (EEPROM_SIZE - 4) // Last 4 bytes for write-in-progress flag
#define WRITE_FLAG_VALUE 0xDEADBEEF       // Indicates write in progress
#define WRITE_FLAG_CLEAR 0x00000000       // Write complete
#define BACKUP_SLOT_ADDR (sizeof(ConfigData) + 16) // Backup after primary + padding

extern StorageManager storage;

#endif
