#pragma once

#include "esphome/components/i2c/i2c.h"
#include "esphome/components/touchscreen/touchscreen.h"
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"

namespace esphome::gsl3670 {

// ---------------------------------------------------------------------------
// GSL3670 touchscreen ESPHome component
// ---------------------------------------------------------------------------
class GSL3670Touchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
 public:
  /// Supply the firmware table (generated by codegen from the YAML)
  void set_firmware(const uint8_t *fw, size_t len) {
    this->firmware_ = fw;
    this->firmware_len_ = len;
  }

  void set_interrupt_pin(InternalGPIOPin *pin) { interrupt_pin_ = pin; }
  void set_reset_pin(GPIOPin *pin) { reset_pin_ = pin; }

  // touchscreen::Touchscreen / Component interface
  void setup() override;
  void dump_config() override;

 protected:
  void update_touches() override;

 private:
  // ---------- init steps (mirrors esp_lcd_touch_gsl3670_init) ----------
  void clear_reg_();      // GPIO reset + 0x88/0xe4/0xe0 sequence
  void reset_();          // GPIO reset + 0xe4/0xbc sequence
  void load_firmware_();  // write GSLX670_FW table
  void startup_chip_();   // 0x00→0xe0 + gsl_DataInit

  // ---------- I2C helpers ----------
  bool write_reg_(uint8_t reg, const uint8_t *data, size_t len);
  bool write_reg8_(uint8_t reg, uint8_t val);

  InternalGPIOPin *interrupt_pin_{nullptr};
  GPIOPin *reset_pin_{nullptr};

  const uint8_t *firmware_{nullptr};
  size_t firmware_len_{0};
};

}  // namespace esphome::gsl3670
