#include <Arduino.h>
#include <Wire.h>

#define SLAVE_ADDRESS 0x77

uint8_t registers[256] = {0}; // Simuleer registermap
uint8_t regAddr = 0;           // Registeradres voor read/write

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
  Serial.println("Slave ready.");
}

void loop() {
}

// Ontvangen van master (write)
void receiveEvent(int howMany) {
  if (howMany < 1) return;

  regAddr = Wire.read(); // Eerste byte is altijd registeradres

  if (howMany > 1) {
    // Daarna komen data bytes
    int bytesToRead = howMany - 1;
    for (int i = 0; i < bytesToRead; i++) {
      if (Wire.available()) {
        uint8_t val = Wire.read();
        registers[regAddr + i] = val;
        Serial.print("Reg ");
        Serial.print(regAddr + i);
        Serial.print(" written with ");
        Serial.println(val);
      }
    }

    // Update min/max registers als 0x21 of 0x22 is gewijzigd
    if (regAddr == 0x21 || regAddr == 0x22) {
      uint8_t a = registers[0x21];
      uint8_t b = registers[0x22];
      registers[0x23] = (a < b) ? a : b; // MIN
      registers[0x24] = (a > b) ? a : b; // MAX

      Serial.print("Updated MIN (0x23): ");
      Serial.println(registers[0x23]);
      Serial.print("Updated MAX (0x24): ");
      Serial.println(registers[0x24]);
    }
  }
  // else alleen registeradres ontvangen, niks schrijven (read setup)
}

// Master vraagt data op (read)
void requestEvent() {
  uint8_t val = registers[regAddr];
  Wire.write(val);

  Serial.print("Sent reg ");
  Serial.print(regAddr, HEX);
  Serial.print(": ");
  Serial.println(val);
}
