#pragma once
#include "driver/i2c_master.h"
#include "esp_err.h"
#include <cstdint>

// Thin CST820B reader for the M5Stack StopWatch.
//
// Protocol verified against the M5GFX StopWatch autodetect path
// (managed_components/M5GFX/src/M5GFX.cpp) and its Touch_CST816S driver:
// the CST820B at I2C 0x15 uses the CST816S register set. The StopWatch maps it
// with x_max=233, y_max=233, INT=GPIO13 and reset via M5IOE1 PYG4.
//
// It reuses the board's existing I2C master bus and never calls M5.begin(),
// Wire.begin() or i2c_new_master_bus().
class Cst820Touch {
public:
    static constexpr uint8_t ADDRESS = 0x15;
    static constexpr uint8_t REG_TOUCH = 0x02;
    static constexpr uint8_t REG_CHIP_ID = 0xA7;
    static constexpr uint8_t REG_MOTION_MASK = 0xEC;

    // Attach to the existing bus. Returns ESP_OK only when the chip answers.
    esp_err_t begin(i2c_master_bus_handle_t bus);
    bool ready() const { return device_ != nullptr; }

    // Sample one contact. Returns true when a finger is down, with the raw
    // (untransformed) coordinates. A monotouch controller reports one point.
    bool read(uint16_t& raw_x, uint16_t& raw_y);

private:
    esp_err_t read_registers(uint8_t reg, uint8_t* data, size_t size);
    esp_err_t write_register(uint8_t reg, uint8_t value);
    i2c_master_dev_handle_t device_ = nullptr;
};