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

#define PIN_LCD_CS    12
#define PIN_LCD_SCLK  38
#define PIN_LCD_D0     4
#define PIN_LCD_D1     5
#define PIN_LCD_D2     6
#define PIN_LCD_D3     7
#define PIN_LCD_RST    2
#define PIN_I2C_SDA   15
#define PIN_I2C_SCL   14

#define DISP_W 480
#define DISP_H 480

#define C_BG      0x0841u
#define C_PANEL   0x1082u
#define C_CARD    0x18C3u
#define C_BORDER  0x39C7u
#define C_TEXT    0xFFFFu
#define C_OK      0x3666u
#define C_WARN    0xECA0u
#define C_BUTTON  0x2145u
#define C_BUTTON2 0x3186u

Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
    PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
Arduino_CO5300 *gfx = new Arduino_CO5300(
    gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);

static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
  gfx->fillRoundRect(x, y, w, h, radius, fill);
  gfx->drawRoundRect(x, y, w, h, radius, border);
}

static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) {
  gfx->setFont();
  gfx->setTextSize(size);
  gfx->setTextColor(color);
  gfx->setCursor(x, y);
  gfx->print(text);
}

static void drawButton(int x, int y, int w, int h, uint16_t fill, const char *label, uint8_t size = 2) {
  drawPanel(x, y, w, h, fill, C_BORDER, 12);
  gfx->setFont();
  gfx->setTextSize(size);
  gfx->setTextColor(C_TEXT);
  int textW = strlen(label) * 6 * size;
  int textX = x + (w - textW) / 2;
  if (textX < x + 8) {
    textX = x + 8;
  }
  int textY = y + (h + 8 * size) / 2 - 2;
  gfx->setCursor(textX, textY);
  gfx->print(label);
}

static void drawScreen() {
  gfx->fillScreen(C_BG);
  drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
  drawText(24, 42, "BUTTON LAYOUT TEST", C_TEXT, 2);
  drawText(24, 70, "Check bottom and wide buttons", C_WARN, 1);

  drawButton(20, 110, 136, 52, C_BUTTON, "STATUS");
  drawButton(172, 110, 136, 52, C_BUTTON, "CONNECT");
  drawButton(324, 110, 136, 52, C_BUTTON, "ACCOUNT");

  drawButton(20, 180, 136, 52, C_BUTTON, "WALLET");
  drawButton(172, 180, 136, 52, C_BUTTON, "REQUESTS");
  drawButton(324, 180, 136, 52, C_BUTTON, "SETTINGS");

  drawButton(20, 270, 212, 48, C_BUTTON2, "BACK");
  drawButton(248, 270, 212, 48, C_OK, "REFRESH");

  drawButton(20, 338, 440, 40, C_BUTTON2, "FULL WIDTH BUTTON", 2);
  drawButton(20, 390, 440, 56, C_OK, "REGISTER DEVICE", 2);
}

void setup() {
  Serial.begin(115200);
  Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
  gfx->begin();
  gBus->writeC8D8(0x36, 0xA0);
  gfx->setBrightness(220);
  drawScreen();
}

void loop() {
  delay(1000);
}
