#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Preferences.h>
#include <lvgl.h>
#include <Arduino_GFX_Library.h>
#include <TouchDrvCSTXXX.hpp>
#include <mbedtls/gcm.h>
#include <mbedtls/sha256.h>
#include <mbedtls/base64.h>
#include <Ed25519.h>
#include <sodium.h>
#include <time.h>
#include <sys/time.h>
#include <vector>
#define XPOWERS_CHIP_AXP2101
#include "XPowersLib.h"
#include "shine_secret_generation.h"
#include <stdint.h>

extern "C" {
#include "../../official-demo/examples/Arduino-v3.3.5/libraries/lvgl/src/extra/libs/qrcode/lv_qrcode.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 PIN_TP_INT    11

#define DISP_W 480
#define DISP_H 480
#define LVGL_TICK_MS 2
#define SWIPE_THRESHOLD 48
#define TAP_CANCEL_THRESHOLD 18
#define MAX_SCAN_RESULTS 8
#define MAX_SAVED_WIFI_NETWORKS 8

extern "C" {
typedef int32_t fe25519[10];
typedef struct {
  fe25519 X;
  fe25519 Y;
  fe25519 Z;
  fe25519 T;
} ge25519_p3;
int ge25519_frombytes(ge25519_p3 *h, const unsigned char *s);
}
#define WIFI_CONNECT_TIMEOUT_MS 12000
#define WIFI_RECONNECT_FAST_MS 10000
#define WIFI_RECONNECT_SLOW_MS 30000
#define WIFI_RECONNECT_SLOW_AFTER_MS 90000
#define HOME_REFRESH_MS 1000
#define ACCOUNT_CHECK_RETRY_MS 15000
#define SHINE_PING_INTERVAL_MS 60000
#define SHINE_RECONNECT_MIN_MS 10000
#define SHINE_RECONNECT_MAX_MS 30000
#define SHINE_RPC_TIMEOUT_MS 2500
#define SHINE_WS_CONNECT_TIMEOUT_MS 1500
#define TEXT_EDIT_PANEL_X 10
#define TEXT_EDIT_PANEL_Y 112
#define TEXT_EDIT_PANEL_W 460
#define TEXT_EDIT_PANEL_H 330
#define TEST_VERSION "SHiNE homeserver (v.0.18)"

static const char *kShineUsersProgramId = "3bYrnXwLc56oVPUBAjY8zTMLwHCYq29b5rUMu3b64SQJ";
static const char *kShineUsersUserPdaSeedPrefix = "user_login=";
static const char *kShineLoginGuardProgramId = "3xkopA7cXagxzMFrKdv3NCBfV6BKiRJCk69kr27M2sRo";
static const char *kShinePaymentsProgramId = "c4yTa4JT9EtQDCBX9LmWFK6T2gp4JGsuymFbom2EudW";
static const char *kSystemProgramId = "11111111111111111111111111111111";
static const char *kEd25519ProgramId = "Ed25519SigVerify111111111111111111111111111";
static const char *kSysvarInstructionsId = "Sysvar1nstructions1111111111111111111111111";
static const char *kUsersSeedPrefix = "user_login=";
static const char *kUsersEconomyConfigSeed = "shine_users_economy_config";
static const char *kPaymentsInflowSeed = "shine_payments_inflow_vault";
static const char *kLastBlockPrefix = "SHiNE_LAST_BLOCK";
static const char *kProgramDerivedAddressMarker = "ProgramDerivedAddress";
static const char *kDefaultShineServerLogin = "shineupme";
static const uint8_t kBlockTypeRecoveryKey = 0;
static const uint8_t kBlockTypeRootKey = 1;
static const uint8_t kBlockTypeClientKey = 2;
static const uint8_t kBlockTypeBlockchainRegistry = 3;
static const uint8_t kBlockTypeServerProfile = 30;
static const uint8_t kBlockTypeAccessServers = 40;
static const uint8_t kBlockTypeSessions = 50;
static const uint8_t kBlockTypeTrustedState = 70;
static const uint8_t kSessionTypeHomeserver = 100;
static const char *kSessionClientPlatformEsp32 = "ESP32";

enum Screen {
  SCREEN_HOME,
  SCREEN_WALLET,
  SCREEN_WALLET_SELECT,
  SCREEN_WALLET_QR,
  SCREEN_WALLET_SIGN_REQUEST,
  SCREEN_SETTINGS_MENU,
  SCREEN_PAIRING_REQUESTS,
  SCREEN_PAIRING_REQUEST_DETAIL,
  SCREEN_WIFI,
  SCREEN_SERVER,
  SCREEN_ACCOUNT,
  SCREEN_ACCOUNT_HOMESERVER,
  SCREEN_ACCOUNT_SECRET,
  SCREEN_SECRET_SHOW,
  SCREEN_SECRET_GENERATE_INFO,
  SCREEN_SECRET_GENERATE_RUNNING,
  SCREEN_SECRET_GENERATE_CANCEL_CONFIRM,
  SCREEN_TEXT_EDIT,
  SCREEN_REGISTER_ACCOUNT_CONFIRM,
  SCREEN_REGISTER_ACCOUNT_RESULT,
  SCREEN_HOMESERVER_PDA_CONFIRM,
  SCREEN_HOMESERVER_PDA_RESULT,
};

enum SwipeDirection {
  SWIPE_NONE,
  SWIPE_LEFT,
  SWIPE_RIGHT,
  SWIPE_UP,
  SWIPE_DOWN,
};

enum ActionId {
  ACTION_NONE,
  ACTION_OPEN_SETTINGS,
  ACTION_OPEN_WALLET,
  ACTION_WALLET_SELECT,
  ACTION_WALLET_SELECT_DEVICE,
  ACTION_WALLET_SELECT_ROOT,
  ACTION_WALLET_SELECT_CUSTOM,
  ACTION_OPEN_WALLET_QR,
  ACTION_WALLET_SIGN_APPROVE,
  ACTION_WALLET_SIGN_REJECT,
  ACTION_OPEN_PAIRING_REQUESTS,
  ACTION_OPEN_WIFI,
  ACTION_OPEN_SERVER,
  ACTION_OPEN_ACCOUNT,
  ACTION_BACK_HOME,
  ACTION_BACK_SETTINGS,
  ACTION_WIFI_SELECT_NETWORK,
  ACTION_WIFI_CLEAR,
  ACTION_SERVER_EDIT_SOLANA,
  ACTION_SERVER_EDIT_SHINE,
  ACTION_ACCOUNT_EDIT_LOGIN,
  ACTION_ACCOUNT_EDIT_HOMESERVER,
  ACTION_ACCOUNT_EDIT_SECRET,
  ACTION_ACCOUNT_HOMESERVER_USE_DEFAULT,
  ACTION_ACCOUNT_HOMESERVER_EDIT_MANUAL,
  ACTION_SECRET_SHOW,
  ACTION_SECRET_MANUAL,
  ACTION_SECRET_GENERATE,
  ACTION_SECRET_GENERATE_START,
  ACTION_SECRET_GENERATE_CANCEL,
  ACTION_SECRET_GENERATE_CANCEL_YES,
  ACTION_SECRET_GENERATE_CANCEL_NO,
  ACTION_BACK_SECRET_MENU,
  ACTION_BACK_ACCOUNT,
  ACTION_REFRESH_BALANCE,
  ACTION_PAIRING_REFRESH,
  ACTION_PAIRING_APPROVE,
  ACTION_PAIRING_REJECT,
  ACTION_REGISTER_ACCOUNT,
  ACTION_REGISTER_ACCOUNT_EXECUTE,
  ACTION_HOMESERVER_PDA_ACTION,
  ACTION_HOMESERVER_PDA_ADD_EXECUTE,
  ACTION_HOMESERVER_PDA_FIX_EXECUTE,
  ACTION_EDITOR_SAVE,
  ACTION_EDITOR_CANCEL,
};

enum WifiViewMode {
  WIFI_VIEW_OVERVIEW,
  WIFI_VIEW_SCAN_RESULTS,
};

enum EditContext {
  EDIT_CONTEXT_NONE,
  EDIT_CONTEXT_WIFI_PASSWORD,
  EDIT_CONTEXT_SOLANA_RPC,
  EDIT_CONTEXT_SHINE_SERVER,
  EDIT_CONTEXT_LOGIN,
  EDIT_CONTEXT_HOMESERVER,
  EDIT_CONTEXT_WALLET_CUSTOM,
  EDIT_CONTEXT_SECRET_MANUAL,
  EDIT_CONTEXT_SECRET_GENERATE_PASSWORD,
};

enum WalletSelectionType {
  WALLET_SELECTION_DEVICE,
  WALLET_SELECTION_ROOT,
  WALLET_SELECTION_CUSTOM,
};

enum KeyboardMode {
  KEYBOARD_MODE_ALPHA,
  KEYBOARD_MODE_SYMBOLS,
};

enum AccountPdaStatus {
  ACCOUNT_PDA_UNKNOWN,
  ACCOUNT_PDA_OK,
  ACCOUNT_PDA_NOT_FOUND,
  ACCOUNT_PDA_MISMATCH,
};

struct ShinePdaSessionRecord {
  uint8_t sessionType = 0;
  uint8_t sessionVersion = 0;
  String sessionName;
  uint8_t sessionPubKey32[32] = {};
};

struct ShinePdaUserState {
  bool found = false;
  String login;
  uint64_t createdAtMs = 0;
  uint64_t updatedAtMs = 0;
  uint32_t recordNumber = 0;
  uint8_t prevRecordHash32[32] = {};
  uint8_t blockchainType = 1;
  bool isServer = false;
  uint8_t addressFormatType = 0;
  uint8_t addressFormatVersion = 0;
  String serverAddress;
  std::vector<String> syncServers;
  std::vector<String> accessServers;
  uint8_t sessionsMode = 1;
  uint8_t trustedCount = 0;
  uint8_t recoveryKey32[32] = {};
  uint8_t rootKey32[32] = {};
  uint8_t clientKey32[32] = {};
  uint8_t blockchainKey32[32] = {};
  String blockchainName;
  uint64_t paidLimitBytes = 0;
  uint64_t usedBytes = 0;
  uint32_t lastBlockNumber = 0;
  uint8_t lastBlockHash32[32] = {};
  uint8_t lastBlockSignature64[64] = {};
  String arweaveTxId;
  std::vector<ShinePdaSessionRecord> sessions;
};

struct SimpleWebSocketClient {
  WiFiClientSecure client;
  bool connected = false;
  String host;
  String path;
  uint16_t port = 0;
};

struct PairingRequestUiItem {
  String pairingId;
  String requesterSessionKey;
  int requesterSessionType = 0;
  String requesterClientPlatform;
  String shortCode;
  uint64_t expiresAtMs = 0;
};

struct PendingWalletRpcRequest {
  String fromLogin;
  String fromSessionId;
  String callId;
  int type = 0;
  String data;
};

struct ActiveWalletSignRequest {
  bool active = false;
  String fromLogin;
  String fromSessionId;
  String callId;
  String requestId;
  String publicKeyBase58;
  String transactionBase64;
  String comment;
  uint64_t requestedAtMs = 0;
  Screen returnScreen = SCREEN_HOME;
};

static lv_disp_draw_buf_t gDrawBuf;
static lv_color_t *gBuf1 = nullptr;
static lv_color_t *gBuf2 = nullptr;
static lv_obj_t *gRoot = nullptr;
static lv_obj_t *gInputTextArea = nullptr;
static uint8_t *gWalletQrCanvasBuffer = nullptr;

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);
TouchDrvCST92xx gTouch;
XPowersPMU gPower;
Preferences gPrefs;

static Screen gCurrentScreen = SCREEN_HOME;
static int gSettingsScrollIndex = 0;
static bool gTouchDown = false;
static int16_t gTouchStartX = 0;
static int16_t gTouchStartY = 0;
static int16_t gTouchLastX = 0;
static int16_t gTouchLastY = 0;
static SwipeDirection gPendingSwipe = SWIPE_NONE;
static bool gBlockClick = false;
static bool gSuppressTouchUntilRelease = false;
static uint32_t gTouchSequence = 0;
static uint32_t gLastHandledTouchSequence = 0;
static bool gWalletQrTapReturnPending = false;

static String gWifiSavedSsid;
static String gWifiSavedPassword;
static String gWifiSelectedSsid;
static String gKnownWifiSsids[MAX_SAVED_WIFI_NETWORKS];
static String gKnownWifiPasswords[MAX_SAVED_WIFI_NETWORKS];
static String gWifiStatusMessage = "No Wi-Fi configured";
static String gScanResults[MAX_SCAN_RESULTS];
static int gScanResultCount = 0;
static WifiViewMode gWifiViewMode = WIFI_VIEW_OVERVIEW;

static String gSolanaRpcUrl = "https://api.devnet.solana.com";
static String gShineServerLogin = kDefaultShineServerLogin;
static String gShineServerUrl;
static String gResolvedShineServerLogin;
static String gServerStatusMessage = "Edit RPC or server login";
static String gLoginValue;
static String gHomeserverValue = "homeserver1";
static bool gSecretConfigured = false;
static String gSecretBase58;
static uint8_t gSecretBytes[32] = {};
static String gAccountStatusMessage = "Edit account fields";
static String gBalanceStatusMessage = "Wallet: tap to load balance";
static bool gBalanceAutoRefreshPending = false;
static unsigned long gLastBalanceAutoRefreshAttemptMs = 0;
static bool gWifiKnownGood = false;
static bool gWifiReconnectEnabled = false;
static bool gWifiOperationBusy = false;
static unsigned long gWifiDisconnectedSinceMs = 0;
static unsigned long gWifiLastReconnectAttemptMs = 0;
static wl_status_t gLastWifiStatus = WL_IDLE_STATUS;
static bool gPowerReady = false;
static AccountPdaStatus gAccountPdaStatus = ACCOUNT_PDA_UNKNOWN;
static String gAccountPdaStatusMessage = "Account not checked";
static bool gAccountCheckPending = true;
static unsigned long gLastAccountCheckMs = 0;
static bool gShowRegisterAccountButton = false;
static bool gShowHomeserverPdaActionButton = false;
static String gHomeserverPdaActionReason;
static bool gCachedAccountPdaValid = false;
static String gCachedAccountPdaLogin;
static ShinePdaUserState gCachedAccountPdaState;
static String gUserPdaAddress;
static String gRegistrationSignature;
static String gShineStatusLine = "SHiNE: account not configured";
static String gRegisterConfirmMessage;
static String gRegisterConfirmBalanceLine;
static String gRegisterConfirmPdaLine;
static String gRegisterConfirmHomeserverLine;
static bool gRegisterConfirmCanSubmit = false;
static String gRegisterResultMessage;
static String gRegisterResultDetails;
static bool gRegisterResultSuccess = false;
static String gHomeserverPdaActionMessage;
static String gHomeserverPdaActionDetail;
static bool gHomeserverPdaCanAdd = false;
static bool gHomeserverPdaCanFix = false;
static String gHomeserverPdaResultMessage;
static String gHomeserverPdaResultDetails;
static bool gHomeserverPdaResultSuccess = false;
static String gLastRegisterDiagStatus = "none";
static String gLastRegisterDiagSummary;
static String gLastRegisterDiagDetails;
static String gLastRegisterDiagTime;
static String gRegisterTriggerSource = "manual";
static String gSerialCommandBuffer;
static String gShineSessionId;
static String gShineSessionKey;
static String gShineStoragePwd;
static bool gShineAuthenticated = false;
static unsigned long gLastShineAttemptMs = 0;
static unsigned long gLastShinePingMs = 0;
static unsigned long gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
static uint32_t gWsRequestCounter = 1;
static int64_t gShineServerTimeOffsetMs = 0;
static SimpleWebSocketClient gShineWs;
static std::vector<PairingRequestUiItem> gPairingRequests;
static int gSelectedPairingRequestIndex = -1;
static String gPairingStatusMessage = "Refresh requests";
static bool gPairingBusy = false;

struct DerivedKeyInfo {
  String title;
  String formula;
  String value;
};

static String gRootPubB58;
static String gRootPrivB58;
static String gRecoveryPubB58;
static String gRecoveryPrivB58;
static String gBlockchainPubB58;
static String gBlockchainPrivB58;
static String gDevicePubB58;
static String gDevicePrivB58;
static String gHomeserverPubB58;
static String gHomeserverPrivB58;
static WalletSelectionType gSelectedWalletType = WALLET_SELECTION_DEVICE;
static String gCustomWalletName;
static String gCustomWalletPubB58;
static String gCustomWalletPrivB58;
static std::vector<PendingWalletRpcRequest> gPendingWalletRpcRequests;
static const int kWalletRpcSignalTypeRequest = 9100;
static const int kWalletRpcSignalTypeResponse = 9101;
static ActiveWalletSignRequest gActiveWalletSignRequest;
static String gWalletSignStatusMessage;
static lv_indev_drv_t *gSecretScrollIndevDriver = nullptr;
static uint8_t gSecretScrollThrowSaved = 0;
static bool gSecretScrollThrowApplied = false;

static EditContext gEditContext = EDIT_CONTEXT_NONE;
static Screen gEditReturnScreen = SCREEN_HOME;
static String gEditTitle;
static String gEditHint;
static String gEditValue;
static int gKeyboardPage = 0;
static bool gEditIsPassword = false;
static KeyboardMode gKeyboardMode = KEYBOARD_MODE_ALPHA;
static bool gKeyboardShift = false;

static void rebuildScreen();
static void showScreen(Screen screen);
static void handleSwipe(SwipeDirection swipe);
static void loadPrefs();
static void saveWifiPrefs();
static void clearWifiPrefs();
static void clearSavedWifiList();
static int findKnownWifiIndex(const String &ssid);
static String savedPasswordForSsid(const String &ssid);
static void upsertKnownWifi(const String &ssid, const String &password);
static bool refreshWalletBalance(String &messageOut);
static void saveServerPrefs();
static void saveAccountPrefs();
static void beginSavedWifi();
static void scanWifiNetworks();
static bool connectWifiNow(const String &ssid, const String &password);
static String wifiHomeStatus();
static String wifiSavedLabel();
static String wifiHomeSummary();
static void updateWifiReconnectState();
static void manageWifiReconnect();
static void openEditor(EditContext context,
                       Screen returnScreen,
                       const String &title,
                       const String &hint,
                       const String &value,
                       bool isPassword);
static void applyEditorValue();
static bool isTextEditKeyboardSwipeArea(int16_t x, int16_t y);
static void syncEditValueFromTextarea();
static void keepCursorAtEnd();
static void restoreTextareaFromEditValue();
static void refreshDerivedKeys();
static void clearDerivedKeys();
static String selectedWalletDisplayName();
static String selectedWalletTypeCode();
static String selectedWalletPublicKeyB58();
static String selectedWalletPrivateKeyB58();
static String selectedWalletDerivationSuffix();
static bool selectedWalletAvailable();
static void refreshSelectedWalletBalanceState();
static bool loadSelectedWalletBalanceLamports(uint64_t &lamportsOut, String &messageOut);
static bool loadBalanceLamportsForAddress(const String &address, uint64_t &lamportsOut, String &messageOut);
static bool queueIncomingWalletRpcRequest(const String &frame);
static void processPendingWalletRpcRequests();
static void pumpShineIncomingFrames(uint32_t maxFrames = 3);
static String loginDisplayValue();
static String homeserverDisplayValue();
static String homeSecretStatus();
static String secretButtonValue();
static void clearSecretValue();
static void setSecretValue(const uint8_t *bytes32);
static void initPowerManagement();
static int batteryPercentValue();
static int wifiSignalLevel();
static void drawTopStatusIndicators();
static void actionButtonCb(lv_event_t *event);
static void markAccountStateDirty();
static void clearShineSessionState(bool clearStoredSession);
static void saveShineSessionPrefs();
static String normalizeLoginValue(const String &value);
static bool base58ToFixed32(const String &value, uint8_t out[32]);
static bool base64DecodeStd(const String &value, std::vector<uint8_t> &out);
static String bytesToBase64String(const uint8_t *data, size_t len);
static String jsonEscape(const String &value);
static bool jsonStringField(const String &json, const String &field, String &valueOut);
static bool jsonBoolField(const String &json, const String &field, bool &valueOut);
static bool jsonInt64Field(const String &json, const String &field, uint64_t &valueOut);
static bool parseUrlHostPortPath(const String &url, String &hostOut, uint16_t &portOut, String &pathOut, bool &secureOut);
static String formatPairingShortCode(const String &value);
static bool pairingMenuVisible();
static int settingsMenuCount();
static String settingsMenuLabel(int itemIndex);
static ActionId settingsMenuAction(int itemIndex);
static String pairingSessionKindLabel(int sessionType);
static String pairingSessionNameLabel(const PairingRequestUiItem &item);
static bool findJsonArrayBounds(const String &json, const String &field, int &startOut, int &endOut);
static bool extractJsonObjectAt(const String &json, int startIndex, int &endOut, String &objectOut);
static bool parsePairingRequestsResponse(const String &json, std::vector<PairingRequestUiItem> &itemsOut, String &errorOut);
static bool refreshPairingRequests(String &errorOut);
static bool buildPkcs8FromSeed32(const uint8_t seed32[32], String &pkcs8B64Out);
static bool buildPairingSecretsPayload(const PairingRequestUiItem &item, String &payloadJsonOut, String &errorOut);
static bool createDelegatedWalletSessionPayload(const PairingRequestUiItem &item, String &payloadJsonOut, String &errorOut);
static bool encryptPairingPayloadForRequester(const String &requesterSessionKey, const String &payloadJson, String &encryptedPayloadOut, String &errorOut);
static bool approvePairingRequest(const PairingRequestUiItem &item, String &errorOut);
static bool rejectPairingRequest(const PairingRequestUiItem &item, String &errorOut);
static String shineWsUrl();
static String shineHomeLine();
static String balanceHomeLine();
static String walletQrUri();
static String walletQrAddressLine();
static uint64_t shineNowMs();
static bool loadWalletBalanceLamports(uint64_t &lamportsOut, String &messageOut);
static void shortVecEncode(size_t value, std::vector<uint8_t> &out);
static void pushU32LE(std::vector<uint8_t> &out, uint32_t value);
static void pushU64LE(std::vector<uint8_t> &out, uint64_t value);
static void pushStrU8(std::vector<uint8_t> &out, const String &value);
static void pushFixed(std::vector<uint8_t> &out, const uint8_t *data, size_t len);
static String bytesToBase58(const uint8_t *data, size_t len);
static bool getSystemEpochMs(uint64_t &epochMsOut);
static bool ensureNtpTimeSynced(String &errorOut);
static bool resolveShineServerUrlFromLogin(const String &serverLogin, String &serverUrlOut, String &errorOut);
static String currentShineServerLoginSource();
static bool ensureCurrentShineServerUrl(String &errorOut);
static String buildBaseRpcRequest(const char *method, const String &paramsJson);
static bool rpcCallSolana(const char *method, const String &paramsJson, String &payloadOut);
static bool rpcResponseHasError(const String &payload);
static bool getLatestBlockhashBytes(uint8_t out[32], String &blockhashB58, String &messageOut);
static bool pdaAlreadyExists(const String &login, String &pdaAddress, String &messageOut);
static bool loadUsersEconomyConfigState(const String &economyConfigAddress,
                                        uint64_t &registrationFeeLamportsOut,
                                        uint64_t &lamportsPerLimitStepOut,
                                        uint64_t &startBonusLimitOut,
                                        String &messageOut);
static bool loadAccountOwner(const String &address, String &ownerOut, bool &existsOut, String &messageOut);
static bool extractRpcErrorSummary(const String &payload, String &messageOut);
static String compactRpcLogs(const String &payload, int maxLines = 3);
static bool simulateTransactionPayload(const String &txBase64, String &payloadOut);
static bool simulateTransactionForError(const String &txBase64, String &messageOut);
static std::vector<uint8_t> buildLastBlockStateBytes(const String &login,
                                                     const String &blockchainName,
                                                     uint32_t lastBlockNumber = 0,
                                                     const uint8_t *lastBlockHash32 = nullptr,
                                                     uint64_t usedBytes = 0);
static std::vector<uint8_t> buildUnsignedCreateRecord(
    const String &login,
    const String &blockchainName,
    const std::vector<String> &accessServers,
    const uint8_t recoveryPub[32],
    const uint8_t rootPub[32],
    const uint8_t clientPub[32],
    const uint8_t blockchainPub[32],
    const uint8_t lastBlockSignature[64],
    uint64_t paidLimitBytes,
    uint64_t createdAtMs);
static std::vector<uint8_t> buildCreateInstructionData(
    const String &login,
    const String &blockchainName,
    const std::vector<String> &accessServers,
    const uint8_t recoveryPub[32],
    const uint8_t rootPub[32],
    const uint8_t clientPub[32],
    const uint8_t blockchainPub[32],
    const uint8_t lastBlockSignature[64],
    const uint8_t rootSignature[64],
    uint64_t createdAtMs);
static std::vector<uint8_t> buildEd25519InstructionData(const uint8_t signature[64], const uint8_t publicKey[32], const uint8_t messageHash[32]);
static std::vector<uint8_t> serializeUnsignedRecordState(const ShinePdaUserState &state);
static std::vector<uint8_t> buildUpdateInstructionData(const ShinePdaUserState &state,
                                                       uint32_t nextVersion,
                                                       uint64_t updatedAtMs,
                                                       const uint8_t prevHash32[32],
                                                       const uint8_t rootSignature64[64]);
static std::vector<uint8_t> buildLegacyMessage(
    const uint8_t recentBlockhash[32],
    const uint8_t clientPub[32],
    const uint8_t userPda[32],
    const uint8_t inflowVault[32],
    const uint8_t economyConfig[32],
    const std::vector<uint8_t> &edRootData,
    const std::vector<uint8_t> &edBchData,
    const std::vector<uint8_t> &createData);
static std::vector<uint8_t> buildUpdateLegacyMessage(
    const uint8_t recentBlockhash[32],
    const uint8_t clientPub[32],
    const uint8_t userPda[32],
    const uint8_t inflowVault[32],
    const uint8_t economyConfig[32],
    const std::vector<uint8_t> &edRootData,
    const std::vector<uint8_t> &edBchData,
    const std::vector<uint8_t> &updateData);
static bool signMessageEd25519(const std::vector<uint8_t> &message, const uint8_t secretKey[64], uint8_t signature[64]);
static String encodeTransactionBase64(const uint8_t signature[64], const std::vector<uint8_t> &message);
static bool shortVecDecode(const std::vector<uint8_t> &bytes, size_t &offset, uint32_t &valueOut);
static bool parseSolanaSignerIndex(const std::vector<uint8_t> &txBytes, const uint8_t targetPub32[32], uint32_t &signerIndexOut, size_t &messageOffsetOut, String &errorOut);
static bool signSelectedWalletTransactionBase64(const String &publicKeyBase58,
                                                const String &txBase64,
                                                String &signedTxBase64Out,
                                                String &signatureBase58Out,
                                                String &errorOut);
static bool sendWalletRpcResponse(const String &toLogin,
                                  const String &targetSessionId,
                                  const String &callId,
                                  const String &responseData);
static void queueWalletSignRequest(const PendingWalletRpcRequest &item,
                                   const String &requestId,
                                   const String &publicKeyBase58,
                                   const String &transactionBase64,
                                   const String &comment);
static void clearWalletSignRequest();
static bool respondToActiveWalletSignRequest(bool approved);
static bool awaitTransactionConfirmation(const String &signatureB58, String &messageOut);
static bool registerHomeserverOnSolana(String &messageOut);
static void executeRegisterAccountFlow(const char *triggerSource, bool showResultScreen);
static bool updateHomeserverSessionOnSolana(bool requireExisting, String &messageOut);
static void loadRegisterDiagDetailsFromPrefs();
static void saveRegisterDiagDetailsToPrefs(const String &details);
static void clearRegisterDiagDetailsFromPrefs();
static void saveRegisterDiag(const String &status, const String &summary, const String &details);
static void saveRegisterDiagCheckpoint(const String &summary, const String &details);
static void printRegisterDiagToSerial();
static void clearRegisterDiag();
static void handleUsbSerialCommands();
static void prepareRegisterAccountScreen();
static void prepareHomeserverPdaActionScreen();
static String buildSessionKeyStringFromPublicBase64(const String &pubB64);
static bool deriveKeypairFromSeed32(const uint8_t seed32[32], uint8_t pub32[32], uint8_t sec64[64]);
static bool deriveSeedKeypairFromBase58(const String &seedB58, uint8_t seed32[32], uint8_t pub32[32], uint8_t sec64[64]);
static bool findProgramAddress(const std::vector<std::vector<uint8_t>> &seeds, const char *programIdB58, uint8_t out32[32]);
static bool readShineUserPda(const String &login, ShinePdaUserState &outState, String &errorOut);
static bool parseShineUserPdaBytes(const std::vector<uint8_t> &bytes, ShinePdaUserState &outState, String &errorOut);
static void refreshAccountPdaStatus();
static void manageAccountPdaRefresh();
static void saveShineConnectDiag(const String &status, const String &summary, const String &details);
static bool ensureWebSocketConnected(SimpleWebSocketClient &ws, const String &url, String &errorOut);
static void closeWebSocket(SimpleWebSocketClient &ws);
static bool wsSendText(SimpleWebSocketClient &ws, const String &payload);
static bool wsReadTextFrame(SimpleWebSocketClient &ws, String &messageOut, uint32_t timeoutMs);
static bool shineWsRequest(SimpleWebSocketClient &ws, const String &op, const String &payloadJson, String &responseOut, uint32_t timeoutMs = SHINE_RPC_TIMEOUT_MS);
static bool ensureShineSessionAuthenticated(String &errorOut);
static void manageShineConnection();

static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
  uint32_t w = area->x2 - area->x1 + 1;
  uint32_t h = area->y2 - area->y1 + 1;
#if (LV_COLOR_16_SWAP != 0)
  gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#else
  gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#endif
  lv_disp_flush_ready(disp);
}

static void lvglTick(void *arg) {
  LV_UNUSED(arg);
  lv_tick_inc(LVGL_TICK_MS);
}

static SwipeDirection detectSwipe(int16_t startX, int16_t startY, int16_t endX, int16_t endY) {
  int16_t dx = endX - startX;
  int16_t dy = endY - startY;
  int16_t absDx = abs(dx);
  int16_t absDy = abs(dy);

  if (absDx < SWIPE_THRESHOLD && absDy < SWIPE_THRESHOLD) {
    return SWIPE_NONE;
  }

  if (absDx >= absDy) {
    return dx > 0 ? SWIPE_RIGHT : SWIPE_LEFT;
  }

  return dy > 0 ? SWIPE_DOWN : SWIPE_UP;
}

static bool movedTooFarForTap(int16_t startX, int16_t startY, int16_t endX, int16_t endY) {
  return abs(endX - startX) >= TAP_CANCEL_THRESHOLD || abs(endY - startY) >= TAP_CANCEL_THRESHOLD;
}

static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
  LV_UNUSED(indevDrv);
  int16_t x = 0;
  int16_t y = 0;
  bool touching = gTouch.getPoint(&x, &y, 1) > 0;

  if (touching) {
    if (!gTouchDown) {
      gTouchDown = true;
      gTouchSequence++;
      gTouchStartX = x;
      gTouchStartY = y;
      gBlockClick = false;
      gSuppressTouchUntilRelease = false;
    }
    gTouchLastX = x;
    gTouchLastY = y;
    if (movedTooFarForTap(gTouchStartX, gTouchStartY, gTouchLastX, gTouchLastY)) {
      gBlockClick = true;
      gSuppressTouchUntilRelease = true;
    }
    if (gSuppressTouchUntilRelease) {
      data->state = LV_INDEV_STATE_REL;
      data->point.x = gTouchLastX;
      data->point.y = gTouchLastY;
      return;
    }
    data->state = LV_INDEV_STATE_PR;
    data->point.x = x;
    data->point.y = y;
    return;
  }

  if (gTouchDown) {
    gTouchDown = false;
    gPendingSwipe = detectSwipe(gTouchStartX, gTouchStartY, gTouchLastX, gTouchLastY);
    if (gCurrentScreen == SCREEN_WALLET_QR
        && gPendingSwipe == SWIPE_NONE
        && !movedTooFarForTap(gTouchStartX, gTouchStartY, gTouchLastX, gTouchLastY)) {
      gWalletQrTapReturnPending = true;
    }
  }

  gSuppressTouchUntilRelease = false;
  gBlockClick = false;

  data->state = LV_INDEV_STATE_REL;
  data->point.x = gTouchLastX;
  data->point.y = gTouchLastY;
}

static void setRootStyle() {
  lv_obj_set_style_bg_color(gRoot, lv_color_hex(0x08111B), 0);
  lv_obj_set_style_bg_opa(gRoot, LV_OPA_COVER, 0);
  lv_obj_set_style_pad_all(gRoot, 0, 0);
  lv_obj_set_scrollbar_mode(gRoot, LV_SCROLLBAR_MODE_OFF);
}

static lv_obj_t *makeTitle(const char *text, lv_coord_t y, const lv_font_t *font) {
  lv_obj_t *label = lv_label_create(gRoot);
  lv_label_set_text(label, text);
  lv_obj_set_style_text_font(label, font, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
  lv_obj_align(label, LV_ALIGN_TOP_MID, 0, y);
  return label;
}

static lv_obj_t *makeBody(const char *text, lv_coord_t y, lv_coord_t width) {
  lv_obj_t *label = lv_label_create(gRoot);
  lv_label_set_text(label, text);
  lv_obj_set_width(label, width);
  lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xD9E1EA), 0);
  lv_obj_align(label, LV_ALIGN_TOP_MID, 0, y);
  return label;
}

static void showMessageAt(const String &text, lv_coord_t y) {
  lv_obj_t *label = lv_label_create(gRoot);
  lv_label_set_text(label, text.c_str());
  lv_obj_set_width(label, 420);
  lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(label, &lv_font_montserrat_16, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xB8C6D3), 0);
  lv_obj_align(label, LV_ALIGN_TOP_MID, 0, y);
}

static void clearSavedWifiList() {
  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    gKnownWifiSsids[i] = "";
    gKnownWifiPasswords[i] = "";
  }
}

static int findKnownWifiIndex(const String &ssid) {
  if (ssid.isEmpty()) {
    return -1;
  }
  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    if (gKnownWifiSsids[i] == ssid) {
      return i;
    }
  }
  return -1;
}

static String savedPasswordForSsid(const String &ssid) {
  int index = findKnownWifiIndex(ssid);
  return index >= 0 ? gKnownWifiPasswords[index] : "";
}

static String splitFixedWidth(const String &value, size_t chunkSize) {
  if (chunkSize == 0 || value.isEmpty()) {
    return value;
  }

  String out;
  for (size_t i = 0; i < value.length(); ++i) {
    if (i > 0 && (i % chunkSize) == 0) {
      out += '\n';
    }
    out += value.charAt(i);
  }
  return out;
}

static void sha256calc(const uint8_t *in, size_t len, uint8_t *out32) {
  mbedtls_sha256_context ctx;
  mbedtls_sha256_init(&ctx);
  mbedtls_sha256_starts(&ctx, 0);
  mbedtls_sha256_update(&ctx, in, len);
  mbedtls_sha256_finish(&ctx, out32);
  mbedtls_sha256_free(&ctx);
}

static String base64Std(const uint8_t *data, size_t len) {
  size_t needed = ((len + 2) / 3) * 4 + 4;
  std::vector<uint8_t> out(needed, 0);
  size_t outLen = 0;
  if (mbedtls_base64_encode(out.data(), out.size(), &outLen, data, len) != 0) {
    return "";
  }
  if (outLen >= out.size()) {
    return "";
  }
  out[outLen] = '\0';
  return String(reinterpret_cast<const char *>(out.data()));
}

static String base58From32(const uint8_t *data32) {
  char out[64] = {};
  shineSecretBase58Encode(data32, 32, out, sizeof(out));
  return String(out);
}

static bool base58ToFixed32(const String &value, uint8_t out[32]) {
  size_t outLen = 32;
  String error;
  if (!shineSecretBase58Decode(value.c_str(), out, &outLen, 32, error)) {
    return false;
  }
  return outLen == 32;
}

static bool base64DecodeStd(const String &value, std::vector<uint8_t> &out) {
  out.clear();
  String normalized = value;
  normalized.trim();
  if (normalized.isEmpty()) {
    return false;
  }
  size_t maxLen = ((normalized.length() + 3) / 4) * 3 + 4;
  out.resize(maxLen);
  size_t outLen = 0;
  if (mbedtls_base64_decode(out.data(), out.size(), &outLen,
                            reinterpret_cast<const uint8_t *>(normalized.c_str()),
                            normalized.length()) != 0) {
    out.clear();
    return false;
  }
  out.resize(outLen);
  return true;
}

static String bytesToBase64String(const uint8_t *data, size_t len) {
  return base64Std(data, len);
}

static String bytesToHexString(const uint8_t *data, size_t len) {
  static const char *kHex = "0123456789abcdef";
  String out;
  out.reserve(len * 2);
  for (size_t i = 0; i < len; ++i) {
    uint8_t v = data[i];
    out += kHex[(v >> 4) & 0x0F];
    out += kHex[v & 0x0F];
  }
  return out;
}

static String normalizeLoginValue(const String &value) {
  String out = value;
  out.trim();
  out.toLowerCase();
  return out;
}

static bool isValidShineServerLoginValue(const String &value) {
  if (value.isEmpty() || value.length() > 20) {
    return false;
  }
  for (size_t i = 0; i < value.length(); ++i) {
    char ch = value.charAt(i);
    if (!(isAlphaNumeric((unsigned char)ch) || ch == '_')) {
      return false;
    }
  }
  return true;
}

static String abbreviateValue(const String &value, size_t head = 8, size_t tail = 6) {
  if (value.length() <= head + tail + 3) {
    return value;
  }
  return value.substring(0, head) + "..." + value.substring(value.length() - tail);
}

static String jsonEscape(const String &value) {
  String out;
  out.reserve(value.length() + 8);
  for (size_t i = 0; i < value.length(); ++i) {
    char ch = value.charAt(i);
    switch (ch) {
      case '\\': out += "\\\\"; break;
      case '"': out += "\\\""; break;
      case '\n': out += "\\n"; break;
      case '\r': out += "\\r"; break;
      case '\t': out += "\\t"; break;
      default: out += ch; break;
    }
  }
  return out;
}

static bool jsonStringField(const String &json, const String &field, String &valueOut) {
  String needle = "\"" + field + "\"";
  int keyPos = json.indexOf(needle);
  if (keyPos < 0) {
    return false;
  }
  int colon = json.indexOf(':', keyPos + needle.length());
  if (colon < 0) {
    return false;
  }
  int quote = json.indexOf('"', colon + 1);
  if (quote < 0) {
    return false;
  }
  String out;
  bool escape = false;
  for (int i = quote + 1; i < (int)json.length(); ++i) {
    char ch = json.charAt(i);
    if (escape) {
      switch (ch) {
        case 'n': out += '\n'; break;
        case 'r': out += '\r'; break;
        case 't': out += '\t'; break;
        default: out += ch; break;
      }
      escape = false;
      continue;
    }
    if (ch == '\\') {
      escape = true;
      continue;
    }
    if (ch == '"') {
      valueOut = out;
      return true;
    }
    out += ch;
  }
  return false;
}

static bool jsonBoolField(const String &json, const String &field, bool &valueOut) {
  String needle = "\"" + field + "\"";
  int keyPos = json.indexOf(needle);
  if (keyPos < 0) {
    return false;
  }
  int colon = json.indexOf(':', keyPos + needle.length());
  if (colon < 0) {
    return false;
  }
  int pos = colon + 1;
  while (pos < (int)json.length() && isspace((unsigned char)json[pos])) {
    pos++;
  }
  if (json.startsWith("true", pos)) {
    valueOut = true;
    return true;
  }
  if (json.startsWith("false", pos)) {
    valueOut = false;
    return true;
  }
  return false;
}

static String formatPairingShortCode(const String &value) {
  String digits;
  for (int i = 0; i < (int)value.length(); ++i) {
    char ch = value.charAt(i);
    if (ch >= '0' && ch <= '9') {
      digits += ch;
    }
  }
  while (digits.length() < 10) {
    digits = String("0") + digits;
  }
  if (digits.length() > 10) {
    digits = digits.substring(0, 10);
  }
  String out;
  for (int i = 0; i < 10; i += 2) {
    if (!out.isEmpty()) out += " ";
    out += digits.substring(i, i + 2);
  }
  return out;
}

static bool pairingMenuVisible() {
  return gShineAuthenticated;
}

static int settingsMenuCount() {
  return pairingMenuVisible() ? 4 : 3;
}

static String settingsMenuLabel(int itemIndex) {
  if (pairingMenuVisible()) {
    switch (itemIndex) {
      case 0: return "1. Device requests";
      case 1: return "2. Wi-Fi";
      case 2: return "3. Server";
      case 3: return "4. Account";
      default: return "";
    }
  }
  switch (itemIndex) {
    case 0: return "1. Wi-Fi";
    case 1: return "2. Server";
    case 2: return "3. Account";
    default: return "";
  }
}

static ActionId settingsMenuAction(int itemIndex) {
  if (pairingMenuVisible()) {
    switch (itemIndex) {
      case 0: return ACTION_OPEN_PAIRING_REQUESTS;
      case 1: return ACTION_OPEN_WIFI;
      case 2: return ACTION_OPEN_SERVER;
      case 3: return ACTION_OPEN_ACCOUNT;
      default: return ACTION_NONE;
    }
  }
  switch (itemIndex) {
    case 0: return ACTION_OPEN_WIFI;
    case 1: return ACTION_OPEN_SERVER;
    case 2: return ACTION_OPEN_ACCOUNT;
    default: return ACTION_NONE;
  }
}

static String pairingSessionKindLabel(int sessionType) {
  return sessionType == 50 ? "Wallet session" : "Client session";
}

static String pairingSessionNameLabel(const PairingRequestUiItem &item) {
  String value = item.requesterClientPlatform;
  value.trim();
  return value.isEmpty() ? "Unknown client" : value;
}

static bool findJsonArrayBounds(const String &json, const String &field, int &startOut, int &endOut) {
  String needle = "\"" + field + "\"";
  int keyPos = json.indexOf(needle);
  if (keyPos < 0) return false;
  int colon = json.indexOf(':', keyPos + needle.length());
  if (colon < 0) return false;
  int start = json.indexOf('[', colon + 1);
  if (start < 0) return false;
  bool inString = false;
  bool escape = false;
  int depth = 0;
  for (int i = start; i < (int)json.length(); ++i) {
    char ch = json.charAt(i);
    if (escape) {
      escape = false;
      continue;
    }
    if (ch == '\\') {
      escape = true;
      continue;
    }
    if (ch == '"') {
      inString = !inString;
      continue;
    }
    if (inString) continue;
    if (ch == '[') depth++;
    if (ch == ']') {
      depth--;
      if (depth == 0) {
        startOut = start;
        endOut = i;
        return true;
      }
    }
  }
  return false;
}

static bool extractJsonObjectAt(const String &json, int startIndex, int &endOut, String &objectOut) {
  int start = json.indexOf('{', startIndex);
  if (start < 0) return false;
  bool inString = false;
  bool escape = false;
  int depth = 0;
  for (int i = start; i < (int)json.length(); ++i) {
    char ch = json.charAt(i);
    if (escape) {
      escape = false;
      continue;
    }
    if (ch == '\\') {
      escape = true;
      continue;
    }
    if (ch == '"') {
      inString = !inString;
      continue;
    }
    if (inString) continue;
    if (ch == '{') depth++;
    if (ch == '}') {
      depth--;
      if (depth == 0) {
        endOut = i;
        objectOut = json.substring(start, i + 1);
        return true;
      }
    }
  }
  return false;
}

static bool parsePairingRequestsResponse(const String &json, std::vector<PairingRequestUiItem> &itemsOut, String &errorOut) {
  itemsOut.clear();
  errorOut = "";
  uint64_t status = 0;
  if (!jsonInt64Field(json, "status", status) || status != 200) {
    errorOut = "ListTrustedDeviceLoginRequests rejected";
    return false;
  }
  int arrayStart = 0;
  int arrayEnd = 0;
  if (!findJsonArrayBounds(json, "requests", arrayStart, arrayEnd)) {
    errorOut = "requests array missing";
    return false;
  }
  int cursor = arrayStart + 1;
  while (cursor < arrayEnd) {
    String objectJson;
    int objectEnd = 0;
    if (!extractJsonObjectAt(json, cursor, objectEnd, objectJson) || objectEnd > arrayEnd) {
      break;
    }
    PairingRequestUiItem item;
    uint64_t sessionType = 0;
    uint64_t expiresAtMs = 0;
    jsonStringField(objectJson, "pairingId", item.pairingId);
    jsonStringField(objectJson, "requesterSessionKey", item.requesterSessionKey);
    jsonStringField(objectJson, "requesterClientPlatform", item.requesterClientPlatform);
    jsonStringField(objectJson, "shortCode", item.shortCode);
    jsonInt64Field(objectJson, "requesterSessionType", sessionType);
    jsonInt64Field(objectJson, "expiresAtMs", expiresAtMs);
    item.requesterSessionType = (int)sessionType;
    item.expiresAtMs = expiresAtMs;
    if (!item.pairingId.isEmpty()) {
      itemsOut.push_back(item);
    }
    cursor = objectEnd + 1;
  }
  return true;
}

static bool parseUrlHostPortPath(const String &url, String &hostOut, uint16_t &portOut, String &pathOut, bool &secureOut) {
  hostOut = "";
  pathOut = "/";
  portOut = 0;
  secureOut = false;

  int schemeEnd = url.indexOf("://");
  if (schemeEnd <= 0) {
    return false;
  }
  String scheme = url.substring(0, schemeEnd);
  secureOut = (scheme == "https" || scheme == "wss");
  int hostStart = schemeEnd + 3;
  int slash = url.indexOf('/', hostStart);
  String hostPort = slash >= 0 ? url.substring(hostStart, slash) : url.substring(hostStart);
  pathOut = slash >= 0 ? url.substring(slash) : "/";
  int atPos = hostPort.lastIndexOf('@');
  if (atPos >= 0) {
    hostPort = hostPort.substring(atPos + 1);
  }
  int colon = hostPort.lastIndexOf(':');
  if (colon > 0 && hostPort.indexOf(']') < 0) {
    hostOut = hostPort.substring(0, colon);
    portOut = (uint16_t)hostPort.substring(colon + 1).toInt();
  } else {
    hostOut = hostPort;
    portOut = secureOut ? 443 : 80;
  }
  hostOut.trim();
  if (pathOut.isEmpty()) {
    pathOut = "/";
  }
  return hostOut.length() > 0 && portOut > 0;
}

static String homeserverKeySuffix() {
  String name = gHomeserverValue;
  name.trim();
  if (name.isEmpty()) {
    name = "homeserver1";
  }
  return String("homeserver.key:") + name;
}

static void deriveKeyPairFromSecretSuffix(const uint8_t *secret32, const String &suffix, String &pubB58, String &privB58) {
  pubB58 = "";
  privB58 = "";
  if (!secret32) {
    return;
  }
  const char *prefix = "SHiNE-key";
  uint8_t seed[32] = {};
  uint8_t pub[32] = {};
  std::vector<uint8_t> material;
  material.reserve(10 + 1 + 32 + 1 + suffix.length());
  material.insert(material.end(), prefix, prefix + strlen(prefix));
  material.push_back(0);
  material.insert(material.end(), secret32, secret32 + 32);
  material.push_back(0);
  material.insert(material.end(), suffix.c_str(), suffix.c_str() + suffix.length());
  sha256calc(material.data(), material.size(), seed);
  Ed25519::derivePublicKey(pub, seed);
  privB58 = base58From32(seed);
  pubB58 = base58From32(pub);
}

static void clearDerivedKeys() {
  gRootPubB58 = "";
  gRootPrivB58 = "";
  gRecoveryPubB58 = "";
  gRecoveryPrivB58 = "";
  gBlockchainPubB58 = "";
  gBlockchainPrivB58 = "";
  gDevicePubB58 = "";
  gDevicePrivB58 = "";
  gHomeserverPubB58 = "";
  gHomeserverPrivB58 = "";
  gCustomWalletPubB58 = "";
  gCustomWalletPrivB58 = "";
}

static void refreshDerivedKeys() {
  clearDerivedKeys();
  if (!gSecretConfigured) {
    return;
  }
  deriveKeyPairFromSecretSuffix(gSecretBytes, "recovery.key", gRecoveryPubB58, gRecoveryPrivB58);
  deriveKeyPairFromSecretSuffix(gSecretBytes, "root.key", gRootPubB58, gRootPrivB58);
  deriveKeyPairFromSecretSuffix(gSecretBytes, "blockchain.key", gBlockchainPubB58, gBlockchainPrivB58);
  deriveKeyPairFromSecretSuffix(gSecretBytes, "client.key", gDevicePubB58, gDevicePrivB58);
  deriveKeyPairFromSecretSuffix(gSecretBytes, homeserverKeySuffix(), gHomeserverPubB58, gHomeserverPrivB58);
  String customName = gCustomWalletName;
  customName.trim();
  if (!customName.isEmpty()) {
    deriveKeyPairFromSecretSuffix(gSecretBytes, String("wallet.") + customName, gCustomWalletPubB58, gCustomWalletPrivB58);
  }
}

static String selectedWalletDisplayName() {
  switch (gSelectedWalletType) {
    case WALLET_SELECTION_ROOT:
      return "RootKey";
    case WALLET_SELECTION_CUSTOM: {
      String customName = gCustomWalletName;
      customName.trim();
      return customName.isEmpty() ? String("Custom") : customName;
    }
    case WALLET_SELECTION_DEVICE:
    default:
      return "ClientKey";
  }
}

static String selectedWalletTypeCode() {
  switch (gSelectedWalletType) {
    case WALLET_SELECTION_ROOT:
      return "root.key";
    case WALLET_SELECTION_CUSTOM:
      return "custom";
    case WALLET_SELECTION_DEVICE:
    default:
      return "client.key";
  }
}

static String selectedWalletDerivationSuffix() {
  switch (gSelectedWalletType) {
    case WALLET_SELECTION_ROOT:
      return "root.key";
    case WALLET_SELECTION_CUSTOM: {
      String customName = gCustomWalletName;
      customName.trim();
      return customName.isEmpty() ? String("") : String("wallet.") + customName;
    }
    case WALLET_SELECTION_DEVICE:
    default:
      return "client.key";
  }
}

static String selectedWalletPublicKeyB58() {
  switch (gSelectedWalletType) {
    case WALLET_SELECTION_ROOT:
      return gRootPubB58;
    case WALLET_SELECTION_CUSTOM:
      return gCustomWalletPubB58;
    case WALLET_SELECTION_DEVICE:
    default:
      return gDevicePubB58;
  }
}

static String selectedWalletPrivateKeyB58() {
  switch (gSelectedWalletType) {
    case WALLET_SELECTION_ROOT:
      return gRootPrivB58;
    case WALLET_SELECTION_CUSTOM:
      return gCustomWalletPrivB58;
    case WALLET_SELECTION_DEVICE:
    default:
      return gDevicePrivB58;
  }
}

static void secretScrollBoostSet(bool enable) {
  if (enable) {
    lv_indev_t *indev = lv_indev_get_act();
    if (!indev || !indev->driver) {
      return;
    }
    if (!gSecretScrollThrowApplied) {
      gSecretScrollIndevDriver = indev->driver;
      gSecretScrollThrowSaved = gSecretScrollIndevDriver->scroll_throw;
      gSecretScrollIndevDriver->scroll_throw = (uint8_t)(gSecretScrollThrowSaved / 4);
      gSecretScrollThrowApplied = true;
    }
  } else if (gSecretScrollThrowApplied && gSecretScrollIndevDriver) {
    gSecretScrollIndevDriver->scroll_throw = gSecretScrollThrowSaved;
    gSecretScrollIndevDriver = nullptr;
    gSecretScrollThrowSaved = 0;
    gSecretScrollThrowApplied = false;
  }
}

static void secretScrollEventCb(lv_event_t *e) {
  lv_event_code_t code = lv_event_get_code(e);
  if (code == LV_EVENT_SCROLL_BEGIN) {
    lv_anim_t *anim = lv_event_get_scroll_anim(e);
    if (anim && anim->time > 0) {
      uint32_t boostedTime = (uint32_t)anim->time / 4;
      if (boostedTime < 80U) {
        boostedTime = 80U;
      }
      lv_anim_set_time(anim, boostedTime);
    }
    secretScrollBoostSet(true);
  } else if (code == LV_EVENT_SCROLL_END || code == LV_EVENT_DELETE) {
    secretScrollBoostSet(false);
  }
}

static bool selectedWalletAvailable() {
  return !selectedWalletPublicKeyB58().isEmpty();
}

static void refreshSelectedWalletBalanceState() {
  gBalanceStatusMessage = selectedWalletAvailable() ? "Wallet: tap to load balance" : "Wallet: secret not set";
  gBalanceAutoRefreshPending = selectedWalletAvailable();
  gLastBalanceAutoRefreshAttemptMs = 0;
}

static bool deriveKeypairFromSeed32(const uint8_t seed32[32], uint8_t pub32[32], uint8_t sec64[64]) {
  return crypto_sign_seed_keypair(pub32, sec64, seed32) == 0;
}

static bool deriveSeedKeypairFromBase58(const String &seedB58, uint8_t seed32[32], uint8_t pub32[32], uint8_t sec64[64]) {
  if (!base58ToFixed32(seedB58, seed32)) {
    return false;
  }
  return deriveKeypairFromSeed32(seed32, pub32, sec64);
}

static void saveShineSessionPrefs() {
  if (gShineSessionId.isEmpty() || gShineSessionKey.isEmpty()) {
    gPrefs.remove("shine_sess_id");
    gPrefs.remove("shine_sess_key");
    gPrefs.remove("shine_store_pwd");
    return;
  }
  gPrefs.putString("shine_sess_id", gShineSessionId);
  gPrefs.putString("shine_sess_key", gShineSessionKey);
  gPrefs.putString("shine_store_pwd", gShineStoragePwd);
}

static void closeWebSocket(SimpleWebSocketClient &ws) {
  if (ws.client.connected()) {
    ws.client.stop();
  }
  ws.connected = false;
}

static void clearShineSessionState(bool clearStoredSession) {
  closeWebSocket(gShineWs);
  gShineAuthenticated = false;
  gLastShinePingMs = 0;
  if (clearStoredSession) {
    gShineSessionId = "";
    gShineSessionKey = "";
    gShineStoragePwd = "";
    saveShineSessionPrefs();
  }
}

static bool shouldPauseShineReconnectForUi() {
  switch (gCurrentScreen) {
    case SCREEN_SETTINGS_MENU:
    case SCREEN_WIFI:
    case SCREEN_SERVER:
    case SCREEN_ACCOUNT:
    case SCREEN_ACCOUNT_HOMESERVER:
    case SCREEN_ACCOUNT_SECRET:
    case SCREEN_SECRET_SHOW:
    case SCREEN_SECRET_GENERATE_INFO:
    case SCREEN_SECRET_GENERATE_RUNNING:
    case SCREEN_SECRET_GENERATE_CANCEL_CONFIRM:
    case SCREEN_REGISTER_ACCOUNT_CONFIRM:
    case SCREEN_REGISTER_ACCOUNT_RESULT:
    case SCREEN_HOMESERVER_PDA_CONFIRM:
    case SCREEN_HOMESERVER_PDA_RESULT:
    case SCREEN_TEXT_EDIT:
      return true;
    default:
      return false;
  }
}

static void markAccountStateDirty() {
  gAccountCheckPending = true;
  gLastAccountCheckMs = 0;
  gAccountPdaStatus = ACCOUNT_PDA_UNKNOWN;
  gAccountPdaStatusMessage = "Account not checked";
  gShowRegisterAccountButton = false;
  gShowHomeserverPdaActionButton = false;
  gHomeserverPdaActionReason = "";
  gHomeserverPdaActionMessage = "";
  gHomeserverPdaActionDetail = "";
  gHomeserverPdaCanAdd = false;
  gHomeserverPdaCanFix = false;
  gHomeserverPdaResultMessage = "";
  gHomeserverPdaResultDetails = "";
  gHomeserverPdaResultSuccess = false;
  gCachedAccountPdaValid = false;
  gCachedAccountPdaLogin = "";
  gCachedAccountPdaState = ShinePdaUserState{};
  gUserPdaAddress = "";
  gRegistrationSignature = "";
  gRegisterConfirmMessage = "";
  gRegisterConfirmBalanceLine = "";
  gRegisterConfirmPdaLine = "";
  gRegisterConfirmHomeserverLine = "";
  gRegisterConfirmCanSubmit = false;
  gRegisterResultMessage = "";
  gRegisterResultDetails = "";
  gRegisterResultSuccess = false;
  clearShineSessionState(true);
  gShineStatusLine = "SHiNE: account not configured";
}

static bool findProgramAddress(const std::vector<std::vector<uint8_t>> &seeds, const char *programIdB58, uint8_t out32[32]) {
  uint8_t programId[32] = {};
  if (!base58ToFixed32(String(programIdB58), programId)) {
    return false;
  }
  for (int bump = 255; bump >= 0; --bump) {
    crypto_hash_sha256_state st;
    crypto_hash_sha256_init(&st);
    for (const auto &seed : seeds) {
      crypto_hash_sha256_update(&st, seed.data(), seed.size());
    }
    uint8_t bumpByte = (uint8_t)bump;
    crypto_hash_sha256_update(&st, &bumpByte, 1);
    crypto_hash_sha256_update(&st, programId, 32);
    crypto_hash_sha256_update(&st,
                              reinterpret_cast<const unsigned char *>(kProgramDerivedAddressMarker),
                              strlen(kProgramDerivedAddressMarker));
    crypto_hash_sha256_final(&st, out32);
    ge25519_p3 point;
    if (ge25519_frombytes(&point, out32) != 0) {
      return true;
    }
  }
  return false;
}

static bool isHttpUrl(const String &url) {
  return url.startsWith("http://") || url.startsWith("https://");
}

static bool httpPostJson(const String &url, const String &body, int &statusCode, String &payload) {
  statusCode = -1;
  payload = "";
  if (!isHttpUrl(url)) {
    return false;
  }

  HTTPClient http;
  WiFiClientSecure secureClient;
  WiFiClient plainClient;
  bool secure = url.startsWith("https://");
  if (secure) {
    secureClient.setInsecure();
    if (!http.begin(secureClient, url)) {
      return false;
    }
  } else {
    if (!http.begin(plainClient, url)) {
      return false;
    }
  }

  http.setTimeout(7000);
  http.addHeader("Content-Type", "application/json");
  statusCode = http.POST(body);
  if (statusCode > 0) {
    payload = http.getString();
  }
  http.end();
  return statusCode > 0;
}

static bool jsonInt64Field(const String &json, const String &field, uint64_t &valueOut) {
  String needle = "\"" + field + "\"";
  int keyPos = json.indexOf(needle);
  if (keyPos < 0) {
    return false;
  }
  int colon = json.indexOf(':', keyPos + needle.length());
  if (colon < 0) {
    return false;
  }
  int pos = colon + 1;
  while (pos < (int)json.length() && (json[pos] == ' ' || json[pos] == '\n' || json[pos] == '\r' || json[pos] == '\t')) {
    pos++;
  }
  int start = pos;
  while (pos < (int)json.length() && isDigit((unsigned char)json[pos])) {
    pos++;
  }
  if (pos == start) {
    return false;
  }
  valueOut = strtoull(json.substring(start, pos).c_str(), nullptr, 10);
  return true;
}

static String formatSolValue(uint64_t lamports) {
  uint64_t whole = lamports / 1000000000ULL;
  uint64_t frac = (lamports % 1000000000ULL) / 1000000ULL;
  char out[48];
  snprintf(out, sizeof(out), "Wallet: %llu.%03llu SOL",
           (unsigned long long)whole,
           (unsigned long long)frac);
  return String(out);
}

static bool refreshWalletBalance(String &messageOut) {
  uint64_t lamports = 0;
  if (!loadSelectedWalletBalanceLamports(lamports, messageOut)) {
    gBalanceStatusMessage = messageOut;
    return false;
  }

  gBalanceStatusMessage = formatSolValue(lamports);
  messageOut = gBalanceStatusMessage;
  return true;
}

static bool loadWalletBalanceLamports(uint64_t &lamportsOut, String &messageOut) {
  return loadBalanceLamportsForAddress(gDevicePubB58, lamportsOut, messageOut);
}

static bool loadSelectedWalletBalanceLamports(uint64_t &lamportsOut, String &messageOut) {
  return loadBalanceLamportsForAddress(selectedWalletPublicKeyB58(), lamportsOut, messageOut);
}

static bool loadBalanceLamportsForAddress(const String &address, uint64_t &lamportsOut, String &messageOut) {
  messageOut = "";
  lamportsOut = 0;
  if (WiFi.status() != WL_CONNECTED) {
    messageOut = "Wallet: Wi-Fi not connected";
    return false;
  }
  if (address.isEmpty()) {
    messageOut = "Wallet: unavailable";
    return false;
  }

  int code = -1;
  String payload;
  String req = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getBalance\",\"params\":[\"" + address + "\",{\"commitment\":\"confirmed\"}]}";
  if (!httpPostJson(gSolanaRpcUrl, req, code, payload)) {
    messageOut = "Wallet: RPC unavailable";
    return false;
  }

  if (!jsonInt64Field(payload, "value", lamportsOut)) {
    messageOut = "Wallet: balance unavailable";
    return false;
  }

  return true;
}

static String balanceHomeLine() {
  return gBalanceStatusMessage;
}

static String shineServerDisplayLabel() {
  if (!gShineServerUrl.isEmpty()) {
    return gShineServerUrl;
  }
  if (!currentShineServerLoginSource().isEmpty()) {
    return currentShineServerLoginSource();
  }
  return "not set";
}

static String wifiHomeRichLine() {
  String ssid = gWifiSavedSsid.isEmpty() ? String("not configured") : gWifiSavedSsid;
  if (WiFi.status() == WL_CONNECTED) {
    return String("Wi-Fi: ") + ssid + " #38B26D connected#";
  }
  return String("Wi-Fi: ") + ssid + " disconnected";
}

static String shineHomeRichLine() {
  String serverLabel = shineServerDisplayLabel();
  if (gShineStatusLine.endsWith(" connected")) {
    return String("SHiNE: ") + serverLabel + " #38B26D connected#";
  }
  if (gShineStatusLine.endsWith(" account not configured")) {
    return String("SHiNE: ") + serverLabel + " account not configured";
  }
  return String("SHiNE: ") + serverLabel + " unavailable";
}

static String walletQrUri() {
  String publicKey = selectedWalletPublicKeyB58();
  if (publicKey.isEmpty()) {
    return "";
  }
  return String("solana:") + publicKey;
}

static String walletQrAddressLine() {
  String publicKey = selectedWalletPublicKeyB58();
  return publicKey.isEmpty() ? String("Wallet not set") : publicKey;
}

static void releaseTransientUiBuffers() {
  if (gWalletQrCanvasBuffer) {
    heap_caps_free(gWalletQrCanvasBuffer);
    gWalletQrCanvasBuffer = nullptr;
  }
}

static void saveUiErrorDiag(const String &summary, const String &details) {
  saveRegisterDiag("error", summary, String("kind=ui_runtime\nscreen=wallet_qr\n") + details);
}

static String buildSessionKeyStringFromPublicBase64(const String &pubB64) {
  return String("ed25519/") + pubB64;
}

static String shineWsUrl() {
  String raw = gShineServerUrl;
  raw.trim();
  if (raw.isEmpty()) {
    return "";
  }
  if (raw.startsWith("ws://") || raw.startsWith("wss://")) {
    return raw;
  }
  if (raw.startsWith("http://")) {
    String tail = raw.substring(strlen("http://"));
    if (tail.indexOf('/') < 0) {
      tail += "/ws";
    } else if (tail.endsWith("/")) {
      tail += "ws";
    }
    return "ws://" + tail;
  }
  if (raw.startsWith("https://")) {
    String tail = raw.substring(strlen("https://"));
    if (tail.indexOf('/') < 0) {
      tail += "/ws";
    } else if (tail.endsWith("/")) {
      tail += "ws";
    }
    return "wss://" + tail;
  }
  if (raw.indexOf('/') < 0) {
    return "wss://" + raw + "/ws";
  }
  return "wss://" + raw;
}

static String shineHomeLine() {
  return gShineStatusLine;
}

static uint64_t shineNowMs() {
  int64_t value = (int64_t)millis() + gShineServerTimeOffsetMs;
  return value > 0 ? (uint64_t)value : (uint64_t)millis();
}

static bool getSystemEpochMs(uint64_t &epochMsOut) {
  struct timeval tv {};
  if (gettimeofday(&tv, nullptr) != 0) {
    return false;
  }
  if (tv.tv_sec < 1700000000) {
    return false;
  }
  epochMsOut = (uint64_t)tv.tv_sec * 1000ULL + (uint64_t)(tv.tv_usec / 1000ULL);
  return true;
}

static bool ensureNtpTimeSynced(String &errorOut) {
  errorOut = "";
  uint64_t epochMs = 0;
  if (getSystemEpochMs(epochMs)) {
    return true;
  }
  configTime(0, 0, "pool.ntp.org", "time.cloudflare.com", "time.google.com");
  for (int i = 0; i < 30; ++i) {
    delay(500);
    if (getSystemEpochMs(epochMs)) {
      return true;
    }
  }
  errorOut = "NTP time sync failed";
  return false;
}

static bool resolveShineServerUrlFromLogin(const String &serverLogin, String &serverUrlOut, String &errorOut) {
  errorOut = "";
  serverUrlOut = "";
  String cleanLogin = normalizeLoginValue(serverLogin);
  if (cleanLogin.isEmpty()) {
    errorOut = "Shine server login is not set";
    return false;
  }

  ShinePdaUserState serverState;
  if (!readShineUserPda(cleanLogin, serverState, errorOut)) {
    if (errorOut.isEmpty()) {
      errorOut = "Failed to read Shine server PDA";
    }
    return false;
  }
  if (!serverState.found) {
    errorOut = "Shine server PDA not found";
    return false;
  }
  if (!serverState.isServer) {
    errorOut = "Shine server PDA is not a server";
    return false;
  }
  if (serverState.serverAddress.isEmpty()) {
    errorOut = "Shine server address is empty";
    return false;
  }

  serverUrlOut = serverState.serverAddress;
  return true;
}

static String currentShineServerLoginSource() {
  if (gCachedAccountPdaValid && gCachedAccountPdaLogin == normalizeLoginValue(gLoginValue) && !gCachedAccountPdaState.accessServers.empty()) {
    String fromPda = normalizeLoginValue(gCachedAccountPdaState.accessServers.front());
    if (!fromPda.isEmpty()) {
      return fromPda;
    }
  }
  return normalizeLoginValue(gShineServerLogin);
}

static bool ensureCurrentShineServerUrl(String &errorOut) {
  errorOut = "";
  String login = currentShineServerLoginSource();
  if (login.isEmpty()) {
    errorOut = "Shine server login is not set";
    return false;
  }
  if (gShineServerUrl.isEmpty() || gResolvedShineServerLogin != login) {
    String resolvedUrl;
    if (!resolveShineServerUrlFromLogin(login, resolvedUrl, errorOut)) {
      return false;
    }
    gShineServerUrl = resolvedUrl;
    gResolvedShineServerLogin = login;
  }
  return true;
}

static void shortVecEncode(size_t value, std::vector<uint8_t> &out) {
  do {
    uint8_t byte = value & 0x7F;
    value >>= 7;
    if (value) {
      byte |= 0x80;
    }
    out.push_back(byte);
  } while (value);
}

static bool shortVecDecode(const std::vector<uint8_t> &bytes, size_t &offset, uint32_t &valueOut) {
  uint32_t value = 0;
  uint32_t shift = 0;
  while (offset < bytes.size() && shift <= 28) {
    uint8_t byte = bytes[offset++];
    value |= (uint32_t)(byte & 0x7F) << shift;
    if ((byte & 0x80) == 0) {
      valueOut = value;
      return true;
    }
    shift += 7;
  }
  return false;
}

static void pushU32LE(std::vector<uint8_t> &out, uint32_t value) {
  out.push_back((uint8_t)(value & 0xFF));
  out.push_back((uint8_t)((value >> 8) & 0xFF));
  out.push_back((uint8_t)((value >> 16) & 0xFF));
  out.push_back((uint8_t)((value >> 24) & 0xFF));
}

static void pushU64LE(std::vector<uint8_t> &out, uint64_t value) {
  for (int i = 0; i < 8; ++i) {
    out.push_back((uint8_t)((value >> (8 * i)) & 0xFF));
  }
}

static void pushStrU8(std::vector<uint8_t> &out, const String &value) {
  shortVecEncode(value.length(), out);
  for (size_t i = 0; i < value.length(); ++i) {
    out.push_back((uint8_t)value.charAt(i));
  }
}

static void pushFixed(std::vector<uint8_t> &out, const uint8_t *data, size_t len) {
  out.insert(out.end(), data, data + len);
}

static String bytesToBase58(const uint8_t *data, size_t len) {
  char out[160] = {};
  shineSecretBase58Encode(data, len, out, sizeof(out));
  return String(out);
}

static String buildBaseRpcRequest(const char *method, const String &paramsJson) {
  return "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"" + String(method) + "\",\"params\":" + paramsJson + "}";
}

static bool rpcCallSolana(const char *method, const String &paramsJson, String &payloadOut) {
  int code = -1;
  if (!httpPostJson(gSolanaRpcUrl, buildBaseRpcRequest(method, paramsJson), code, payloadOut)) {
    return false;
  }
  return code >= 200 && code < 300;
}

static bool rpcResponseHasError(const String &payload) {
  return payload.indexOf("\"error\"") >= 0;
}

static std::vector<uint8_t> buildLastBlockStateBytes(const String &login,
                                                     const String &blockchainName,
                                                     uint32_t lastBlockNumber,
                                                     const uint8_t *lastBlockHash32,
                                                     uint64_t usedBytes) {
  std::vector<uint8_t> out;
  out.reserve(80);
  pushFixed(out, (const uint8_t *)kLastBlockPrefix, strlen(kLastBlockPrefix));
  pushStrU8(out, login);
  pushStrU8(out, blockchainName);
  pushU32LE(out, lastBlockNumber);
  if (lastBlockHash32) {
    pushFixed(out, lastBlockHash32, 32);
  } else {
    out.insert(out.end(), 32, 0);
  }
  pushU64LE(out, usedBytes);
  return out;
}

static std::vector<uint8_t> serializeUnsignedRecordState(const ShinePdaUserState &state) {
  std::vector<uint8_t> out;
  out.reserve(640);
  pushFixed(out, (const uint8_t *)"SHiNE", 5);
  out.push_back(1);
  out.push_back(0);
  out.push_back(0);
  out.push_back(0);
  pushU64LE(out, state.createdAtMs);
  pushU64LE(out, state.updatedAtMs);
  pushU32LE(out, state.recordNumber);
  pushFixed(out, state.prevRecordHash32, 32);
  pushStrU8(out, state.login);
  out.push_back(state.isServer ? 8 : 7);

  out.push_back(kBlockTypeRecoveryKey);
  out.push_back(0);
  pushFixed(out, state.recoveryKey32, 32);

  out.push_back(kBlockTypeRootKey);
  out.push_back(0);
  pushFixed(out, state.rootKey32, 32);

  out.push_back(kBlockTypeClientKey);
  out.push_back(0);
  pushFixed(out, state.clientKey32, 32);

  out.push_back(kBlockTypeBlockchainRegistry);
  out.push_back(0);
  out.push_back(1);
  out.push_back(state.blockchainType);
  pushStrU8(out, state.blockchainName);
  pushFixed(out, state.blockchainKey32, 32);
  pushU64LE(out, state.paidLimitBytes);
  pushU64LE(out, state.usedBytes);
  pushU32LE(out, state.lastBlockNumber);
  pushFixed(out, state.lastBlockHash32, 32);
  pushFixed(out, state.lastBlockSignature64, 64);
  if (state.arweaveTxId.isEmpty()) {
    out.push_back(0);
  } else {
    out.push_back(1);
    pushStrU8(out, state.arweaveTxId);
  }

  if (state.isServer) {
    out.push_back(kBlockTypeServerProfile);
    out.push_back(0);
    out.push_back(1);
    out.push_back(state.addressFormatType);
    out.push_back(state.addressFormatVersion);
    pushStrU8(out, state.serverAddress);
    out.push_back((uint8_t)state.syncServers.size());
    for (const auto &value : state.syncServers) {
      pushStrU8(out, value);
    }
  }

  out.push_back(kBlockTypeAccessServers);
  out.push_back(0);
  out.push_back((uint8_t)state.accessServers.size());
  for (const auto &value : state.accessServers) {
    pushStrU8(out, value);
  }

  out.push_back(kBlockTypeSessions);
  out.push_back(0);
  out.push_back(state.sessionsMode);
  out.push_back((uint8_t)state.sessions.size());
  for (const auto &session : state.sessions) {
    out.push_back(session.sessionType);
    out.push_back(session.sessionVersion);
    pushStrU8(out, session.sessionName);
    pushFixed(out, session.sessionPubKey32, 32);
  }

  out.push_back(kBlockTypeTrustedState);
  out.push_back(0);
  out.push_back(state.trustedCount);

  uint16_t recordLen = (uint16_t)(out.size() + 64);
  out[7] = (uint8_t)(recordLen & 0xFF);
  out[8] = (uint8_t)((recordLen >> 8) & 0xFF);
  return out;
}

static std::vector<uint8_t> buildUpdateInstructionData(const ShinePdaUserState &state,
                                                       uint32_t nextVersion,
                                                       uint64_t updatedAtMs,
                                                       const uint8_t prevHash32[32],
                                                       const uint8_t rootSignature64[64]) {
  std::vector<uint8_t> out;
  out.reserve(640);
  out.push_back(4);
  pushStrU8(out, state.login);
  pushFixed(out, state.recoveryKey32, 32);
  pushFixed(out, state.rootKey32, 32);
  pushU64LE(out, state.createdAtMs);
  pushU64LE(out, updatedAtMs);
  pushU32LE(out, nextVersion);
  pushFixed(out, prevHash32, 32);
  pushU64LE(out, 0);
  pushFixed(out, state.clientKey32, 32);
  pushFixed(out, state.blockchainKey32, 32);
  pushStrU8(out, state.blockchainName);
  pushU64LE(out, state.usedBytes);
  pushU32LE(out, state.lastBlockNumber);
  pushFixed(out, state.lastBlockHash32, 32);
  pushFixed(out, state.lastBlockSignature64, 64);
  if (state.arweaveTxId.isEmpty()) {
    out.push_back(0);
  } else {
    out.push_back(1);
    pushStrU8(out, state.arweaveTxId);
  }
  out.push_back(state.isServer ? 1 : 0);
  if (state.isServer) {
    out.push_back(state.addressFormatType);
    out.push_back(state.addressFormatVersion);
    pushStrU8(out, state.serverAddress);
    out.push_back((uint8_t)state.syncServers.size());
    for (const auto &value : state.syncServers) {
      pushStrU8(out, value);
    }
  }
  out.push_back((uint8_t)state.accessServers.size());
  for (const auto &value : state.accessServers) {
    pushStrU8(out, value);
  }
  out.push_back(state.sessionsMode);
  out.push_back((uint8_t)state.sessions.size());
  for (const auto &session : state.sessions) {
    out.push_back(session.sessionType);
    out.push_back(session.sessionVersion);
    pushStrU8(out, session.sessionName);
    pushFixed(out, session.sessionPubKey32, 32);
  }
  out.push_back(state.trustedCount);
  pushFixed(out, rootSignature64, 64);
  return out;
}

static std::vector<uint8_t> buildUnsignedCreateRecord(
    const String &login,
    const String &blockchainName,
    const std::vector<String> &accessServers,
    const uint8_t recoveryPub[32],
    const uint8_t rootPub[32],
    const uint8_t clientPub[32],
    const uint8_t blockchainPub[32],
    const uint8_t lastBlockSignature[64],
    uint64_t paidLimitBytes,
    uint64_t createdAtMs) {
  std::vector<uint8_t> out;
  out.reserve(512);
  pushFixed(out, (const uint8_t *)"SHiNE", 5);
  out.push_back(1);
  out.push_back(0);
  out.push_back(0);
  out.push_back(0);
  pushU64LE(out, createdAtMs);
  pushU64LE(out, createdAtMs);
  pushU32LE(out, 0);
  out.insert(out.end(), 32, 0);
  pushStrU8(out, login);
  out.push_back(7);

  out.push_back(kBlockTypeRecoveryKey);
  out.push_back(0);
  pushFixed(out, recoveryPub, 32);

  out.push_back(kBlockTypeRootKey);
  out.push_back(0);
  pushFixed(out, rootPub, 32);

  out.push_back(kBlockTypeClientKey);
  out.push_back(0);
  pushFixed(out, clientPub, 32);

  out.push_back(kBlockTypeBlockchainRegistry);
  out.push_back(0);
  out.push_back(1);
  out.push_back(1);
  pushStrU8(out, blockchainName);
  pushFixed(out, blockchainPub, 32);
  pushU64LE(out, paidLimitBytes);
  pushU64LE(out, 0);
  pushU32LE(out, 0);
  out.insert(out.end(), 32, 0);
  pushFixed(out, lastBlockSignature, 64);
  out.push_back(0);

  out.push_back(kBlockTypeAccessServers);
  out.push_back(0);
  out.push_back((uint8_t)accessServers.size());
  for (const auto &value : accessServers) {
    pushStrU8(out, value);
  }

  out.push_back(kBlockTypeSessions);
  out.push_back(0);
  out.push_back(1);
  out.push_back(0);

  out.push_back(kBlockTypeTrustedState);
  out.push_back(0);
  out.push_back(0);

  uint16_t recordLen = (uint16_t)(out.size() + 64);
  out[7] = (uint8_t)(recordLen & 0xFF);
  out[8] = (uint8_t)((recordLen >> 8) & 0xFF);
  return out;
}

static std::vector<uint8_t> buildCreateInstructionData(
    const String &login,
    const String &blockchainName,
    const std::vector<String> &accessServers,
    const uint8_t recoveryPub[32],
    const uint8_t rootPub[32],
    const uint8_t clientPub[32],
    const uint8_t blockchainPub[32],
    const uint8_t lastBlockSignature[64],
    const uint8_t rootSignature[64],
    uint64_t createdAtMs) {
  std::vector<uint8_t> out;
  out.reserve(512);
  out.push_back(3);
  pushStrU8(out, login);
  pushFixed(out, recoveryPub, 32);
  pushFixed(out, rootPub, 32);
  pushU64LE(out, createdAtMs);
  pushU64LE(out, 0);
  pushFixed(out, clientPub, 32);
  pushFixed(out, blockchainPub, 32);
  pushStrU8(out, blockchainName);
  pushU64LE(out, 0);
  pushU32LE(out, 0);
  out.insert(out.end(), 32, 0);
  pushFixed(out, lastBlockSignature, 64);
  out.push_back(0);
  out.push_back(0);
  out.push_back((uint8_t)accessServers.size());
  for (const auto &value : accessServers) {
    pushStrU8(out, value);
  }
  out.push_back(1);
  out.push_back(0);
  out.push_back(0);
  pushFixed(out, rootSignature, 64);
  return out;
}

static std::vector<uint8_t> buildEd25519InstructionData(const uint8_t signature[64], const uint8_t publicKey[32], const uint8_t messageHash[32]) {
  const uint16_t sigOff = 16;
  const uint16_t pkOff = sigOff + 64;
  const uint16_t msgOff = pkOff + 32;
  std::vector<uint8_t> out(msgOff + 32, 0);
  out[0] = 1;
  out[1] = 0;
  out[2] = (uint8_t)(sigOff & 0xFF);
  out[3] = (uint8_t)((sigOff >> 8) & 0xFF);
  out[6] = (uint8_t)(pkOff & 0xFF);
  out[7] = (uint8_t)((pkOff >> 8) & 0xFF);
  out[10] = (uint8_t)(msgOff & 0xFF);
  out[11] = (uint8_t)((msgOff >> 8) & 0xFF);
  out[12] = 32;
  out[4] = out[8] = out[14] = 0xFF;
  out[5] = out[9] = out[15] = 0xFF;
  memcpy(out.data() + sigOff, signature, 64);
  memcpy(out.data() + pkOff, publicKey, 32);
  memcpy(out.data() + msgOff, messageHash, 32);
  return out;
}

static bool getLatestBlockhashBytes(uint8_t out[32], String &blockhashB58, String &messageOut) {
  for (int attempt = 0; attempt < 3; ++attempt) {
    String payload;
    if (rpcCallSolana("getLatestBlockhash", "[{\"commitment\":\"confirmed\"}]", payload)
        && jsonStringField(payload, "blockhash", blockhashB58)
        && !blockhashB58.isEmpty()
        && base58ToFixed32(blockhashB58, out)) {
      return true;
    }
    if (attempt < 2) {
      delay(120);
    }
  }
  messageOut = "RPC did not return blockhash";
  return false;
}

static bool pdaAlreadyExists(const String &login, String &pdaAddress, String &messageOut) {
  uint8_t userPda[32];
  std::vector<std::vector<uint8_t>> seeds = {
      std::vector<uint8_t>((const uint8_t *)kUsersSeedPrefix, (const uint8_t *)kUsersSeedPrefix + strlen(kUsersSeedPrefix)),
      std::vector<uint8_t>((const uint8_t *)login.c_str(), (const uint8_t *)login.c_str() + login.length())};
  if (!findProgramAddress(seeds, kShineUsersProgramId, userPda)) {
    messageOut = "Failed to derive user PDA";
    return false;
  }
  pdaAddress = bytesToBase58(userPda, 32);
  String payload;
  if (!rpcCallSolana("getAccountInfo", "[\"" + pdaAddress + "\",{\"encoding\":\"base64\",\"commitment\":\"confirmed\"}]", payload)) {
    messageOut = "Failed to check PDA";
    return false;
  }
  if (payload.indexOf("\"value\":null") >= 0) {
    return false;
  }
  if (payload.indexOf("\"value\"") >= 0) {
    messageOut = "Login is already registered";
    return true;
  }
  messageOut = "Unexpected getAccountInfo response";
  return false;
}

static bool loadAccountOwner(const String &address, String &ownerOut, bool &existsOut, String &messageOut) {
  ownerOut = "";
  existsOut = false;
  String payload;
  if (!rpcCallSolana("getAccountInfo", "[\"" + address + "\",{\"encoding\":\"base64\",\"commitment\":\"confirmed\"}]", payload)) {
    messageOut = "Failed to read account info";
    return false;
  }
  if (payload.indexOf("\"value\":null") >= 0) {
    existsOut = false;
    return true;
  }
  existsOut = true;
  if (!jsonStringField(payload, "owner", ownerOut) || ownerOut.isEmpty()) {
    messageOut = "Account owner missing in RPC response";
    return false;
  }
  return true;
}

static bool loadUsersEconomyConfigState(const String &economyConfigAddress,
                                        uint64_t &registrationFeeLamportsOut,
                                        uint64_t &lamportsPerLimitStepOut,
                                        uint64_t &startBonusLimitOut,
                                        String &messageOut) {
  registrationFeeLamportsOut = 0;
  lamportsPerLimitStepOut = 0;
  startBonusLimitOut = 0;

  String payload;
  if (!rpcCallSolana("getAccountInfo", "[\"" + economyConfigAddress + "\",{\"encoding\":\"base64\",\"commitment\":\"confirmed\"}]", payload)) {
    messageOut = "Failed to read users economy config";
    return false;
  }
  if (payload.indexOf("\"value\":null") >= 0) {
    messageOut = "Users economy config is missing on this Solana RPC";
    return false;
  }

  String owner;
  if (!jsonStringField(payload, "owner", owner) || owner.isEmpty()) {
    messageOut = "Users economy config owner is missing";
    return false;
  }
  if (owner != String(kShineUsersProgramId)) {
    messageOut = String("Users economy config owner mismatch: ") + owner;
    return false;
  }

  String dataB64;
  if (!jsonStringField(payload, "data", dataB64) || dataB64.isEmpty()) {
    messageOut = "Users economy config base64 is missing";
    return false;
  }

  std::vector<uint8_t> raw;
  if (!base64DecodeStd(dataB64, raw)) {
    messageOut = "Users economy config base64 decode failed";
    return false;
  }
  if (raw.size() < 25) {
    messageOut = "Users economy config is too short";
    return false;
  }

  registrationFeeLamportsOut = 0;
  lamportsPerLimitStepOut = 0;
  startBonusLimitOut = 0;
  for (int i = 0; i < 8; ++i) {
    registrationFeeLamportsOut |= ((uint64_t)raw[1 + i]) << (8 * i);
    lamportsPerLimitStepOut |= ((uint64_t)raw[9 + i]) << (8 * i);
    startBonusLimitOut |= ((uint64_t)raw[17 + i]) << (8 * i);
  }
  return true;
}

static String compactRpcLogs(const String &payload, int maxLines) {
  String out;
  int pos = payload.indexOf("\"logs\"");
  if (pos < 0) {
    return "";
  }
  int bracket = payload.indexOf('[', pos);
  if (bracket < 0) {
    return "";
  }
  int i = bracket + 1;
  int lines = 0;
  while (i < (int)payload.length() && lines < maxLines) {
    while (i < (int)payload.length() && payload[i] != '"' && payload[i] != ']') {
      i++;
    }
    if (i >= (int)payload.length() || payload[i] == ']') {
      break;
    }
    String line;
    bool escape = false;
    i++;
    for (; i < (int)payload.length(); ++i) {
      char ch = payload[i];
      if (escape) {
        switch (ch) {
          case 'n': line += ' '; break;
          case 'r': break;
          case 't': line += ' '; break;
          default: line += ch; break;
        }
        escape = false;
        continue;
      }
      if (ch == '\\') {
        escape = true;
        continue;
      }
      if (ch == '"') {
        i++;
        break;
      }
      line += ch;
    }
    line.trim();
    if (!line.isEmpty()) {
      if (!out.isEmpty()) {
        out += " | ";
      }
      out += line;
      lines++;
    }
  }
  return out;
}

static bool extractRpcErrorSummary(const String &payload, String &messageOut) {
  messageOut = "";
  String errorMessage;
  if (jsonStringField(payload, "message", errorMessage) && !errorMessage.isEmpty()) {
    messageOut = errorMessage;
  }
  String logs = compactRpcLogs(payload, 3);
  if (!logs.isEmpty()) {
    if (!messageOut.isEmpty()) {
      messageOut += " | ";
    }
    messageOut += logs;
  }
  return !messageOut.isEmpty();
}

static bool simulateTransactionPayload(const String &txBase64, String &payloadOut) {
  payloadOut = "";
  return rpcCallSolana("simulateTransaction", "[\"" + txBase64 + "\",{\"encoding\":\"base64\",\"sigVerify\":true,\"commitment\":\"processed\"}]", payloadOut);
}

static bool simulateTransactionForError(const String &txBase64, String &messageOut) {
  String payload;
  if (!simulateTransactionPayload(txBase64, payload)) {
    return false;
  }
  return extractRpcErrorSummary(payload, messageOut);
}

static std::vector<uint8_t> buildLegacyMessage(
    const uint8_t recentBlockhash[32],
    const uint8_t clientPub[32],
    const uint8_t userPda[32],
    const uint8_t inflowVault[32],
    const uint8_t economyConfig[32],
    const std::vector<uint8_t> &edRootData,
    const std::vector<uint8_t> &edBchData,
    const std::vector<uint8_t> &createData) {
  uint8_t systemProgram[32];
  uint8_t ed25519Program[32];
  uint8_t sysvarInstructions[32];
  uint8_t usersProgram[32];
  uint8_t loginGuardProgram[32];
  base58ToFixed32(kSystemProgramId, systemProgram);
  base58ToFixed32(kEd25519ProgramId, ed25519Program);
  base58ToFixed32(kSysvarInstructionsId, sysvarInstructions);
  base58ToFixed32(kShineUsersProgramId, usersProgram);
  base58ToFixed32(kShineLoginGuardProgramId, loginGuardProgram);

  std::vector<std::vector<uint8_t>> accountKeys;
  accountKeys.emplace_back(clientPub, clientPub + 32);
  accountKeys.emplace_back(userPda, userPda + 32);
  accountKeys.emplace_back(inflowVault, inflowVault + 32);
  accountKeys.emplace_back(systemProgram, systemProgram + 32);
  accountKeys.emplace_back(loginGuardProgram, loginGuardProgram + 32);
  accountKeys.emplace_back(economyConfig, economyConfig + 32);
  accountKeys.emplace_back(ed25519Program, ed25519Program + 32);
  accountKeys.emplace_back(usersProgram, usersProgram + 32);
  accountKeys.emplace_back(sysvarInstructions, sysvarInstructions + 32);

  std::vector<uint8_t> msg;
  msg.reserve(512);
  msg.push_back(1);
  msg.push_back(0);
  msg.push_back(6);
  shortVecEncode(accountKeys.size(), msg);
  for (const auto &key : accountKeys) {
    msg.insert(msg.end(), key.begin(), key.end());
  }
  msg.insert(msg.end(), recentBlockhash, recentBlockhash + 32);
  shortVecEncode(3, msg);

  msg.push_back(6);
  msg.push_back(0);
  shortVecEncode(edRootData.size(), msg);
  msg.insert(msg.end(), edRootData.begin(), edRootData.end());

  msg.push_back(6);
  msg.push_back(0);
  shortVecEncode(edBchData.size(), msg);
  msg.insert(msg.end(), edBchData.begin(), edBchData.end());

  msg.push_back(7);
  msg.push_back(7);
  msg.push_back(0);
  msg.push_back(1);
  msg.push_back(3);
  msg.push_back(2);
  msg.push_back(8);
  msg.push_back(5);
  msg.push_back(4);
  shortVecEncode(createData.size(), msg);
  msg.insert(msg.end(), createData.begin(), createData.end());
  return msg;
}

static std::vector<uint8_t> buildUpdateLegacyMessage(
    const uint8_t recentBlockhash[32],
    const uint8_t clientPub[32],
    const uint8_t userPda[32],
    const uint8_t inflowVault[32],
    const uint8_t economyConfig[32],
    const std::vector<uint8_t> &edRootData,
    const std::vector<uint8_t> &edBchData,
    const std::vector<uint8_t> &updateData) {
  uint8_t systemProgram[32];
  uint8_t ed25519Program[32];
  uint8_t usersProgram[32];
  uint8_t sysvarInstructions[32];
  base58ToFixed32(kSystemProgramId, systemProgram);
  base58ToFixed32(kEd25519ProgramId, ed25519Program);
  base58ToFixed32(kShineUsersProgramId, usersProgram);
  base58ToFixed32(kSysvarInstructionsId, sysvarInstructions);

  std::vector<std::vector<uint8_t>> accountKeys;
  accountKeys.emplace_back(clientPub, clientPub + 32);
  accountKeys.emplace_back(userPda, userPda + 32);
  accountKeys.emplace_back(inflowVault, inflowVault + 32);
  accountKeys.emplace_back(systemProgram, systemProgram + 32);
  accountKeys.emplace_back(economyConfig, economyConfig + 32);
  accountKeys.emplace_back(ed25519Program, ed25519Program + 32);
  accountKeys.emplace_back(usersProgram, usersProgram + 32);
  accountKeys.emplace_back(sysvarInstructions, sysvarInstructions + 32);

  std::vector<uint8_t> msg;
  msg.reserve(512);
  msg.push_back(1);
  msg.push_back(0);
  msg.push_back(5);
  shortVecEncode(accountKeys.size(), msg);
  for (const auto &key : accountKeys) {
    msg.insert(msg.end(), key.begin(), key.end());
  }
  msg.insert(msg.end(), recentBlockhash, recentBlockhash + 32);
  shortVecEncode(3, msg);

  msg.push_back(5);
  msg.push_back(0);
  shortVecEncode(edRootData.size(), msg);
  msg.insert(msg.end(), edRootData.begin(), edRootData.end());

  msg.push_back(5);
  msg.push_back(0);
  shortVecEncode(edBchData.size(), msg);
  msg.insert(msg.end(), edBchData.begin(), edBchData.end());

  msg.push_back(6);
  msg.push_back(6);
  msg.push_back(0);
  msg.push_back(1);
  msg.push_back(3);
  msg.push_back(2);
  msg.push_back(7);
  msg.push_back(4);
  shortVecEncode(updateData.size(), msg);
  msg.insert(msg.end(), updateData.begin(), updateData.end());
  return msg;
}

static bool signMessageEd25519(const std::vector<uint8_t> &message, const uint8_t secretKey[64], uint8_t signature[64]) {
  return crypto_sign_ed25519_detached(signature, nullptr, message.data(), (unsigned long long)message.size(), secretKey) == 0;
}

static String encodeTransactionBase64(const uint8_t signature[64], const std::vector<uint8_t> &message) {
  std::vector<uint8_t> tx;
  tx.reserve(1 + 64 + message.size());
  shortVecEncode(1, tx);
  pushFixed(tx, signature, 64);
  tx.insert(tx.end(), message.begin(), message.end());
  return bytesToBase64String(tx.data(), tx.size());
}

static bool parseSolanaSignerIndex(const std::vector<uint8_t> &txBytes,
                                   const uint8_t targetPub32[32],
                                   uint32_t &signerIndexOut,
                                   size_t &messageOffsetOut,
                                   String &errorOut) {
  signerIndexOut = 0;
  messageOffsetOut = 0;
  size_t offset = 0;
  uint32_t signatureCount = 0;
  if (!shortVecDecode(txBytes, offset, signatureCount)) {
    errorOut = "transaction_signature_count_invalid";
    return false;
  }
  size_t signatureBytesLen = (size_t)signatureCount * 64;
  if (offset + signatureBytesLen + 4 > txBytes.size()) {
    errorOut = "transaction_too_short";
    return false;
  }
  messageOffsetOut = offset + signatureBytesLen;
  size_t cursor = messageOffsetOut;
  bool versioned = (txBytes[cursor] & 0x80) != 0;
  if (versioned) {
    cursor += 1;
  }
  if (cursor + 3 > txBytes.size()) {
    errorOut = "transaction_header_invalid";
    return false;
  }
  uint8_t requiredSignatures = txBytes[cursor];
  cursor += 3;
  uint32_t accountCount = 0;
  if (!shortVecDecode(txBytes, cursor, accountCount)) {
    errorOut = "transaction_accounts_invalid";
    return false;
  }
  if (accountCount < requiredSignatures || signatureCount < requiredSignatures) {
    errorOut = "transaction_signer_count_invalid";
    return false;
  }
  size_t keysBytesLen = (size_t)accountCount * 32;
  if (cursor + keysBytesLen > txBytes.size()) {
    errorOut = "transaction_account_keys_truncated";
    return false;
  }
  for (uint32_t i = 0; i < requiredSignatures; ++i) {
    const uint8_t *candidate = txBytes.data() + cursor + ((size_t)i * 32);
    if (memcmp(candidate, targetPub32, 32) == 0) {
      signerIndexOut = i;
      return true;
    }
  }
  errorOut = "wallet_mismatch";
  return false;
}

static bool signSelectedWalletTransactionBase64(const String &publicKeyBase58,
                                                const String &txBase64,
                                                String &signedTxBase64Out,
                                                String &signatureBase58Out,
                                                String &errorOut) {
  signedTxBase64Out = "";
  signatureBase58Out = "";
  errorOut = "";

  String activePublicKey = selectedWalletPublicKeyB58();
  String activePrivateKey = selectedWalletPrivateKeyB58();
  if (activePublicKey.isEmpty() || activePrivateKey.isEmpty()) {
    errorOut = "wallet_unavailable";
    return false;
  }
  if (activePublicKey != publicKeyBase58) {
    errorOut = "wallet_mismatch";
    return false;
  }

  std::vector<uint8_t> txBytes;
  if (!base64DecodeStd(txBase64, txBytes) || txBytes.empty()) {
    errorOut = "transaction_base64_invalid";
    return false;
  }

  uint8_t expectedPub32[32] = {};
  if (!base58ToFixed32(activePublicKey, expectedPub32)) {
    errorOut = "wallet_public_key_invalid";
    return false;
  }

  uint8_t seed32[32] = {};
  uint8_t pub32[32] = {};
  uint8_t sec64[64] = {};
  if (!deriveSeedKeypairFromBase58(activePrivateKey, seed32, pub32, sec64)) {
    errorOut = "wallet_private_key_invalid";
    return false;
  }
  if (memcmp(pub32, expectedPub32, 32) != 0) {
    errorOut = "wallet_keypair_mismatch";
    return false;
  }

  uint32_t signerIndex = 0;
  size_t messageOffset = 0;
  if (!parseSolanaSignerIndex(txBytes, expectedPub32, signerIndex, messageOffset, errorOut)) {
    return false;
  }

  std::vector<uint8_t> message(txBytes.begin() + (long)messageOffset, txBytes.end());
  uint8_t signature[64] = {};
  if (!signMessageEd25519(message, sec64, signature)) {
    errorOut = "transaction_sign_failed";
    return false;
  }

  size_t signatureCountOffset = 0;
  uint32_t signatureCount = 0;
  if (!shortVecDecode(txBytes, signatureCountOffset, signatureCount)) {
    errorOut = "transaction_signature_count_invalid";
    return false;
  }
  size_t signatureOffset = signatureCountOffset + ((size_t)signerIndex * 64);
  if (signatureOffset + 64 > txBytes.size()) {
    errorOut = "transaction_signature_slot_invalid";
    return false;
  }
  memcpy(txBytes.data() + signatureOffset, signature, 64);

  signedTxBase64Out = bytesToBase64String(txBytes.data(), txBytes.size());
  signatureBase58Out = bytesToBase58(signature, 64);
  return true;
}

static bool sendWalletRpcResponse(const String &toLogin,
                                  const String &targetSessionId,
                                  const String &callId,
                                  const String &responseData) {
  String response;
  String req = String("{\"toLogin\":\"") + jsonEscape(toLogin)
             + "\",\"targetSessionId\":\"" + jsonEscape(targetSessionId)
             + "\",\"callId\":\"" + jsonEscape(callId)
             + "\",\"type\":" + String((unsigned int)kWalletRpcSignalTypeResponse)
             + ",\"data\":\"" + jsonEscape(responseData) + "\"}";
  return shineWsRequest(gShineWs, "CallSignalToSession", req, response, SHINE_RPC_TIMEOUT_MS);
}

static void queueWalletSignRequest(const PendingWalletRpcRequest &item,
                                   const String &requestId,
                                   const String &publicKeyBase58,
                                   const String &transactionBase64,
                                   const String &comment) {
  if (gActiveWalletSignRequest.active) {
    return;
  }
  gActiveWalletSignRequest.active = true;
  gActiveWalletSignRequest.fromLogin = item.fromLogin;
  gActiveWalletSignRequest.fromSessionId = item.fromSessionId;
  gActiveWalletSignRequest.callId = item.callId;
  gActiveWalletSignRequest.requestId = requestId;
  gActiveWalletSignRequest.publicKeyBase58 = publicKeyBase58;
  gActiveWalletSignRequest.transactionBase64 = transactionBase64;
  gActiveWalletSignRequest.comment = comment;
  gActiveWalletSignRequest.requestedAtMs = shineNowMs();
  gActiveWalletSignRequest.returnScreen = gCurrentScreen;
  gWalletSignStatusMessage = "";
  showScreen(SCREEN_WALLET_SIGN_REQUEST);
}

static void clearWalletSignRequest() {
  gActiveWalletSignRequest = ActiveWalletSignRequest();
  gWalletSignStatusMessage = "";
}

static bool respondToActiveWalletSignRequest(bool approved) {
  if (!gActiveWalletSignRequest.active) {
    return false;
  }

  String responseData;
  if (!approved) {
    responseData = String("{\"v\":1,\"op\":\"sign_transaction_result\",\"requestId\":\"")
                 + jsonEscape(gActiveWalletSignRequest.requestId)
                 + "\",\"ok\":false,\"error\":\"rejected_by_user\",\"timeMs\":"
                 + String((unsigned long long)shineNowMs()) + "}";
  } else {
    String signedTxBase64;
    String signatureBase58;
    String error;
    if (!signSelectedWalletTransactionBase64(gActiveWalletSignRequest.publicKeyBase58,
                                             gActiveWalletSignRequest.transactionBase64,
                                             signedTxBase64,
                                             signatureBase58,
                                             error)) {
      responseData = String("{\"v\":1,\"op\":\"sign_transaction_result\",\"requestId\":\"")
                   + jsonEscape(gActiveWalletSignRequest.requestId)
                   + "\",\"ok\":false,\"error\":\"" + jsonEscape(error.isEmpty() ? String("sign_failed") : error)
                   + "\",\"timeMs\":" + String((unsigned long long)shineNowMs()) + "}";
    } else {
      responseData = String("{\"v\":1,\"op\":\"sign_transaction_result\",\"requestId\":\"")
                   + jsonEscape(gActiveWalletSignRequest.requestId)
                   + "\",\"ok\":true,\"publicKeyBase58\":\"" + jsonEscape(gActiveWalletSignRequest.publicKeyBase58)
                   + "\",\"signatureBase58\":\"" + jsonEscape(signatureBase58)
                   + "\",\"signedTransactionBase64\":\"" + jsonEscape(signedTxBase64)
                   + "\",\"timeMs\":" + String((unsigned long long)shineNowMs()) + "}";
    }
  }

  bool sent = sendWalletRpcResponse(gActiveWalletSignRequest.fromLogin,
                                    gActiveWalletSignRequest.fromSessionId,
                                    gActiveWalletSignRequest.callId,
                                    responseData);
  if (!sent) {
    gWalletSignStatusMessage = "Failed to send response";
    return false;
  }

  Screen returnScreen = gActiveWalletSignRequest.returnScreen;
  clearWalletSignRequest();
  showScreen(returnScreen == SCREEN_WALLET_SIGN_REQUEST ? SCREEN_WALLET : returnScreen);
  return true;
}

static bool awaitTransactionConfirmation(const String &signatureB58, String &messageOut) {
  for (int attempt = 0; attempt < 15; attempt++) {
    String payload;
    if (!rpcCallSolana("getSignatureStatuses", "[[\"" + signatureB58 + "\"],{\"searchTransactionHistory\":true}]", payload)) {
      delay(1000);
      continue;
    }
    if (payload.indexOf("\"err\":null") >= 0 &&
        (payload.indexOf("\"confirmationStatus\":\"confirmed\"") >= 0 ||
         payload.indexOf("\"confirmationStatus\":\"finalized\"") >= 0)) {
      return true;
    }
    if (payload.indexOf("\"err\":{") >= 0 || payload.indexOf("\"err\":\"") >= 0) {
      messageOut = "Transaction rejected by network";
      return false;
    }
    delay(1000);
  }
  messageOut = "RPC did not confirm transaction in time";
  return false;
}

static bool registerHomeserverOnSolana(String &messageOut) {
  messageOut = "";
  String diagDetails;
  auto failWithDiag = [&](const String &summary) -> bool {
    messageOut = summary;
    saveRegisterDiag("error", summary, diagDetails);
    printRegisterDiagToSerial();
    return false;
  };

  String cleanLogin = normalizeLoginValue(gLoginValue);
  String accessServerLogin = normalizeLoginValue(gShineServerLogin);
  if (!isValidShineServerLoginValue(accessServerLogin)) {
    accessServerLogin = kDefaultShineServerLogin;
  }
  diagDetails += String("trigger=") + gRegisterTriggerSource + "\n";
  diagDetails += String("test_uptime_ms=") + String(millis()) + "\n";
  diagDetails += String("login=") + cleanLogin + "\n";
  diagDetails += String("rpc=") + gSolanaRpcUrl + "\n";
  diagDetails += String("shine_server_login=") + accessServerLogin + "\n";
  diagDetails += String("homeserver=") + gHomeserverValue + "\n";

  if (cleanLogin.isEmpty()) {
    return failWithDiag("Login is not set");
  }
  if (!gSecretConfigured || gRootPrivB58.isEmpty() || gBlockchainPrivB58.isEmpty() || gDevicePrivB58.isEmpty()) {
    return failWithDiag("Secret is not ready");
  }
  if (WiFi.status() != WL_CONNECTED) {
    diagDetails += "wifi=disconnected\n";
    return failWithDiag("Connect Wi-Fi first");
  }
  diagDetails += String("wifi=connected:") + WiFi.localIP().toString() + "\n";
  if (gSolanaRpcUrl.isEmpty()) {
    return failWithDiag("Set Solana RPC first");
  }

  String existingPda;
  String pdaCheckMessage;
  if (pdaAlreadyExists(cleanLogin, existingPda, pdaCheckMessage)) {
    gUserPdaAddress = existingPda;
    gRegistrationSignature = "";
    saveAccountPrefs();
    gAccountPdaStatus = ACCOUNT_PDA_OK;
    gAccountPdaStatusMessage = "User is already registered";
    gShowRegisterAccountButton = false;
    gAccountStatusMessage = "User is already registered";
    gShineStatusLine = String("SHiNE: ") + (!gShineServerUrl.isEmpty() ? gShineServerUrl : accessServerLogin) + " registered";
    refreshAccountPdaStatus();
    diagDetails += String("user_pda=") + existingPda + "\n";
    saveRegisterDiag("ok", "User is already registered", diagDetails);
    return true;
  }
  if (pdaCheckMessage == "Failed to derive user PDA" || pdaCheckMessage == "Failed to check PDA" || pdaCheckMessage == "Unexpected getAccountInfo response") {
    diagDetails += String("user_pda_check=") + pdaCheckMessage + "\n";
    return failWithDiag(pdaCheckMessage);
  }

  uint8_t userPda[32];
  uint8_t economyConfig[32];
  uint8_t inflowVault[32];
  if (!findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kUsersSeedPrefix, (const uint8_t *)kUsersSeedPrefix + strlen(kUsersSeedPrefix)),
          std::vector<uint8_t>((const uint8_t *)cleanLogin.c_str(), (const uint8_t *)cleanLogin.c_str() + cleanLogin.length())
      }, kShineUsersProgramId, userPda) ||
      !findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kUsersEconomyConfigSeed, (const uint8_t *)kUsersEconomyConfigSeed + strlen(kUsersEconomyConfigSeed))
      }, kShineUsersProgramId, economyConfig) ||
      !findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kPaymentsInflowSeed, (const uint8_t *)kPaymentsInflowSeed + strlen(kPaymentsInflowSeed))
      }, kShinePaymentsProgramId, inflowVault)) {
    return failWithDiag("Failed to derive required PDAs");
  }

  String userPdaB58 = bytesToBase58(userPda, 32);
  String economyConfigB58 = bytesToBase58(economyConfig, 32);
  String inflowVaultB58 = bytesToBase58(inflowVault, 32);
  diagDetails += String("user_pda=") + userPdaB58 + "\n";
  diagDetails += String("users_economy_config_pda=") + economyConfigB58 + "\n";
  diagDetails += String("inflow_vault_pda=") + inflowVaultB58 + "\n";

  String accountInfoMessage;
  String ownerValue;
  bool ownerExists = false;
  if (!loadAccountOwner(userPdaB58, ownerValue, ownerExists, accountInfoMessage)) {
    diagDetails += String("user_pda_rpc_error=") + accountInfoMessage + "\n";
    return failWithDiag(accountInfoMessage);
  }
  diagDetails += String("user_pda_exists=") + (ownerExists ? "true" : "false") + "\n";
  if (ownerExists) {
    diagDetails += String("user_pda_owner=") + ownerValue + "\n";
    return failWithDiag("User PDA already exists on RPC");
  }

  uint64_t registrationFeeLamports = 0;
  uint64_t lamportsPerLimitStep = 0;
  uint64_t startBonusLimit = 0;
  if (!loadUsersEconomyConfigState(economyConfigB58,
                                   registrationFeeLamports,
                                   lamportsPerLimitStep,
                                   startBonusLimit,
                                   accountInfoMessage)) {
    diagDetails += String("users_economy_config_error=") + accountInfoMessage + "\n";
    return failWithDiag(accountInfoMessage);
  }
  diagDetails += String("registration_fee_lamports=") + String((unsigned long long)registrationFeeLamports) + "\n";
  diagDetails += String("lamports_per_limit_step=") + String((unsigned long long)lamportsPerLimitStep) + "\n";
  diagDetails += String("start_bonus_limit=") + String((unsigned long long)startBonusLimit) + "\n";

  uint8_t rootSeed[32] = {};
  uint8_t rootPub[32] = {};
  uint8_t rootSec[64] = {};
  uint8_t recoverySeed[32] = {};
  uint8_t recoveryPub[32] = {};
  uint8_t recoverySec[64] = {};
  uint8_t blockchainSeed[32] = {};
  uint8_t blockchainPub[32] = {};
  uint8_t blockchainSec[64] = {};
  uint8_t clientSeed[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t deviceSec[64] = {};
  if (!deriveSeedKeypairFromBase58(gRecoveryPrivB58, recoverySeed, recoveryPub, recoverySec) ||
      !deriveSeedKeypairFromBase58(gRootPrivB58, rootSeed, rootPub, rootSec) ||
      !deriveSeedKeypairFromBase58(gBlockchainPrivB58, blockchainSeed, blockchainPub, blockchainSec) ||
      !deriveSeedKeypairFromBase58(gDevicePrivB58, clientSeed, clientPub, deviceSec)) {
    return failWithDiag("Failed to restore keys");
  }
  diagDetails += String("recovery_pub=") + bytesToBase58(recoveryPub, 32) + "\n";
  diagDetails += String("root_pub=") + bytesToBase58(rootPub, 32) + "\n";
  diagDetails += String("blockchain_pub=") + bytesToBase58(blockchainPub, 32) + "\n";
  diagDetails += String("device_pub=") + bytesToBase58(clientPub, 32) + "\n";

  String blockchainName = cleanLogin + "-001";
  diagDetails += String("blockchain_name=") + blockchainName + "\n";
  std::vector<uint8_t> lastBlockState = buildLastBlockStateBytes(cleanLogin, blockchainName, 0, nullptr, 0);
  uint8_t lastBlockHash[32];
  uint8_t lastBlockSignature[64];
  sha256calc(lastBlockState.data(), lastBlockState.size(), lastBlockHash);
  if (!signMessageEd25519(std::vector<uint8_t>(lastBlockHash, lastBlockHash + 32), blockchainSec, lastBlockSignature)) {
    return failWithDiag("Failed to sign LastBlockState");
  }
  diagDetails += String("last_block_hash=") + bytesToHexString(lastBlockHash, 32) + "\n";
  diagDetails += String("last_block_signature_b64=") + bytesToBase64String(lastBlockSignature, 64) + "\n";

  if (!ensureNtpTimeSynced(messageOut)) {
    diagDetails += String("ntp_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }
  uint64_t createdAtMs = 0;
  if (!getSystemEpochMs(createdAtMs)) {
    return failWithDiag("NTP time is not ready");
  }
  diagDetails += String("created_at_ms=") + String((unsigned long long)createdAtMs) + "\n";
  std::vector<String> accessServers = {accessServerLogin};
  std::vector<uint8_t> unsignedRecord = buildUnsignedCreateRecord(
      cleanLogin, blockchainName, accessServers,
      recoveryPub,
      rootPub, clientPub, blockchainPub,
      lastBlockSignature, startBonusLimit, createdAtMs);
  uint8_t unsignedHash[32];
  uint8_t rootSignature[64];
  sha256calc(unsignedRecord.data(), unsignedRecord.size(), unsignedHash);
  if (!signMessageEd25519(std::vector<uint8_t>(unsignedHash, unsignedHash + 32), rootSec, rootSignature)) {
    return failWithDiag("Failed to sign PDA record");
  }
  diagDetails += String("unsigned_record_len=") + String((unsigned long)unsignedRecord.size()) + "\n";
  diagDetails += String("unsigned_record_hash=") + bytesToHexString(unsignedHash, 32) + "\n";
  diagDetails += String("root_signature_b64=") + bytesToBase64String(rootSignature, 64) + "\n";

  std::vector<uint8_t> createData = buildCreateInstructionData(
      cleanLogin, blockchainName, accessServers,
      recoveryPub,
      rootPub, clientPub, blockchainPub,
      lastBlockSignature, rootSignature, createdAtMs);
  std::vector<uint8_t> edRootData = buildEd25519InstructionData(rootSignature, rootPub, unsignedHash);
  std::vector<uint8_t> edBchData = buildEd25519InstructionData(lastBlockSignature, blockchainPub, lastBlockHash);

  uint8_t recentBlockhash[32];
  String recentBlockhash58;
  if (!getLatestBlockhashBytes(recentBlockhash, recentBlockhash58, messageOut)) {
    diagDetails += String("blockhash_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }
  diagDetails += String("recent_blockhash=") + recentBlockhash58 + "\n";

  std::vector<uint8_t> message = buildLegacyMessage(
      recentBlockhash,
      clientPub,
      userPda,
      inflowVault,
      economyConfig,
      edRootData,
      edBchData,
      createData);
  uint8_t txSignature[64];
  if (!signMessageEd25519(message, deviceSec, txSignature)) {
    return failWithDiag("Failed to sign Solana transaction");
  }
  String txBase64 = encodeTransactionBase64(txSignature, message);
  String signatureB58 = bytesToBase58(txSignature, 64);
  diagDetails += String("tx_signature=") + signatureB58 + "\n";

  String payload;
  if (!rpcCallSolana("sendTransaction", "[\"" + txBase64 + "\",{\"encoding\":\"base64\",\"preflightCommitment\":\"confirmed\"}]", payload)) {
    diagDetails += "send_transaction_rpc_error=true\n";
    return failWithDiag("RPC did not accept transaction");
  }
  if (rpcResponseHasError(payload)) {
    if (!extractRpcErrorSummary(payload, messageOut)) {
      messageOut = "RPC returned sendTransaction error";
    }
    diagDetails += "send_transaction_payload<<\n";
    diagDetails += payload;
    diagDetails += "\n>>send_transaction_payload\n";
    String simulated;
    String simulatedPayload;
    if (simulateTransactionPayload(txBase64, simulatedPayload)) {
      extractRpcErrorSummary(simulatedPayload, simulated);
      if (messageOut.isEmpty()) {
        messageOut = simulated;
      } else if (messageOut.indexOf(simulated) < 0) {
        messageOut += " | simulate: " + simulated;
      }
      diagDetails += "simulate_payload<<\n";
      diagDetails += simulatedPayload;
      diagDetails += "\n>>simulate_payload\n";
    }
    diagDetails += String("send_transaction_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }
  if (!awaitTransactionConfirmation(signatureB58, messageOut)) {
    diagDetails += String("confirmation_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }

  gUserPdaAddress = userPdaB58;
  gRegistrationSignature = signatureB58;
  gAccountStatusMessage = "Solana registration complete";
  gAccountPdaStatus = ACCOUNT_PDA_OK;
  gAccountPdaStatusMessage = "User registered";
  gShowRegisterAccountButton = false;
  gShineStatusLine = String("SHiNE: ") + (!gShineServerUrl.isEmpty() ? gShineServerUrl : accessServerLogin) + " registered";
  saveAccountPrefs();
  refreshAccountPdaStatus();
  messageOut = "Solana registration confirmed";
  saveRegisterDiag("ok", messageOut, diagDetails);
  printRegisterDiagToSerial();
  return true;
}

static void executeRegisterAccountFlow(const char *triggerSource, bool showResultScreen) {
  gRegisterTriggerSource = triggerSource ? String(triggerSource) : String("manual");
  prepareRegisterAccountScreen();
  String registerMessage;
  if (registerHomeserverOnSolana(registerMessage)) {
    gRegisterResultSuccess = true;
    gRegisterResultMessage = registerMessage;
    gRegisterResultDetails = String("user_pda and tx signature were saved");
    gAccountStatusMessage = "Registration completed";
  } else {
    gRegisterResultSuccess = false;
    gRegisterResultMessage = registerMessage;
    gRegisterResultDetails = "";
    gAccountStatusMessage = registerMessage;
  }
  gRegisterConfirmMessage = "";
  gRegisterConfirmBalanceLine = "";
  gRegisterConfirmPdaLine = "";
  gRegisterConfirmHomeserverLine = "";
  gRegisterConfirmCanSubmit = false;
  if (showResultScreen) {
    showScreen(SCREEN_REGISTER_ACCOUNT_RESULT);
  }
}

static void prepareRegisterAccountScreen() {
  gRegisterResultMessage = "";
  gRegisterResultDetails = "";
  gRegisterResultSuccess = false;
  gRegisterConfirmMessage = "";
  gRegisterConfirmBalanceLine = "";
  gRegisterConfirmPdaLine = "";
  gRegisterConfirmHomeserverLine = "";
  gRegisterConfirmCanSubmit = false;

  String cleanLogin = normalizeLoginValue(gLoginValue);
  if (cleanLogin.isEmpty()) {
    gRegisterConfirmMessage = "Login is not set";
    return;
  }
  if (!gSecretConfigured) {
    gRegisterConfirmMessage = "Secret is not set";
    return;
  }
  if (WiFi.status() != WL_CONNECTED) {
    gRegisterConfirmMessage = "Wi-Fi is not connected";
    return;
  }

  String balanceMessage;
  uint64_t lamports = 0;
  if (!loadWalletBalanceLamports(lamports, balanceMessage)) {
    gRegisterConfirmMessage = balanceMessage;
  } else {
    gRegisterConfirmBalanceLine = formatSolValue(lamports);
    if (lamports < 20000000ULL) {
      gRegisterConfirmMessage = "Balance is below 0.020 SOL";
    } else {
      gRegisterConfirmMessage = "Balance is OK: 0.020 SOL or more";
    }
  }

  if (gHomeserverValue.isEmpty()) {
    gRegisterConfirmHomeserverLine = "Homeserver is not set";
  } else if (gHomeserverValue == "homeserver1") {
    gRegisterConfirmHomeserverLine = "Homeserver: homeserver1 (default value)";
  } else {
    gRegisterConfirmHomeserverLine = String("Homeserver: ") + gHomeserverValue;
  }

  ShinePdaUserState pdaState;
  String pdaError;
  if (!readShineUserPda(cleanLogin, pdaState, pdaError)) {
    gRegisterConfirmPdaLine = pdaError.isEmpty() ? "PDA: failed to check" : String("PDA: ") + pdaError;
    if (gRegisterConfirmMessage.isEmpty()) {
      gRegisterConfirmMessage = pdaError.isEmpty() ? "Failed to check PDA" : pdaError;
    }
    return;
  }

  if (pdaState.found) {
    gRegisterConfirmPdaLine = "PDA is already occupied, login is not free";
    if (gRegisterConfirmMessage.isEmpty()) {
      gRegisterConfirmMessage = "Login is already registered";
    }
    return;
  }

  gRegisterConfirmPdaLine = "PDA is free for registration";
  if (gRegisterConfirmMessage.isEmpty()) {
    gRegisterConfirmMessage = "All checks passed";
  }
  gRegisterConfirmCanSubmit = true;
}

static void prepareHomeserverPdaActionScreen() {
  gHomeserverPdaActionMessage = "";
  gHomeserverPdaActionDetail = "";
  gHomeserverPdaCanAdd = false;
  gHomeserverPdaCanFix = false;
  gHomeserverPdaResultMessage = "";
  gHomeserverPdaResultDetails = "";
  gHomeserverPdaResultSuccess = false;

  if (gLoginValue.isEmpty()) {
    gHomeserverPdaActionMessage = "Login is not set";
    return;
  }
  if (!gSecretConfigured) {
    gHomeserverPdaActionMessage = "Secret is not set";
    return;
  }
  if (gHomeserverValue.isEmpty()) {
    gHomeserverPdaActionMessage = "Homeserver is not set";
    return;
  }
  if (WiFi.status() != WL_CONNECTED) {
    gHomeserverPdaActionMessage = "Wi-Fi is not connected";
    gHomeserverPdaActionDetail = "Connect Wi-Fi, then try again.";
    return;
  }

  if (gHomeserverPdaActionReason == "homeserver key mismatch") {
    gHomeserverPdaActionMessage = "Homeserver key in PDA does not match local secret";
    gHomeserverPdaActionDetail = String("Homeserver: ") + gHomeserverValue;
    gHomeserverPdaCanFix = true;
    return;
  }
  if (gHomeserverPdaActionReason == "homeserver not in PDA") {
    gHomeserverPdaActionMessage = "Homeserver session is missing from user PDA";
    gHomeserverPdaActionDetail = String("Homeserver: ") + gHomeserverValue;
    gHomeserverPdaCanAdd = true;
    return;
  }

  gHomeserverPdaActionMessage = "Homeserver PDA action is not available";
}

static bool updateHomeserverSessionOnSolana(bool requireExisting, String &messageOut) {
  messageOut = "";
  String diagDetails;
  auto failWithDiag = [&](const String &summary) -> bool {
    messageOut = summary;
    saveRegisterDiag("error", summary, diagDetails);
    printRegisterDiagToSerial();
    return false;
  };

  String cleanLogin = normalizeLoginValue(gLoginValue);
  diagDetails += String("trigger=") + gRegisterTriggerSource + "\n";
  diagDetails += String("action=") + (requireExisting ? "fix_homeserver_key" : "add_homeserver") + "\n";
  diagDetails += String("uptime_ms=") + String(millis()) + "\n";
  diagDetails += String("login=") + cleanLogin + "\n";
  diagDetails += String("homeserver=") + gHomeserverValue + "\n";
  diagDetails += String("rpc=") + gSolanaRpcUrl + "\n";
  Serial.println("HOMESERVER_UPDATE_BEGIN");

  if (cleanLogin.isEmpty()) {
    return failWithDiag("Login is not set");
  }
  if (!gSecretConfigured) {
    return failWithDiag("Secret is not ready");
  }
  if (gHomeserverValue.isEmpty()) {
    return failWithDiag("Homeserver is not set");
  }
  if (WiFi.status() != WL_CONNECTED) {
    diagDetails += "wifi=disconnected\n";
    return failWithDiag("Connect Wi-Fi first");
  }
  diagDetails += String("wifi=connected:") + WiFi.localIP().toString() + "\n";
  Serial.println("HOMESERVER_UPDATE_WIFI_OK");
  if (gShineAuthenticated || gShineWs.connected) {
    Serial.println("HOMESERVER_UPDATE_CLOSE_SHINE_SESSION");
    clearShineSessionState(false);
  }

  ShinePdaUserState currentState;
  String stateError;
  bool usedCachedPda = false;
  if (gCachedAccountPdaValid && gCachedAccountPdaLogin == cleanLogin && gCachedAccountPdaState.found) {
    currentState = gCachedAccountPdaState;
    usedCachedPda = true;
    diagDetails += "read_pda_source=cache\n";
  } else {
    Serial.println("HOMESERVER_UPDATE_READ_PDA_CALL");
    if (!readShineUserPda(cleanLogin, currentState, stateError)) {
      diagDetails += String("read_pda_error=") + stateError + "\n";
      return failWithDiag(stateError.isEmpty() ? "Failed to read user PDA" : stateError);
    }
    if (!currentState.found) {
      return failWithDiag("User PDA does not exist yet");
    }
    diagDetails += "read_pda_source=rpc\n";
  }
  Serial.println(usedCachedPda ? "HOMESERVER_UPDATE_PDA_READ_CACHE" : "HOMESERVER_UPDATE_PDA_READ_RPC");
  Serial.println("HOMESERVER_UPDATE_PDA_SNAPSHOT_OK");

  uint8_t recoverySeed[32] = {};
  uint8_t recoveryPub[32] = {};
  uint8_t recoverySec[64] = {};
  uint8_t rootSeed[32] = {};
  uint8_t rootPub[32] = {};
  uint8_t rootSec[64] = {};
  uint8_t clientSeed[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t deviceSec[64] = {};
  uint8_t homeserverPub[32] = {};
  if (!deriveSeedKeypairFromBase58(gRecoveryPrivB58, recoverySeed, recoveryPub, recoverySec)
      || !deriveSeedKeypairFromBase58(gRootPrivB58, rootSeed, rootPub, rootSec)
      || !deriveSeedKeypairFromBase58(gDevicePrivB58, clientSeed, clientPub, deviceSec)
      || !base58ToFixed32(gHomeserverPubB58, homeserverPub)) {
    return failWithDiag("Failed to restore local keys");
  }
  if (memcmp(recoveryPub, currentState.recoveryKey32, 32) != 0) {
    return failWithDiag("Recovery key does not match PDA");
  }
  if (memcmp(clientPub, currentState.clientKey32, 32) != 0) {
    return failWithDiag("Client key does not match PDA");
  }
  saveRegisterDiagCheckpoint("Local keys restored", diagDetails);

  if (!ensureNtpTimeSynced(messageOut)) {
    diagDetails += String("ntp_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }
  uint64_t updatedAtMs = 0;
  if (!getSystemEpochMs(updatedAtMs)) {
    return failWithDiag("NTP time is not ready");
  }
  diagDetails += String("updated_at_ms=") + String((unsigned long long)updatedAtMs) + "\n";
  saveRegisterDiagCheckpoint("Homeserver update timestamp ready", diagDetails);

  uint8_t userPda[32] = {};
  uint8_t economyConfig[32] = {};
  uint8_t inflowVault[32] = {};
  if (!findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kUsersSeedPrefix, (const uint8_t *)kUsersSeedPrefix + strlen(kUsersSeedPrefix)),
          std::vector<uint8_t>((const uint8_t *)cleanLogin.c_str(), (const uint8_t *)cleanLogin.c_str() + cleanLogin.length())
      }, kShineUsersProgramId, userPda)
      || !findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kUsersEconomyConfigSeed, (const uint8_t *)kUsersEconomyConfigSeed + strlen(kUsersEconomyConfigSeed))
      }, kShineUsersProgramId, economyConfig)
      || !findProgramAddress({
          std::vector<uint8_t>((const uint8_t *)kPaymentsInflowSeed, (const uint8_t *)kPaymentsInflowSeed + strlen(kPaymentsInflowSeed))
      }, kShinePaymentsProgramId, inflowVault)) {
    return failWithDiag("Failed to derive required PDAs");
  }

  String userPdaB58 = bytesToBase58(userPda, 32);
  diagDetails += String("user_pda=") + userPdaB58 + "\n";
  diagDetails += String("users_economy_config_pda=") + bytesToBase58(economyConfig, 32) + "\n";
  diagDetails += String("inflow_vault_pda=") + bytesToBase58(inflowVault, 32) + "\n";

  ShinePdaUserState nextState = currentState;
  memcpy(nextState.recoveryKey32, recoveryPub, 32);
  memcpy(nextState.rootKey32, rootPub, 32);
  memcpy(nextState.clientKey32, clientPub, 32);
  nextState.updatedAtMs = updatedAtMs;
  nextState.recordNumber = currentState.recordNumber + 1;
  if (nextState.sessionsMode == 0) {
    nextState.sessionsMode = 1;
  }

  bool foundSession = false;
  for (auto &session : nextState.sessions) {
    if (session.sessionType == kSessionTypeHomeserver && session.sessionName == gHomeserverValue) {
      foundSession = true;
      memcpy(session.sessionPubKey32, homeserverPub, 32);
      session.sessionVersion = 1;
      break;
    }
  }
  if (!foundSession) {
    if (requireExisting) {
      return failWithDiag("Homeserver session is missing in PDA");
    }
    ShinePdaSessionRecord rec;
    rec.sessionType = kSessionTypeHomeserver;
    rec.sessionVersion = 1;
    rec.sessionName = gHomeserverValue;
    memcpy(rec.sessionPubKey32, homeserverPub, 32);
    nextState.sessions.push_back(rec);
  }
  saveRegisterDiagCheckpoint("Homeserver session merged", diagDetails);

  std::vector<uint8_t> oldUnsigned = serializeUnsignedRecordState(currentState);
  uint8_t prevHash32[32] = {};
  sha256calc(oldUnsigned.data(), oldUnsigned.size(), prevHash32);
  memcpy(nextState.prevRecordHash32, prevHash32, 32);
  diagDetails += String("prev_hash=") + bytesToHexString(prevHash32, 32) + "\n";

  std::vector<uint8_t> newUnsigned = serializeUnsignedRecordState(nextState);
  uint8_t unsignedHash[32] = {};
  uint8_t rootSignature[64] = {};
  sha256calc(newUnsigned.data(), newUnsigned.size(), unsignedHash);
  if (!signMessageEd25519(std::vector<uint8_t>(unsignedHash, unsignedHash + 32), rootSec, rootSignature)) {
    return failWithDiag("Failed to sign updated PDA record");
  }
  diagDetails += String("unsigned_record_len=") + String((unsigned long)newUnsigned.size()) + "\n";
  diagDetails += String("unsigned_record_hash=") + bytesToHexString(unsignedHash, 32) + "\n";
  saveRegisterDiagCheckpoint("Unsigned update built", diagDetails);

  std::vector<uint8_t> lastBlockState = buildLastBlockStateBytes(
      cleanLogin,
      currentState.blockchainName,
      currentState.lastBlockNumber,
      currentState.lastBlockHash32,
      currentState.usedBytes);
  uint8_t lastBlockHash[32] = {};
  sha256calc(lastBlockState.data(), lastBlockState.size(), lastBlockHash);
  diagDetails += String("last_block_hash=") + bytesToHexString(lastBlockHash, 32) + "\n";

  std::vector<uint8_t> updateData = buildUpdateInstructionData(
      nextState,
      nextState.recordNumber,
      nextState.updatedAtMs,
      prevHash32,
      rootSignature);
  std::vector<uint8_t> edRootData = buildEd25519InstructionData(rootSignature, rootPub, unsignedHash);
  std::vector<uint8_t> edBchData = buildEd25519InstructionData(currentState.lastBlockSignature64, currentState.blockchainKey32, lastBlockHash);

  uint8_t recentBlockhash[32] = {};
  String recentBlockhash58;
  if (!getLatestBlockhashBytes(recentBlockhash, recentBlockhash58, messageOut)) {
    diagDetails += String("blockhash_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }
  diagDetails += String("recent_blockhash=") + recentBlockhash58 + "\n";
  saveRegisterDiagCheckpoint("Recent blockhash loaded", diagDetails);

  std::vector<uint8_t> message = buildUpdateLegacyMessage(
      recentBlockhash,
      clientPub,
      userPda,
      inflowVault,
      economyConfig,
      edRootData,
      edBchData,
      updateData);
  uint8_t txSignature[64] = {};
  if (!signMessageEd25519(message, deviceSec, txSignature)) {
    return failWithDiag("Failed to sign Solana transaction");
  }
  String txBase64 = encodeTransactionBase64(txSignature, message);
  String signatureB58 = bytesToBase58(txSignature, 64);
  diagDetails += String("tx_signature=") + signatureB58 + "\n";
  saveRegisterDiagCheckpoint("Signed update transaction", diagDetails);

  String payload;
  if (!rpcCallSolana("sendTransaction", "[\"" + txBase64 + "\",{\"encoding\":\"base64\",\"preflightCommitment\":\"confirmed\"}]", payload)) {
    diagDetails += "send_transaction_rpc_error=true\n";
    return failWithDiag("RPC did not accept transaction");
  }
  if (rpcResponseHasError(payload)) {
    if (!extractRpcErrorSummary(payload, messageOut)) {
      messageOut = "RPC returned sendTransaction error";
    }
    diagDetails += "send_transaction_payload<<\n";
    diagDetails += payload;
    diagDetails += "\n>>send_transaction_payload\n";
    String simulated;
    String simulatedPayload;
    if (simulateTransactionPayload(txBase64, simulatedPayload)) {
      extractRpcErrorSummary(simulatedPayload, simulated);
      if (messageOut.isEmpty()) {
        messageOut = simulated;
      } else if (messageOut.indexOf(simulated) < 0) {
        messageOut += " | simulate: " + simulated;
      }
      diagDetails += "simulate_payload<<\n";
      diagDetails += simulatedPayload;
      diagDetails += "\n>>simulate_payload\n";
    }
    return failWithDiag(messageOut);
  }
  if (!awaitTransactionConfirmation(signatureB58, messageOut)) {
    diagDetails += String("confirmation_error=") + messageOut + "\n";
    return failWithDiag(messageOut);
  }

  gUserPdaAddress = userPdaB58;
  gRegistrationSignature = signatureB58;
  saveAccountPrefs();
  refreshAccountPdaStatus();
  gHomeserverPdaResultSuccess = true;
  gHomeserverPdaResultMessage = requireExisting ? "Homeserver key updated in PDA" : "Homeserver added to user PDA";
  gHomeserverPdaResultDetails = String("tx: ") + abbreviateValue(signatureB58, 12, 8);
  messageOut = gHomeserverPdaResultMessage;
  saveRegisterDiag("ok", messageOut, diagDetails);
  printRegisterDiagToSerial();
  return true;
}

static bool parseShineUserPdaBytes(const std::vector<uint8_t> &bytes, ShinePdaUserState &outState, String &errorOut) {
  outState = ShinePdaUserState{};
  errorOut = "";
  if (bytes.size() < 64) {
    errorOut = "PDA too short";
    return false;
  }

  size_t offset = 0;
  auto ensure = [&](size_t need) -> bool {
    return offset + need <= bytes.size();
  };
  auto readU8 = [&](uint8_t &value) -> bool {
    if (!ensure(1)) return false;
    value = bytes[offset++];
    return true;
  };
  auto readU16 = [&](uint16_t &value) -> bool {
    if (!ensure(2)) return false;
    value = (uint16_t)bytes[offset] | ((uint16_t)bytes[offset + 1] << 8);
    offset += 2;
    return true;
  };
  auto readU32 = [&](uint32_t &value) -> bool {
    if (!ensure(4)) return false;
    value = (uint32_t)bytes[offset]
          | ((uint32_t)bytes[offset + 1] << 8)
          | ((uint32_t)bytes[offset + 2] << 16)
          | ((uint32_t)bytes[offset + 3] << 24);
    offset += 4;
    return true;
  };
  auto readU64 = [&](uint64_t &value) -> bool {
    if (!ensure(8)) return false;
    value = 0;
    for (int i = 0; i < 8; ++i) {
      value |= ((uint64_t)bytes[offset + i]) << (8 * i);
    }
    offset += 8;
    return true;
  };
  auto readBytes = [&](uint8_t *dst, size_t len) -> bool {
    if (!ensure(len)) return false;
    memcpy(dst, bytes.data() + offset, len);
    offset += len;
    return true;
  };
  auto readStringU8 = [&](String &value) -> bool {
    uint8_t len = 0;
    if (!readU8(len) || !ensure(len)) return false;
    value = "";
    value.reserve(len);
    for (uint8_t i = 0; i < len; ++i) {
      value += (char)bytes[offset + i];
    }
    offset += len;
    return true;
  };

  if (!ensure(5) || memcmp(bytes.data(), "SHiNE", 5) != 0) {
    errorOut = "Bad PDA magic";
    return false;
  }
  offset += 5;
  uint8_t version = 0;
  uint8_t flags = 0;
  uint16_t recordLen = 0;
  if (!readU8(version) || !readU8(flags) || !readU16(recordLen)) {
    errorOut = "Bad PDA header";
    return false;
  }
  if (recordLen < 73 || recordLen > bytes.size()) {
    errorOut = "Bad PDA record len";
    return false;
  }
  offset = 9;
  if (!readU64(outState.createdAtMs) || !readU64(outState.updatedAtMs) || !readU32(outState.recordNumber)) {
    errorOut = "Bad PDA fixed fields";
    return false;
  }
  if (!readBytes(outState.prevRecordHash32, 32)) {
    errorOut = "Bad PDA prev hash";
    return false;
  }
  if (!readStringU8(outState.login)) {
    errorOut = "Bad PDA login";
    return false;
  }
  uint8_t blocksCount = 0;
  if (!readU8(blocksCount)) {
    errorOut = "Bad PDA blocks count";
    return false;
  }

  for (uint8_t i = 0; i < blocksCount; ++i) {
    uint8_t blockType = 0;
    uint8_t blockVersion = 0;
    if (!readU8(blockType) || !readU8(blockVersion)) {
      errorOut = "Bad PDA block header";
      return false;
    }
    if (blockType == kBlockTypeRecoveryKey) {
      if (!readBytes(outState.recoveryKey32, 32)) {
        errorOut = "Bad recovery key block";
        return false;
      }
      continue;
    }
    if (blockType == kBlockTypeRootKey) {
      if (!readBytes(outState.rootKey32, 32)) {
        errorOut = "Bad root key block";
        return false;
      }
      continue;
    }
    if (blockType == kBlockTypeClientKey) {
      if (!readBytes(outState.clientKey32, 32)) {
        errorOut = "Bad client key block";
        return false;
      }
      continue;
    }
    if (blockType == kBlockTypeBlockchainRegistry) {
      uint8_t count = 0;
      if (!readU8(count)) {
        errorOut = "Bad blockchain count";
        return false;
      }
      for (uint8_t j = 0; j < count; ++j) {
        uint8_t blockchainType = 0;
        String blockchainName;
        uint8_t blockchainKey[32] = {};
        uint64_t paidLimit = 0;
        uint64_t usedBytes = 0;
        uint32_t lastBlockNumber = 0;
        uint8_t lastBlockHash[32] = {};
        uint8_t lastBlockSig[64] = {};
        uint8_t arweavePresent = 0;
        String arweaveTxId;
        if (!readU8(blockchainType)
            || !readStringU8(blockchainName)
            || !readBytes(blockchainKey, 32)
            || !readU64(paidLimit)
            || !readU64(usedBytes)
            || !readU32(lastBlockNumber)
            || !readBytes(lastBlockHash, 32)
            || !readBytes(lastBlockSig, 64)
            || !readU8(arweavePresent)) {
          errorOut = "Bad blockchain block";
          return false;
        }
        if (arweavePresent == 1 && !readStringU8(arweaveTxId)) {
          errorOut = "Bad arweave field";
          return false;
        }
        if (j == 0) {
          outState.blockchainType = blockchainType;
          outState.blockchainName = blockchainName;
          memcpy(outState.blockchainKey32, blockchainKey, 32);
          outState.paidLimitBytes = paidLimit;
          outState.usedBytes = usedBytes;
          outState.lastBlockNumber = lastBlockNumber;
          memcpy(outState.lastBlockHash32, lastBlockHash, 32);
          memcpy(outState.lastBlockSignature64, lastBlockSig, 64);
          outState.arweaveTxId = arweaveTxId;
        }
      }
      continue;
    }
    if (blockType == kBlockTypeServerProfile) {
      uint8_t isServer = 0;
      if (!readU8(isServer)) {
        errorOut = "Bad server profile";
        return false;
      }
      outState.isServer = isServer == 1;
      if (outState.isServer) {
        outState.addressFormatType = 0;
        outState.addressFormatVersion = 0;
        uint8_t syncCount = 0;
        if (!readU8(outState.addressFormatType)
            || !readU8(outState.addressFormatVersion)
            || !readStringU8(outState.serverAddress)
            || !readU8(syncCount)) {
          errorOut = "Bad server address";
          return false;
        }
        outState.syncServers.clear();
        for (uint8_t j = 0; j < syncCount; ++j) {
          String syncServer;
          if (!readStringU8(syncServer)) {
            errorOut = "Bad sync_servers";
            return false;
          }
          outState.syncServers.push_back(syncServer);
        }
      }
      continue;
    }
    if (blockType == kBlockTypeAccessServers) {
      uint8_t accessCount = 0;
      if (!readU8(accessCount)) {
        errorOut = "Bad access servers";
        return false;
      }
      outState.accessServers.clear();
      for (uint8_t j = 0; j < accessCount; ++j) {
        String accessServer;
        if (!readStringU8(accessServer)) {
          errorOut = "Bad access server item";
          return false;
        }
        outState.accessServers.push_back(accessServer);
      }
      continue;
    }
    if (blockType == kBlockTypeSessions) {
      uint8_t sessionsMode = 0;
      uint8_t sessionsCount = 0;
      if (!readU8(sessionsMode) || !readU8(sessionsCount)) {
        errorOut = "Bad sessions block";
        return false;
      }
      outState.sessionsMode = sessionsMode;
      outState.sessions.clear();
      for (uint8_t j = 0; j < sessionsCount; ++j) {
        ShinePdaSessionRecord rec;
        if (!readU8(rec.sessionType)
            || !readU8(rec.sessionVersion)
            || !readStringU8(rec.sessionName)
            || !readBytes(rec.sessionPubKey32, 32)) {
          errorOut = "Bad session item";
          return false;
        }
        outState.sessions.push_back(rec);
      }
      continue;
    }
    if (blockType == kBlockTypeTrustedState) {
      if (!readU8(outState.trustedCount)) {
        errorOut = "Bad trusted block";
        return false;
      }
      continue;
    }
    errorOut = "Unknown PDA block";
    return false;
  }

  if (offset + 64 > recordLen) {
    errorOut = "Missing PDA signature";
    return false;
  }
  outState.found = true;
  return true;
}

static bool readShineUserPda(const String &login, ShinePdaUserState &outState, String &errorOut) {
  outState = ShinePdaUserState{};
  errorOut = "";
  String cleanLogin = normalizeLoginValue(login);
  if (cleanLogin.isEmpty()) {
    errorOut = "Login not set";
    return false;
  }
  if (gSolanaRpcUrl.isEmpty()) {
    errorOut = "Solana RPC not set";
    return false;
  }

  uint8_t userPda[32] = {};
  std::vector<std::vector<uint8_t>> seeds = {
      std::vector<uint8_t>((const uint8_t *)kShineUsersUserPdaSeedPrefix,
                           (const uint8_t *)kShineUsersUserPdaSeedPrefix + strlen(kShineUsersUserPdaSeedPrefix)),
      std::vector<uint8_t>((const uint8_t *)cleanLogin.c_str(),
                           (const uint8_t *)cleanLogin.c_str() + cleanLogin.length()),
  };
  if (!findProgramAddress(seeds, kShineUsersProgramId, userPda)) {
    errorOut = "Cannot derive user PDA";
    return false;
  }

  String pdaB58 = base58From32(userPda);
  Serial.println(String("READ_PDA_RPC_START: ") + pdaB58);
  int code = -1;
  String payload;
  String req = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getAccountInfo\",\"params\":[\"" + pdaB58 + "\",{\"encoding\":\"base64\",\"commitment\":\"confirmed\"}]}";
  if (!httpPostJson(gSolanaRpcUrl, req, code, payload)) {
    errorOut = "Solana RPC unavailable";
    return false;
  }
  Serial.println(String("READ_PDA_RPC_DONE_CODE: ") + String(code));
  if (payload.indexOf("\"value\":null") >= 0) {
    outState.found = false;
    return true;
  }
  String dataB64;
  if (!jsonStringField(payload, "data", dataB64)) {
    errorOut = "PDA base64 missing";
    return false;
  }
  std::vector<uint8_t> raw;
  if (!base64DecodeStd(dataB64, raw)) {
    errorOut = "PDA base64 decode failed";
    return false;
  }
  return parseShineUserPdaBytes(raw, outState, errorOut);
}

static void refreshAccountPdaStatus() {
  gAccountCheckPending = false;
  gShowRegisterAccountButton = false;
  gShowHomeserverPdaActionButton = false;
  gHomeserverPdaActionReason = "";
  gHomeserverPdaCanAdd = false;
  gHomeserverPdaCanFix = false;

  if (gLoginValue.isEmpty() || !gSecretConfigured) {
    gAccountPdaStatus = ACCOUNT_PDA_UNKNOWN;
    gAccountPdaStatusMessage = "account not configured";
    gShineStatusLine = String("SHiNE: ") + shineServerDisplayLabel() + " account not configured";
    clearShineSessionState(false);
    return;
  }

  ShinePdaUserState pdaState;
  String error;
  if (!readShineUserPda(gLoginValue, pdaState, error)) {
    gAccountPdaStatus = ACCOUNT_PDA_MISMATCH;
    gAccountPdaStatusMessage = error.isEmpty() ? "solana check failed" : error;
    gShineStatusLine = String("SHiNE: ") + shineServerDisplayLabel() + " unavailable";
    clearShineSessionState(false);
    if (error == "Solana RPC unavailable") {
      gAccountCheckPending = true;
    }
    return;
  }

  if (!pdaState.found) {
    gAccountPdaStatus = ACCOUNT_PDA_NOT_FOUND;
    gAccountPdaStatusMessage = "user not found";
    gShowRegisterAccountButton = true;
    gShineStatusLine = String("SHiNE: ") + shineServerDisplayLabel() + " account not configured";
    clearShineSessionState(false);
    return;
  }

  gCachedAccountPdaState = pdaState;
  gCachedAccountPdaLogin = normalizeLoginValue(gLoginValue);
  gCachedAccountPdaValid = true;

  uint8_t recoveryPub[32] = {};
  uint8_t rootPub[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t blockchainPub[32] = {};
  if (!base58ToFixed32(gRecoveryPubB58, recoveryPub)
      || !base58ToFixed32(gRootPubB58, rootPub)
      || !base58ToFixed32(gDevicePubB58, clientPub)
      || !base58ToFixed32(gBlockchainPubB58, blockchainPub)) {
    gAccountPdaStatus = ACCOUNT_PDA_MISMATCH;
    gAccountPdaStatusMessage = "local keys invalid";
    gShineStatusLine = String("SHiNE: ") + shineServerDisplayLabel() + " account not configured";
    clearShineSessionState(false);
    return;
  }

  String mismatch;
  if (memcmp(recoveryPub, pdaState.recoveryKey32, 32) != 0) {
    mismatch = "recovery key mismatch";
  } else if (memcmp(rootPub, pdaState.rootKey32, 32) != 0) {
    mismatch = "root key mismatch";
  } else if (memcmp(blockchainPub, pdaState.blockchainKey32, 32) != 0) {
    mismatch = "blockchain key mismatch";
  } else if (memcmp(clientPub, pdaState.clientKey32, 32) != 0) {
    mismatch = "client key mismatch";
  } else if (gHomeserverValue.isEmpty()) {
    mismatch = "homeserver not set";
  } else {
    bool foundSession = false;
    bool sessionMismatch = false;
    for (const auto &session : pdaState.sessions) {
      if (session.sessionType == kSessionTypeHomeserver && session.sessionName == gHomeserverValue) {
        foundSession = true;
        if (gHomeserverPubB58.isEmpty()) {
          sessionMismatch = true;
        } else {
          uint8_t homeserverPub[32] = {};
          if (!base58ToFixed32(gHomeserverPubB58, homeserverPub)
              || memcmp(homeserverPub, session.sessionPubKey32, 32) != 0) {
            sessionMismatch = true;
          }
        }
        break;
      }
    }
    if (!foundSession) {
      mismatch = "homeserver not in PDA";
    } else if (sessionMismatch) {
      mismatch = "homeserver key mismatch";
    }
  }

  if (!mismatch.isEmpty()) {
    gAccountPdaStatus = ACCOUNT_PDA_MISMATCH;
    gAccountPdaStatusMessage = mismatch;
    if (mismatch == "homeserver not in PDA") {
      gShowHomeserverPdaActionButton = true;
      gHomeserverPdaActionReason = mismatch;
      gHomeserverPdaCanAdd = true;
    } else if (mismatch == "homeserver key mismatch") {
      gShowHomeserverPdaActionButton = true;
      gHomeserverPdaActionReason = mismatch;
      gHomeserverPdaCanFix = true;
    }
    gShineStatusLine = String("SHiNE: ") + shineServerDisplayLabel() + " account not configured";
    clearShineSessionState(false);
    return;
  }

  gAccountPdaStatus = ACCOUNT_PDA_OK;
  gAccountPdaStatusMessage = "ok";
}

static void manageAccountPdaRefresh() {
  if (!gAccountCheckPending) {
    return;
  }
  if (WiFi.status() != WL_CONNECTED) {
    return;
  }
  unsigned long now = millis();
  if (gLastAccountCheckMs != 0 && now - gLastAccountCheckMs < ACCOUNT_CHECK_RETRY_MS) {
    return;
  }
  gLastAccountCheckMs = now;
  refreshAccountPdaStatus();
}

static bool waitForClientBytes(WiFiClientSecure &client, size_t need, uint32_t timeoutMs) {
  unsigned long start = millis();
  while (client.connected() && millis() - start < timeoutMs) {
    if ((size_t)client.available() >= need) {
      return true;
    }
    delay(2);
  }
  return false;
}

static bool ensureWebSocketConnected(SimpleWebSocketClient &ws, const String &url, String &errorOut) {
  errorOut = "";
  if (ws.connected && ws.client.connected()) {
    return true;
  }

  closeWebSocket(ws);

  bool secure = false;
  if (!parseUrlHostPortPath(url, ws.host, ws.port, ws.path, secure)) {
    errorOut = "bad WS url";
    return false;
  }

  ws.client.setInsecure();
  ws.client.setTimeout(SHINE_WS_CONNECT_TIMEOUT_MS);
  if (!ws.client.connect(ws.host.c_str(), ws.port)) {
    errorOut = "WS connect failed";
    return false;
  }

  uint8_t keyRaw[16];
  for (size_t i = 0; i < sizeof(keyRaw); ++i) {
    keyRaw[i] = (uint8_t)esp_random();
  }
  String secKey = bytesToBase64String(keyRaw, sizeof(keyRaw));
  String request =
      String("GET ") + ws.path + " HTTP/1.1\r\n"
      + "Host: " + ws.host + ":" + String(ws.port) + "\r\n"
      + "Upgrade: websocket\r\n"
      + "Connection: Upgrade\r\n"
      + "Sec-WebSocket-Version: 13\r\n"
      + "Sec-WebSocket-Key: " + secKey + "\r\n"
      + "User-Agent: SHiNE-ESP32\r\n\r\n";
  ws.client.print(request);

  String statusLine = ws.client.readStringUntil('\n');
  if (statusLine.indexOf("101") < 0) {
    errorOut = String("WS handshake failed: ") + statusLine;
    closeWebSocket(ws);
    return false;
  }

  while (ws.client.connected()) {
    String headerLine = ws.client.readStringUntil('\n');
    headerLine.trim();
    if (headerLine.isEmpty()) {
      break;
    }
  }

  ws.connected = true;
  return true;
}

static bool wsSendFrame(SimpleWebSocketClient &ws, uint8_t opcode, const uint8_t *data, size_t len) {
  if (!ws.connected || !ws.client.connected()) {
    return false;
  }
  uint8_t header[10];
  size_t headerLen = 0;
  header[headerLen++] = 0x80 | (opcode & 0x0F);
  if (len < 126) {
    header[headerLen++] = 0x80 | (uint8_t)len;
  } else {
    header[headerLen++] = 0x80 | 126;
    header[headerLen++] = (uint8_t)((len >> 8) & 0xFF);
    header[headerLen++] = (uint8_t)(len & 0xFF);
  }
  uint8_t mask[4];
  for (int i = 0; i < 4; ++i) {
    mask[i] = (uint8_t)esp_random();
    header[headerLen++] = mask[i];
  }
  if (ws.client.write(header, headerLen) != (int)headerLen) {
    closeWebSocket(ws);
    return false;
  }
  for (size_t i = 0; i < len; ++i) {
    uint8_t byte = data ? (data[i] ^ mask[i % 4]) : mask[i % 4];
    if (ws.client.write(&byte, 1) != 1) {
      closeWebSocket(ws);
      return false;
    }
  }
  return true;
}

static bool wsSendText(SimpleWebSocketClient &ws, const String &payload) {
  return wsSendFrame(ws, 0x1, reinterpret_cast<const uint8_t *>(payload.c_str()), payload.length());
}

static bool wsReadTextFrame(SimpleWebSocketClient &ws, String &messageOut, uint32_t timeoutMs) {
  messageOut = "";
  while (ws.connected && ws.client.connected()) {
    if (!waitForClientBytes(ws.client, 2, timeoutMs)) {
      closeWebSocket(ws);
      return false;
    }
    uint8_t hdr[2];
    if (ws.client.read(hdr, 2) != 2) {
      closeWebSocket(ws);
      return false;
    }
    uint8_t opcode = hdr[0] & 0x0F;
    bool masked = (hdr[1] & 0x80) != 0;
    uint64_t payloadLen = hdr[1] & 0x7F;
    if (payloadLen == 126) {
      if (!waitForClientBytes(ws.client, 2, timeoutMs)) {
        closeWebSocket(ws);
        return false;
      }
      uint8_t ext[2];
      if (ws.client.read(ext, 2) != 2) {
        closeWebSocket(ws);
        return false;
      }
      payloadLen = ((uint16_t)ext[0] << 8) | ext[1];
    } else if (payloadLen == 127) {
      closeWebSocket(ws);
      return false;
    }
    uint8_t mask[4] = {};
    if (masked) {
      if (!waitForClientBytes(ws.client, 4, timeoutMs) || ws.client.read(mask, 4) != 4) {
        closeWebSocket(ws);
        return false;
      }
    }
    if (payloadLen > 4096) {
      closeWebSocket(ws);
      return false;
    }
    std::vector<uint8_t> payload(payloadLen);
    if (payloadLen > 0) {
      if (!waitForClientBytes(ws.client, payloadLen, timeoutMs)
          || ws.client.read(payload.data(), payloadLen) != (int)payloadLen) {
        closeWebSocket(ws);
        return false;
      }
      if (masked) {
        for (size_t i = 0; i < payloadLen; ++i) {
          payload[i] ^= mask[i % 4];
        }
      }
    }

    if (opcode == 0x8) {
      closeWebSocket(ws);
      return false;
    }
    if (opcode == 0x9) {
      wsSendFrame(ws, 0xA, payload.data(), payload.size());
      continue;
    }
    if (opcode == 0xA) {
      continue;
    }
    if (opcode == 0x1) {
      messageOut = "";
      messageOut.reserve(payload.size());
      for (uint8_t byte : payload) {
        messageOut += (char)byte;
      }
      return true;
    }
  }
  closeWebSocket(ws);
  return false;
}

static bool shineWsRequest(SimpleWebSocketClient &ws, const String &op, const String &payloadJson, String &responseOut, uint32_t timeoutMs) {
  responseOut = "";
  String requestId = String("esp32-") + String(gWsRequestCounter++);
  String request = String("{\"op\":\"") + op + "\",\"requestId\":\"" + requestId + "\",\"payload\":" + payloadJson + "}";
  if (!wsSendText(ws, request)) {
    return false;
  }
  unsigned long start = millis();
  while (millis() - start < timeoutMs) {
    String frame;
    if (!wsReadTextFrame(ws, frame, timeoutMs)) {
      return false;
    }
    if (frame.indexOf("\"requestId\":\"" + requestId + "\"") >= 0 && frame.indexOf("\"op\":\"" + op + "\"") >= 0) {
      responseOut = frame;
      return true;
    }
    queueIncomingWalletRpcRequest(frame);
  }
  return false;
}

static bool queueIncomingWalletRpcRequest(const String &frame) {
  if (frame.indexOf("\"op\":\"IncomingCallSignal\"") < 0 || frame.indexOf("\"event\":true") < 0) {
    return false;
  }
  int payloadPos = frame.indexOf("\"payload\":");
  if (payloadPos < 0) {
    return false;
  }
  int objectStart = frame.indexOf('{', payloadPos);
  if (objectStart < 0) {
    return false;
  }
  int objectEnd = -1;
  String payloadJson;
  if (!extractJsonObjectAt(frame, objectStart, objectEnd, payloadJson)) {
    return false;
  }
  uint64_t type = 0;
  String fromLogin;
  String fromSessionId;
  String callId;
  String data;
  if (!jsonInt64Field(payloadJson, "type", type)
      || !jsonStringField(payloadJson, "fromLogin", fromLogin)
      || !jsonStringField(payloadJson, "fromSessionId", fromSessionId)
      || !jsonStringField(payloadJson, "callId", callId)
      || !jsonStringField(payloadJson, "data", data)) {
    return false;
  }
  if ((int)type != kWalletRpcSignalTypeRequest) {
    return false;
  }
  PendingWalletRpcRequest item;
  item.fromLogin = fromLogin;
  item.fromSessionId = fromSessionId;
  item.callId = callId;
  item.type = (int)type;
  item.data = data;
  gPendingWalletRpcRequests.push_back(item);
  return true;
}

static void processPendingWalletRpcRequests() {
  if (gPendingWalletRpcRequests.empty() || !gShineAuthenticated || !gShineWs.connected || !gShineWs.client.connected()) {
    return;
  }

  while (!gPendingWalletRpcRequests.empty()) {
    if (gActiveWalletSignRequest.active) {
      return;
    }
    PendingWalletRpcRequest item = gPendingWalletRpcRequests.front();
    gPendingWalletRpcRequests.erase(gPendingWalletRpcRequests.begin());

    String operation;
    String requestId;
    jsonStringField(item.data, "operation", operation);
    jsonStringField(item.data, "requestId", requestId);

    String responseData;
    if (operation == "get_wallet_public_key") {
      String publicKey = selectedWalletPublicKeyB58();
      if (publicKey.isEmpty()) {
        responseData = String("{\"v\":1,\"op\":\"get_wallet_public_key_result\",\"requestId\":\"")
                     + jsonEscape(requestId)
                     + "\",\"ok\":false,\"error\":\"wallet_unavailable\",\"timeMs\":"
                     + String((unsigned long long)shineNowMs()) + "}";
      } else {
        responseData = String("{\"v\":1,\"op\":\"get_wallet_public_key_result\",\"requestId\":\"")
                     + jsonEscape(requestId)
                     + "\",\"ok\":true,\"wallet\":{\"type\":\"" + jsonEscape(selectedWalletTypeCode())
                     + "\",\"publicKeyBase58\":\"" + jsonEscape(publicKey)
                     + "\"},\"timeMs\":" + String((unsigned long long)shineNowMs()) + "}";
      }
    } else if (operation == "sign_transaction") {
      String publicKeyBase58;
      String transactionBase64;
      String comment;
      jsonStringField(item.data, "publicKeyBase58", publicKeyBase58);
      jsonStringField(item.data, "transactionBase64", transactionBase64);
      jsonStringField(item.data, "comment", comment);
      if (publicKeyBase58.isEmpty() || transactionBase64.isEmpty()) {
        responseData = String("{\"v\":1,\"op\":\"sign_transaction_result\",\"requestId\":\"")
                     + jsonEscape(requestId)
                     + "\",\"ok\":false,\"error\":\"bad_request\",\"timeMs\":"
                     + String((unsigned long long)shineNowMs()) + "}";
      } else {
        queueWalletSignRequest(item, requestId, publicKeyBase58, transactionBase64, comment);
        return;
      }
    } else {
      responseData = String("{\"v\":1,\"op\":\"wallet_rpc_result\",\"requestId\":\"")
                   + jsonEscape(requestId)
                   + "\",\"ok\":false,\"error\":\"unsupported_operation\",\"timeMs\":"
                   + String((unsigned long long)shineNowMs()) + "}";
    }

    sendWalletRpcResponse(item.fromLogin, item.fromSessionId, item.callId, responseData);
  }
}

static void pumpShineIncomingFrames(uint32_t maxFrames) {
  if (!gShineAuthenticated || !gShineWs.connected || !gShineWs.client.connected()) {
    return;
  }
  for (uint32_t i = 0; i < maxFrames; ++i) {
    if (!gShineWs.client.available()) {
      break;
    }
    String frame;
    if (!wsReadTextFrame(gShineWs, frame, 5)) {
      break;
    }
    queueIncomingWalletRpcRequest(frame);
  }
}

static bool refreshPairingRequests(String &errorOut) {
  errorOut = "";
  String authError;
  if (!ensureShineSessionAuthenticated(authError)) {
    errorOut = authError.isEmpty() ? "Homeserver is offline" : authError;
    return false;
  }
  String response;
  if (!shineWsRequest(gShineWs, "ListTrustedDeviceLoginRequests", "{}", response, SHINE_RPC_TIMEOUT_MS)) {
    errorOut = "ListTrustedDeviceLoginRequests failed";
    return false;
  }
  std::vector<PairingRequestUiItem> items;
  if (!parsePairingRequestsResponse(response, items, errorOut)) {
    return false;
  }
  gPairingRequests = items;
  if (gSelectedPairingRequestIndex >= (int)gPairingRequests.size()) {
    gSelectedPairingRequestIndex = -1;
  }
  gPairingStatusMessage = "";
  return true;
}

static bool buildPkcs8FromSeed32(const uint8_t seed32[32], String &pkcs8B64Out) {
  static const uint8_t kEd25519Pkcs8Prefix[] = {
      0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,
      0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20
  };
  std::vector<uint8_t> raw;
  raw.reserve(sizeof(kEd25519Pkcs8Prefix) + 32);
  raw.insert(raw.end(), kEd25519Pkcs8Prefix, kEd25519Pkcs8Prefix + sizeof(kEd25519Pkcs8Prefix));
  raw.insert(raw.end(), seed32, seed32 + 32);
  pkcs8B64Out = bytesToBase64String(raw.data(), raw.size());
  return !pkcs8B64Out.isEmpty();
}

static bool buildPairingSecretsPayload(const PairingRequestUiItem &item, String &payloadJsonOut, String &errorOut) {
  payloadJsonOut = "";
  errorOut = "";
  uint8_t clientSeed[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t deviceSec[64] = {};
  if (!deriveSeedKeypairFromBase58(gDevicePrivB58, clientSeed, clientPub, deviceSec)) {
    errorOut = "Failed to derive client key";
    return false;
  }
  String devicePkcs8;
  if (!buildPkcs8FromSeed32(clientSeed, devicePkcs8)) {
    errorOut = "Failed to encode client key";
    return false;
  }
  payloadJsonOut = String("{\"v\":1,\"type\":\"shine-esp-pairing-transfer\",\"login\":\"") + jsonEscape(gLoginValue)
                 + "\",\"mode\":\"device-only\",\"keys\":{\"clientKey\":\"" + jsonEscape(devicePkcs8)
                 + "\",\"blockchainKey\":\"\",\"rootKey\":\"\"},\"payloadType\":1,\"createdAtMs\":"
                 + String((unsigned long long)shineNowMs()) + "}";
  return true;
}

static bool createDelegatedWalletSessionPayload(const PairingRequestUiItem &item, String &payloadJsonOut, String &errorOut) {
  payloadJsonOut = "";
  errorOut = "";
  uint8_t clientSeed[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t deviceSec[64] = {};
  if (!deriveSeedKeypairFromBase58(gDevicePrivB58, clientSeed, clientPub, deviceSec)) {
    errorOut = "Failed to derive client key";
    return false;
  }

  String wsUrl = shineWsUrl();
  if (wsUrl.isEmpty()) {
    errorOut = "Shine server is not configured";
    return false;
  }

  uint8_t storageRaw[32];
  for (size_t i = 0; i < sizeof(storageRaw); ++i) storageRaw[i] = (uint8_t)esp_random();
  String storagePwd = bytesToBase64String(storageRaw, sizeof(storageRaw));

  SimpleWebSocketClient tempWs;
  String wsError;
  if (!ensureWebSocketConnected(tempWs, wsUrl, wsError)) {
    errorOut = wsError.isEmpty() ? "Delegated session WS connect failed" : wsError;
    return false;
  }

  bool ok = false;
  do {
    String authResp;
    if (!shineWsRequest(tempWs, "AuthChallenge",
                        String("{\"login\":\"") + jsonEscape(gLoginValue) + "\"}",
                        authResp, SHINE_RPC_TIMEOUT_MS)) {
      errorOut = "Delegated AuthChallenge failed";
      break;
    }
    uint64_t statusCode = 0;
    String authNonce;
    if (!jsonInt64Field(authResp, "status", statusCode) || statusCode != 200 || !jsonStringField(authResp, "authNonce", authNonce)) {
      errorOut = "Delegated AuthChallenge rejected";
      break;
    }

    uint64_t timeMs = shineNowMs();
    String preimage = String("AUTH_CREATE_SESSION:") + gLoginValue + ":" + item.requesterSessionKey + ":" + storagePwd + ":" + String((unsigned long long)timeMs) + ":" + authNonce;
    uint8_t signature[64] = {};
    crypto_sign_ed25519_detached(signature, nullptr,
                                 reinterpret_cast<const unsigned char *>(preimage.c_str()),
                                 preimage.length(), deviceSec);
    String clientPlatform = item.requesterClientPlatform;
    clientPlatform.trim();
    if (clientPlatform.isEmpty()) clientPlatform = "Wallet session";
    String createReq = String("{\"login\":\"") + jsonEscape(gLoginValue)
                     + "\",\"sessionKey\":\"" + jsonEscape(item.requesterSessionKey)
                     + "\",\"storagePwd\":\"" + jsonEscape(storagePwd)
                     + "\",\"timeMs\":" + String((unsigned long long)timeMs)
                     + ",\"authNonce\":\"" + jsonEscape(authNonce)
                     + "\",\"clientKey\":\"" + jsonEscape(bytesToBase64String(clientPub, 32))
                     + "\",\"signatureB64\":\"" + jsonEscape(bytesToBase64String(signature, 64))
                     + "\",\"sessionType\":50"
                     + ",\"clientPlatform\":\"" + jsonEscape(clientPlatform)
                     + "\",\"clientInfo\":\"Wallet session approved via ESP32 pairing\"}";
    String createResp;
    if (!shineWsRequest(tempWs, "CreateAuthSession", createReq, createResp, SHINE_RPC_TIMEOUT_MS)) {
      errorOut = "Delegated CreateAuthSession failed";
      break;
    }
    String sessionId;
    if (!jsonInt64Field(createResp, "status", statusCode) || statusCode != 200 || !jsonStringField(createResp, "sessionId", sessionId)) {
      errorOut = "Delegated CreateAuthSession rejected";
      break;
    }

    payloadJsonOut = String("{\"v\":1,\"type\":\"shine-esp-session-attach\",\"login\":\"") + jsonEscape(gLoginValue)
                   + "\",\"session\":{\"sessionId\":\"" + jsonEscape(sessionId)
                   + "\",\"sessionKey\":\"" + jsonEscape(item.requesterSessionKey)
                   + "\",\"storagePwd\":\"" + jsonEscape(storagePwd)
                   + "\",\"sessionType\":50,\"clientPlatform\":\"" + jsonEscape(clientPlatform)
                   + "\"},\"createdAtMs\":" + String((unsigned long long)shineNowMs()) + "}";
    ok = true;
  } while (false);

  closeWebSocket(tempWs);
  return ok;
}

static bool encryptPairingPayloadForRequester(const String &requesterSessionKey, const String &payloadJson, String &encryptedPayloadOut, String &errorOut) {
  encryptedPayloadOut = "";
  errorOut = "";
  if (!requesterSessionKey.startsWith("ed25519/")) {
    errorOut = "Unsupported requesterSessionKey";
    return false;
  }

  std::vector<uint8_t> requesterEdPub;
  if (!base64DecodeStd(requesterSessionKey.substring(8), requesterEdPub) || requesterEdPub.size() != 32) {
    errorOut = "Bad requester session public key";
    return false;
  }
  uint8_t requesterCurvePub[32] = {};
  if (crypto_sign_ed25519_pk_to_curve25519(requesterCurvePub, requesterEdPub.data()) != 0) {
    errorOut = "Failed to convert requester public key";
    return false;
  }

  uint8_t ephPub[32] = {};
  uint8_t ephSec[32] = {};
  if (crypto_box_keypair(ephPub, ephSec) != 0) {
    errorOut = "Failed to create ephemeral key";
    return false;
  }
  uint8_t sharedSecret[32] = {};
  if (crypto_scalarmult(sharedSecret, ephSec, requesterCurvePub) != 0) {
    errorOut = "Failed to derive shared secret";
    return false;
  }
  uint8_t aesKey[32] = {};
  mbedtls_sha256(sharedSecret, sizeof(sharedSecret), aesKey, 0);

  uint8_t iv[12] = {};
  for (size_t i = 0; i < sizeof(iv); ++i) iv[i] = (uint8_t)esp_random();

  std::vector<uint8_t> plain(payloadJson.length());
  for (int i = 0; i < (int)payloadJson.length(); ++i) plain[i] = (uint8_t)payloadJson.charAt(i);
  std::vector<uint8_t> cipher(plain.size());
  uint8_t tag[16] = {};

  mbedtls_gcm_context gcm;
  mbedtls_gcm_init(&gcm);
  bool ok = false;
  if (mbedtls_gcm_setkey(&gcm, MBEDTLS_CIPHER_ID_AES, aesKey, 256) == 0
      && mbedtls_gcm_crypt_and_tag(&gcm,
                                   MBEDTLS_GCM_ENCRYPT,
                                   plain.size(),
                                   iv, sizeof(iv),
                                   nullptr, 0,
                                   plain.data(),
                                   cipher.data(),
                                   sizeof(tag), tag) == 0) {
    std::vector<uint8_t> cipherWithTag = cipher;
    cipherWithTag.insert(cipherWithTag.end(), tag, tag + sizeof(tag));
    String envelopeJson = String("{\"v\":1,\"alg\":\"x25519-aes256-gcm\",\"ephPubB64\":\"")
                        + jsonEscape(bytesToBase64String(ephPub, sizeof(ephPub)))
                        + "\",\"ivB64\":\"" + jsonEscape(bytesToBase64String(iv, sizeof(iv)))
                        + "\",\"cipherB64\":\"" + jsonEscape(bytesToBase64String(cipherWithTag.data(), cipherWithTag.size()))
                        + "\",\"createdAtMs\":" + String((unsigned long long)shineNowMs()) + "}";
    String payloadB64 = bytesToBase64String(reinterpret_cast<const uint8_t *>(envelopeJson.c_str()), envelopeJson.length());
    payloadB64.replace("+", "-");
    payloadB64.replace("/", "_");
    while (payloadB64.endsWith("=")) payloadB64.remove(payloadB64.length() - 1);
    encryptedPayloadOut = String("shine-esp-pairing-v1:") + payloadB64;
    ok = true;
  } else {
    errorOut = "AES-GCM encryption failed";
  }
  mbedtls_gcm_free(&gcm);
  sodium_memzero(sharedSecret, sizeof(sharedSecret));
  sodium_memzero(aesKey, sizeof(aesKey));
  sodium_memzero(ephSec, sizeof(ephSec));
  return ok;
}

static bool approvePairingRequest(const PairingRequestUiItem &item, String &errorOut) {
  errorOut = "";
  String payloadJson;
  if (item.requesterSessionType == 50) {
    if (!createDelegatedWalletSessionPayload(item, payloadJson, errorOut)) {
      return false;
    }
  } else {
    if (!buildPairingSecretsPayload(item, payloadJson, errorOut)) {
      return false;
    }
  }

  String encryptedPayload;
  if (!encryptPairingPayloadForRequester(item.requesterSessionKey, payloadJson, encryptedPayload, errorOut)) {
    return false;
  }

  String authError;
  if (!ensureShineSessionAuthenticated(authError)) {
    errorOut = authError.isEmpty() ? "Homeserver is offline" : authError;
    return false;
  }

  String approveReq = String("{\"pairingId\":\"") + jsonEscape(item.pairingId)
                    + "\",\"encryptedPayload\":\"" + jsonEscape(encryptedPayload) + "\"}";
  String response;
  if (!shineWsRequest(gShineWs, "ApproveTrustedDeviceLogin", approveReq, response, SHINE_RPC_TIMEOUT_MS)) {
    errorOut = "ApproveTrustedDeviceLogin failed";
    return false;
  }
  uint64_t status = 0;
  if (!jsonInt64Field(response, "status", status) || status != 200) {
    errorOut = "ApproveTrustedDeviceLogin rejected";
    return false;
  }
  return true;
}

static bool rejectPairingRequest(const PairingRequestUiItem &item, String &errorOut) {
  errorOut = "";
  String authError;
  if (!ensureShineSessionAuthenticated(authError)) {
    errorOut = authError.isEmpty() ? "Homeserver is offline" : authError;
    return false;
  }
  String rejectReq = String("{\"pairingId\":\"") + jsonEscape(item.pairingId)
                   + "\",\"reason\":\"rejected_by_user\"}";
  String response;
  if (!shineWsRequest(gShineWs, "RejectTrustedDeviceLogin", rejectReq, response, SHINE_RPC_TIMEOUT_MS)) {
    errorOut = "RejectTrustedDeviceLogin failed";
    return false;
  }
  uint64_t status = 0;
  if (!jsonInt64Field(response, "status", status) || status != 200) {
    errorOut = "RejectTrustedDeviceLogin rejected";
    return false;
  }
  return true;
}

static bool ensureShineSessionAuthenticated(String &errorOut) {
  errorOut = "";
  String diagDetails;
  auto failWithDiag = [&](const String &summary) -> bool {
    errorOut = summary;
    saveShineConnectDiag("error", summary, diagDetails);
    printRegisterDiagToSerial();
    return false;
  };
  diagDetails += "kind=shine_connect\n";
  diagDetails += String("uptime_ms=") + String(millis()) + "\n";
  diagDetails += String("login=") + gLoginValue + "\n";
  diagDetails += String("homeserver=") + gHomeserverValue + "\n";
  diagDetails += String("server_login=") + currentShineServerLoginSource() + "\n";
  diagDetails += String("pda_status=") + gAccountPdaStatusMessage + "\n";
  if (WiFi.status() != WL_CONNECTED) {
    diagDetails += "wifi=disconnected\n";
    return failWithDiag("Wi-Fi disconnected");
  }
  diagDetails += String("wifi=connected:") + WiFi.localIP().toString() + "\n";
  if (gLoginValue.isEmpty() || !gSecretConfigured || gHomeserverValue.isEmpty()) {
    return failWithDiag("account not configured");
  }
  if (gAccountPdaStatus != ACCOUNT_PDA_OK) {
    return failWithDiag("account not ready");
  }
  if (!ensureCurrentShineServerUrl(errorOut)) {
    diagDetails += String("server_resolve_error=") + errorOut + "\n";
    return failWithDiag(errorOut);
  }
  diagDetails += String("server_url=") + gShineServerUrl + "\n";
  diagDetails += String("ws_url=") + shineWsUrl() + "\n";

  String wsUrl = shineWsUrl();
  if (wsUrl.isEmpty()) {
    return failWithDiag("shine server not set");
  }
  if (!ensureWebSocketConnected(gShineWs, wsUrl, errorOut)) {
    diagDetails += String("ws_connect_error=") + errorOut + "\n";
    return failWithDiag(errorOut.isEmpty() ? "WS connect failed" : errorOut);
  }
  diagDetails += "ws_connected=true\n";

  {
    String pingResp;
    if (!shineWsRequest(gShineWs, "Ping", "{\"ts\":0}", pingResp, SHINE_RPC_TIMEOUT_MS)) {
      diagDetails += "ping_error=request_failed\n";
      return failWithDiag("Ping failed");
    }
    diagDetails += "ping_response<<\n";
    diagDetails += pingResp;
    diagDetails += "\n>>ping_response\n";
    uint64_t pingStatus = 0;
    uint64_t serverTs = 0;
    if (!jsonInt64Field(pingResp, "status", pingStatus) || pingStatus != 200 || !jsonInt64Field(pingResp, "ts", serverTs)) {
      return failWithDiag("Ping rejected");
    }
    gShineServerTimeOffsetMs = (int64_t)serverTs - (int64_t)millis();
    diagDetails += String("server_time_offset_ms=") + String((long long)gShineServerTimeOffsetMs) + "\n";
  }

  uint8_t clientSeed[32] = {};
  uint8_t clientPub[32] = {};
  uint8_t deviceSec[64] = {};
  uint8_t subSeed[32] = {};
  uint8_t subPub[32] = {};
  uint8_t subSec[64] = {};
  if (!deriveSeedKeypairFromBase58(gDevicePrivB58, clientSeed, clientPub, deviceSec)
      || !deriveSeedKeypairFromBase58(gHomeserverPrivB58, subSeed, subPub, subSec)) {
    return failWithDiag("local key derive failed");
  }

  String sessionKey = buildSessionKeyStringFromPublicBase64(bytesToBase64String(subPub, 32));
  diagDetails += String("session_key=") + sessionKey + "\n";
  if (!gShineSessionKey.isEmpty() && gShineSessionKey != sessionKey) {
    clearShineSessionState(true);
    diagDetails += "stored_session_key_reset=true\n";
  }

  if (!gShineSessionId.isEmpty()) {
    diagDetails += String("stored_session_id=") + gShineSessionId + "\n";
    String response;
    if (shineWsRequest(gShineWs,
                       "SessionChallenge",
                       String("{\"sessionId\":\"") + jsonEscape(gShineSessionId) + "\"}",
                       response)) {
      diagDetails += "session_challenge_response<<\n";
      diagDetails += response;
      diagDetails += "\n>>session_challenge_response\n";
      uint64_t statusCode = 0;
      String nonce;
      if (jsonInt64Field(response, "status", statusCode) && statusCode == 200 && jsonStringField(response, "nonce", nonce)) {
        uint64_t timeMs = shineNowMs();
        String preimage = String("SESSION_LOGIN:") + gShineSessionId + ":" + String((unsigned long long)timeMs) + ":" + nonce;
        uint8_t signature[64] = {};
        crypto_sign_ed25519_detached(signature, nullptr,
                                     reinterpret_cast<const unsigned char *>(preimage.c_str()),
                                     preimage.length(), subSec);
        String loginReq = String("{\"sessionId\":\"") + jsonEscape(gShineSessionId)
                        + "\",\"sessionKey\":\"" + jsonEscape(sessionKey)
                        + "\",\"timeMs\":" + String((unsigned long long)timeMs)
                        + ",\"signatureB64\":\"" + jsonEscape(bytesToBase64String(signature, 64))
                        + "\",\"sessionType\":" + String((unsigned int)kSessionTypeHomeserver)
                        + ",\"clientPlatform\":\"" + jsonEscape(kSessionClientPlatformEsp32)
                        + "\",\"clientInfo\":\"" + jsonEscape(String("ESP32 homeserver:") + gHomeserverValue) + "\"}";
        String loginResp;
        if (shineWsRequest(gShineWs, "SessionLogin", loginReq, loginResp)) {
          diagDetails += "session_login_response<<\n";
          diagDetails += loginResp;
          diagDetails += "\n>>session_login_response\n";
          if (jsonInt64Field(loginResp, "status", statusCode) && statusCode == 200) {
            String storagePwd;
            if (jsonStringField(loginResp, "storagePwd", storagePwd)) {
              gShineStoragePwd = storagePwd;
            }
            gShineSessionKey = sessionKey;
            gShineAuthenticated = true;
            saveShineSessionPrefs();
            saveShineConnectDiag("ok", "SessionLogin success", diagDetails);
            return true;
          }
        }
      }
    }
    clearShineSessionState(true);
    if (!ensureWebSocketConnected(gShineWs, wsUrl, errorOut)) {
      diagDetails += String("ws_reconnect_error=") + errorOut + "\n";
      return failWithDiag(errorOut.isEmpty() ? "WS reconnect failed" : errorOut);
    }
    diagDetails += "stored_session_login_failed=true\n";
  }

  if (gShineStoragePwd.isEmpty()) {
    uint8_t storageRaw[32];
    for (size_t i = 0; i < sizeof(storageRaw); ++i) {
      storageRaw[i] = (uint8_t)esp_random();
    }
    gShineStoragePwd = bytesToBase64String(storageRaw, sizeof(storageRaw));
  }

  String authResp;
  if (!shineWsRequest(gShineWs, "AuthChallenge",
                      String("{\"login\":\"") + jsonEscape(gLoginValue) + "\"}",
                      authResp)) {
    diagDetails += "auth_challenge_error=request_failed\n";
    return failWithDiag("AuthChallenge failed");
  }
  diagDetails += "auth_challenge_response<<\n";
  diagDetails += authResp;
  diagDetails += "\n>>auth_challenge_response\n";
  uint64_t statusCode = 0;
  String authNonce;
  if (!jsonInt64Field(authResp, "status", statusCode) || statusCode != 200 || !jsonStringField(authResp, "authNonce", authNonce)) {
    return failWithDiag("AuthChallenge rejected");
  }

  uint64_t timeMs = shineNowMs();
  String preimage = String("AUTH_CREATE_SESSION:") + gLoginValue + ":" + sessionKey + ":" + gShineStoragePwd + ":" + String((unsigned long long)timeMs) + ":" + authNonce;
  uint8_t signature[64] = {};
  crypto_sign_ed25519_detached(signature, nullptr,
                               reinterpret_cast<const unsigned char *>(preimage.c_str()),
                               preimage.length(), deviceSec);
  String createReq = String("{\"login\":\"") + jsonEscape(gLoginValue)
                   + "\",\"sessionKey\":\"" + jsonEscape(sessionKey)
                   + "\",\"storagePwd\":\"" + jsonEscape(gShineStoragePwd)
                   + "\",\"timeMs\":" + String((unsigned long long)timeMs)
                   + ",\"authNonce\":\"" + jsonEscape(authNonce)
                   + "\",\"clientKey\":\"" + jsonEscape(bytesToBase64String(clientPub, 32))
                   + "\",\"signatureB64\":\"" + jsonEscape(bytesToBase64String(signature, 64))
                   + "\",\"sessionType\":" + String((unsigned int)kSessionTypeHomeserver)
                   + ",\"clientPlatform\":\"" + jsonEscape(kSessionClientPlatformEsp32)
                   + "\",\"clientInfo\":\"" + jsonEscape(String("ESP32 homeserver:") + gHomeserverValue) + "\"}";
  String createResp;
  if (!shineWsRequest(gShineWs, "CreateAuthSession", createReq, createResp)) {
    diagDetails += "create_auth_session_error=request_failed\n";
    return failWithDiag("CreateAuthSession failed");
  }
  diagDetails += "create_auth_session_response<<\n";
  diagDetails += createResp;
  diagDetails += "\n>>create_auth_session_response\n";
  if (!jsonInt64Field(createResp, "status", statusCode) || statusCode != 200 || !jsonStringField(createResp, "sessionId", gShineSessionId)) {
    return failWithDiag("CreateAuthSession rejected");
  }

  gShineSessionKey = sessionKey;
  gShineAuthenticated = true;
  saveShineSessionPrefs();
  diagDetails += String("new_session_id=") + gShineSessionId + "\n";
  saveShineConnectDiag("ok", "CreateAuthSession success", diagDetails);
  return true;
}

static void manageShineConnection() {
  String serverLabel = shineServerDisplayLabel();
  if (gLoginValue.isEmpty() || !gSecretConfigured || gHomeserverValue.isEmpty()) {
    gShineStatusLine = String("SHiNE: ") + serverLabel + " account not configured";
    clearShineSessionState(false);
    gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
    return;
  }
  if (gAccountPdaStatus != ACCOUNT_PDA_OK) {
    gShineStatusLine = String("SHiNE: ") + serverLabel + " account not configured";
    clearShineSessionState(false);
    gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
    return;
  }
  if (WiFi.status() != WL_CONNECTED) {
    gShineStatusLine = String("SHiNE: ") + serverLabel + " unavailable";
    clearShineSessionState(false);
    gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
    return;
  }

  unsigned long now = millis();
  if (!gShineAuthenticated || !gShineWs.connected || !gShineWs.client.connected()) {
    if (shouldPauseShineReconnectForUi()) {
      return;
    }
    if (now - gLastShineAttemptMs < gShineReconnectDelayMs) {
      return;
    }
    gLastShineAttemptMs = now;
    String error;
    if (!ensureCurrentShineServerUrl(error)) {
      gShineStatusLine = String("SHiNE: ") + serverLabel + " unavailable";
      clearShineSessionState(false);
      gShineReconnectDelayMs = min(gShineReconnectDelayMs + SHINE_RECONNECT_MIN_MS, (unsigned long)SHINE_RECONNECT_MAX_MS);
      return;
    }
    serverLabel = shineServerDisplayLabel();
    if (ensureShineSessionAuthenticated(error)) {
      gShineStatusLine = String("SHiNE: ") + serverLabel + " connected";
      gLastShinePingMs = now;
      gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
    } else {
      gShineStatusLine = String("SHiNE: ") + serverLabel + " unavailable";
      clearShineSessionState(false);
      gShineReconnectDelayMs = min(gShineReconnectDelayMs + SHINE_RECONNECT_MIN_MS, (unsigned long)SHINE_RECONNECT_MAX_MS);
    }
    return;
  }

  if (now - gLastShinePingMs >= SHINE_PING_INTERVAL_MS) {
    String pingResp;
    if (shineWsRequest(gShineWs, "Ping", "{\"ts\":0}", pingResp, SHINE_RPC_TIMEOUT_MS)) {
      uint64_t statusCode = 0;
      if (jsonInt64Field(pingResp, "status", statusCode) && statusCode == 200) {
        gLastShinePingMs = now;
        gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
        gShineStatusLine = String("SHiNE: ") + serverLabel + " connected";
        return;
      }
    }
    String details;
    details += "kind=shine_ping\n";
    details += String("uptime_ms=") + String(millis()) + "\n";
    details += String("server_url=") + gShineServerUrl + "\n";
    details += "ping_response<<\n";
    details += pingResp;
    details += "\n>>ping_response\n";
    saveShineConnectDiag("error", "Ping keepalive failed", details);
    printRegisterDiagToSerial();
    gShineStatusLine = String("SHiNE: ") + serverLabel + " unavailable";
    clearShineSessionState(false);
    gShineReconnectDelayMs = min(gShineReconnectDelayMs + SHINE_RECONNECT_MIN_MS, (unsigned long)SHINE_RECONNECT_MAX_MS);
  }

  pumpShineIncomingFrames();
  processPendingWalletRpcRequests();
}

static void upsertKnownWifi(const String &ssid, const String &password) {
  if (ssid.isEmpty()) {
    return;
  }

  int existing = findKnownWifiIndex(ssid);
  if (existing >= 0) {
    gKnownWifiPasswords[existing] = password;
    return;
  }

  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    if (gKnownWifiSsids[i].isEmpty()) {
      gKnownWifiSsids[i] = ssid;
      gKnownWifiPasswords[i] = password;
      return;
    }
  }

  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS - 1; ++i) {
    gKnownWifiSsids[i] = gKnownWifiSsids[i + 1];
    gKnownWifiPasswords[i] = gKnownWifiPasswords[i + 1];
  }
  gKnownWifiSsids[MAX_SAVED_WIFI_NETWORKS - 1] = ssid;
  gKnownWifiPasswords[MAX_SAVED_WIFI_NETWORKS - 1] = password;
}

static void loadPrefs() {
  clearSavedWifiList();
  gWifiSavedSsid = gPrefs.getString("wifi_ssid", "");
  gWifiSavedPassword = gPrefs.getString("wifi_pass", "");
  gWifiKnownGood = gPrefs.getBool("wifi_known_good", false);
  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    String ssidKey = String("wifi_ssid_") + i;
    String passKey = String("wifi_pass_") + i;
    gKnownWifiSsids[i] = gPrefs.getString(ssidKey.c_str(), "");
    gKnownWifiPasswords[i] = gPrefs.getString(passKey.c_str(), "");
  }
  if (!gWifiSavedSsid.isEmpty() && findKnownWifiIndex(gWifiSavedSsid) < 0) {
    upsertKnownWifi(gWifiSavedSsid, gWifiSavedPassword);
  }
  gSolanaRpcUrl = gPrefs.getString("solana_rpc", "https://api.devnet.solana.com");
  String storedShineServerLogin = normalizeLoginValue(gPrefs.getString("shine_server_login", ""));
  if (!isValidShineServerLoginValue(storedShineServerLogin)) {
    String legacyShineServer = normalizeLoginValue(gPrefs.getString("shine_server", ""));
    if (isValidShineServerLoginValue(legacyShineServer)) {
      storedShineServerLogin = legacyShineServer;
    } else {
      storedShineServerLogin = kDefaultShineServerLogin;
    }
  }
  gShineServerLogin = storedShineServerLogin;
  gShineServerUrl = "";
  gResolvedShineServerLogin = "";
  gLoginValue = gPrefs.getString("login", "");
  gHomeserverValue = gPrefs.getString("homeserver", "homeserver1");
  String walletTypeStored = gPrefs.getString("wallet_type", "client.key");
  if (walletTypeStored == "root.key") {
    gSelectedWalletType = WALLET_SELECTION_ROOT;
  } else if (walletTypeStored == "custom") {
    gSelectedWalletType = WALLET_SELECTION_CUSTOM;
  } else {
    gSelectedWalletType = WALLET_SELECTION_DEVICE;
  }
  gCustomWalletName = gPrefs.getString("wallet_custom_name", "");
  gSecretConfigured = gPrefs.getBool("secret_set", false);
  gSecretBase58 = gPrefs.getString("secret_b58", "");
  if (gSecretConfigured && gPrefs.getBytesLength("secret_bytes") == 32) {
    gPrefs.getBytes("secret_bytes", gSecretBytes, 32);
  } else {
    memset(gSecretBytes, 0, sizeof(gSecretBytes));
    if (!gSecretConfigured) {
      gSecretBase58 = "";
    }
  }
  refreshDerivedKeys();
  gShineSessionId = gPrefs.getString("shine_sess_id", "");
  gShineSessionKey = gPrefs.getString("shine_sess_key", "");
  gShineStoragePwd = gPrefs.getString("shine_store_pwd", "");
  gUserPdaAddress = gPrefs.getString("user_pda", "");
  gRegistrationSignature = gPrefs.getString("registration_sig", "");
  gLastRegisterDiagStatus = gPrefs.getString("reg_diag_status", "none");
  gLastRegisterDiagSummary = gPrefs.getString("reg_diag_summary", "");
  loadRegisterDiagDetailsFromPrefs();
  gLastRegisterDiagTime = gPrefs.getString("reg_diag_time", "");
  refreshSelectedWalletBalanceState();
  gAccountCheckPending = true;
  gLastAccountCheckMs = 0;
  gAccountPdaStatus = ACCOUNT_PDA_UNKNOWN;
  gAccountPdaStatusMessage = "Account not checked";
  gShowRegisterAccountButton = false;
  gShowHomeserverPdaActionButton = false;
  gHomeserverPdaActionReason = "";
  gHomeserverPdaActionMessage = "";
  gHomeserverPdaActionDetail = "";
  gHomeserverPdaCanAdd = false;
  gHomeserverPdaCanFix = false;
  gHomeserverPdaResultMessage = "";
  gHomeserverPdaResultDetails = "";
  gHomeserverPdaResultSuccess = false;
  gShineStatusLine = "SHiNE: account not configured";
}

static void saveWifiPrefs() {
  gPrefs.putString("wifi_ssid", gWifiSavedSsid);
  gPrefs.putString("wifi_pass", gWifiSavedPassword);
  gPrefs.putBool("wifi_known_good", gWifiKnownGood);
  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    String ssidKey = String("wifi_ssid_") + i;
    String passKey = String("wifi_pass_") + i;
    if (gKnownWifiSsids[i].isEmpty()) {
      gPrefs.remove(ssidKey.c_str());
      gPrefs.remove(passKey.c_str());
    } else {
      gPrefs.putString(ssidKey.c_str(), gKnownWifiSsids[i]);
      gPrefs.putString(passKey.c_str(), gKnownWifiPasswords[i]);
    }
  }
}

static void saveServerPrefs() {
  gPrefs.putString("solana_rpc", gSolanaRpcUrl);
  gPrefs.putString("shine_server_login", gShineServerLogin);
  gPrefs.remove("shine_server");
}

static void saveAccountPrefs() {
  gPrefs.putString("login", gLoginValue);
  gPrefs.putString("homeserver", gHomeserverValue);
  gPrefs.putString("wallet_type", selectedWalletTypeCode());
  gPrefs.putString("wallet_custom_name", gCustomWalletName);
  gPrefs.putBool("secret_set", gSecretConfigured);
  gPrefs.putString("secret_b58", gSecretBase58);
  if (gUserPdaAddress.isEmpty()) {
    gPrefs.remove("user_pda");
  } else {
    gPrefs.putString("user_pda", gUserPdaAddress);
  }
  if (gRegistrationSignature.isEmpty()) {
    gPrefs.remove("registration_sig");
  } else {
    gPrefs.putString("registration_sig", gRegistrationSignature);
  }
  if (gSecretConfigured) {
    gPrefs.putBytes("secret_bytes", gSecretBytes, 32);
  } else {
    gPrefs.remove("secret_b58");
    gPrefs.remove("secret_bytes");
  }
}

static void clearWifiPrefs() {
  gWifiSavedSsid = "";
  gWifiSavedPassword = "";
  gWifiSelectedSsid = "";
  clearSavedWifiList();
  gWifiKnownGood = false;
  gWifiReconnectEnabled = false;
  gWifiDisconnectedSinceMs = 0;
  gWifiLastReconnectAttemptMs = 0;
  saveWifiPrefs();
  WiFi.disconnect(true, false);
  gWifiStatusMessage = "Saved Wi-Fi cleared";
}

static void beginSavedWifi() {
  if (gWifiSavedSsid.isEmpty() || !gWifiKnownGood) {
    gWifiReconnectEnabled = false;
    return;
  }

  WiFi.mode(WIFI_STA);
  WiFi.begin(gWifiSavedSsid.c_str(), gWifiSavedPassword.c_str());
  gWifiReconnectEnabled = true;
  gWifiDisconnectedSinceMs = millis();
  gWifiLastReconnectAttemptMs = millis();
}

static String wifiHomeStatus() {
  if (gWifiSavedSsid.isEmpty()) {
    return "Wi-Fi not configured";
  }
  if (WiFi.status() == WL_CONNECTED) {
    return "Wi-Fi connected";
  }
  return "Wi-Fi disconnected";
}

static String wifiSavedLabel() {
  if (gWifiSavedSsid.isEmpty()) {
    return "Saved: none";
  }
  int knownCount = 0;
  for (int i = 0; i < MAX_SAVED_WIFI_NETWORKS; ++i) {
    if (!gKnownWifiSsids[i].isEmpty()) {
      knownCount++;
    }
  }
  return String("Saved: ") + gWifiSavedSsid + " (" + knownCount + ")";
}

static String wifiHomeSummary() {
  if (gWifiSavedSsid.isEmpty()) {
    return "Wi-Fi (not configured) not configured";
  }
  if (WiFi.status() == WL_CONNECTED) {
    return String("Wi-Fi (") + WiFi.SSID() + ") connected";
  }
  return String("Wi-Fi (") + gWifiSavedSsid + ") disconnected";
}

static void loadRegisterDiagDetailsFromPrefs() {
  gLastRegisterDiagDetails = "";
  int chunks = gPrefs.getInt("rddn", 0);
  if (chunks <= 0) {
    gLastRegisterDiagDetails = gPrefs.getString("reg_diag_details", "");
    return;
  }
  if (chunks > 12) {
    chunks = 12;
  }
  for (int i = 0; i < chunks; ++i) {
    String key = String("rdd") + i;
    gLastRegisterDiagDetails += gPrefs.getString(key.c_str(), "");
  }
}

static void saveRegisterDiagDetailsToPrefs(const String &details) {
  const int chunkSize = 1400;
  const int maxChunks = 20;
  gPrefs.remove("reg_diag_details");
  for (int i = 0; i < maxChunks; ++i) {
    String key = String("rdd") + i;
    gPrefs.remove(key.c_str());
  }

  String stored = details;
  int requiredChunks = (stored.length() + chunkSize - 1) / chunkSize;
  if (requiredChunks > maxChunks) {
    int maxLen = chunkSize * maxChunks;
    stored = stored.substring(0, maxLen);
    stored += "\n[truncated in NVS]\n";
    requiredChunks = (stored.length() + chunkSize - 1) / chunkSize;
    if (requiredChunks > maxChunks) {
      stored = stored.substring(0, chunkSize * maxChunks);
      requiredChunks = maxChunks;
    }
  }

  for (int i = 0; i < requiredChunks; ++i) {
    int start = i * chunkSize;
    String key = String("rdd") + i;
    gPrefs.putString(key.c_str(), stored.substring(start, min((int)stored.length(), start + chunkSize)));
  }
  gPrefs.putInt("rddn", requiredChunks);
  gLastRegisterDiagDetails = stored;
}

static void clearRegisterDiagDetailsFromPrefs() {
  gPrefs.remove("reg_diag_details");
  gPrefs.remove("rddn");
  for (int i = 0; i < 20; ++i) {
    String key = String("rdd") + i;
    gPrefs.remove(key.c_str());
  }
}

static void saveRegisterDiag(const String &status, const String &summary, const String &details) {
  gLastRegisterDiagStatus = status;
  gLastRegisterDiagSummary = summary;
  gLastRegisterDiagTime = String(shineNowMs());
  gPrefs.putString("reg_diag_status", gLastRegisterDiagStatus);
  gPrefs.putString("reg_diag_summary", gLastRegisterDiagSummary);
  gPrefs.putString("reg_diag_time", gLastRegisterDiagTime);
  saveRegisterDiagDetailsToPrefs(details);
}

static void saveRegisterDiagCheckpoint(const String &summary, const String &details) {
  saveRegisterDiag("progress", summary, details);
}

static void clearRegisterDiag() {
  gLastRegisterDiagStatus = "none";
  gLastRegisterDiagSummary = "";
  gLastRegisterDiagDetails = "";
  gLastRegisterDiagTime = "";
  gPrefs.remove("reg_diag_status");
  gPrefs.remove("reg_diag_summary");
  gPrefs.remove("reg_diag_time");
  clearRegisterDiagDetailsFromPrefs();
}

static void saveShineConnectDiag(const String &status, const String &summary, const String &details) {
  saveRegisterDiag(status, summary, details);
}

static void printRegisterDiagToSerial() {
  Serial.println("LAST_REGISTER_DIAG_BEGIN");
  Serial.println(String("status=") + gLastRegisterDiagStatus);
  Serial.println(String("time_ms=") + gLastRegisterDiagTime);
  Serial.println(String("summary=") + gLastRegisterDiagSummary);
  Serial.println("details<<");
  Serial.println(gLastRegisterDiagDetails);
  Serial.println(">>details");
  Serial.println("LAST_REGISTER_DIAG_END");
}

static void handleUsbSerialCommands() {
  while (Serial.available() > 0) {
    char ch = (char)Serial.read();
    if (ch == '\r') {
      continue;
    }
    if (ch == '\n') {
      String cmd = gSerialCommandBuffer;
      gSerialCommandBuffer = "";
      cmd.trim();
      cmd.toLowerCase();
      if (cmd.isEmpty()) {
        continue;
      }
      if (cmd == "last_error" || cmd == "last_diag" || cmd == "reg_diag") {
        printRegisterDiagToSerial();
      } else if (cmd == "clear_error" || cmd == "clear_diag") {
        clearRegisterDiag();
        Serial.println("register diag cleared");
      } else if (cmd == "help") {
        Serial.println("commands: last_error, last_diag, reg_diag, clear_error, clear_diag, help");
      } else {
        Serial.println(String("unknown command: ") + cmd);
      }
      continue;
    }
    if (gSerialCommandBuffer.length() < 120) {
      gSerialCommandBuffer += ch;
    }
  }
}

static String loginDisplayValue() {
  return gLoginValue.isEmpty() ? "login not set" : gLoginValue;
}

static String homeserverDisplayValue() {
  return gHomeserverValue.isEmpty() ? "homeserver not set" : gHomeserverValue;
}

static String homeSecretStatus() {
  return gSecretConfigured ? "" : "secret not set";
}

static String secretButtonValue() {
  return gSecretConfigured ? "*****" : "not set";
}

static void initPowerManagement() {
  gPowerReady = gPower.begin(Wire, AXP2101_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
  if (!gPowerReady) {
    return;
  }
  gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ);
  gPower.setChargeTargetVoltage(3);
  gPower.clearIrqStatus();
  gPower.enableTemperatureMeasure();
  gPower.enableBattDetection();
  gPower.enableBattVoltageMeasure();
  gPower.enableVbusVoltageMeasure();
  gPower.enableSystemVoltageMeasure();
}

static int batteryPercentValue() {
  if (!gPowerReady || !gPower.isBatteryConnect()) {
    return -1;
  }
  int value = gPower.getBatteryPercent();
  if (value < 0) value = 0;
  if (value > 100) value = 100;
  return value;
}

static bool batteryIsChargingNow() {
  return gPowerReady && gPower.isBatteryConnect() && gPower.isCharging();
}

static int wifiSignalLevel() {
  if (WiFi.status() != WL_CONNECTED) {
    return 0;
  }
  int rssi = WiFi.RSSI();
  if (rssi >= -55) return 4;
  if (rssi >= -67) return 3;
  if (rssi >= -75) return 2;
  return 1;
}

static void drawTopStatusIndicators() {
  int batt = batteryPercentValue();
  bool charging = batteryIsChargingNow();
  String battText = batt >= 0 ? String(batt) + "%" : "--";

  lv_obj_t *battLabel = lv_label_create(gRoot);
  lv_label_set_text(battLabel, battText.c_str());
  lv_obj_set_style_text_font(battLabel, &lv_font_montserrat_16, 0);
  lv_obj_set_style_text_color(battLabel, lv_color_hex(0xC9D3DE), 0);
  lv_obj_set_pos(battLabel, 297, 18);

  if (charging) {
    static const lv_point_t boltPoints[] = {
        {6, 0}, {1, 9}, {5, 9}, {2, 18}, {10, 7}, {6, 7}
    };
    lv_obj_t *chargeBolt = lv_line_create(gRoot);
    lv_line_set_points(chargeBolt, boltPoints, sizeof(boltPoints) / sizeof(boltPoints[0]));
    lv_obj_set_pos(chargeBolt, 337, 15);
    lv_obj_set_style_line_width(chargeBolt, 2, 0);
    lv_obj_set_style_line_color(chargeBolt, lv_color_hex(0xFFD34D), 0);
    lv_obj_set_style_line_rounded(chargeBolt, true, 0);
  }

  lv_obj_t *battery = lv_obj_create(gRoot);
  lv_obj_set_size(battery, 32, 16);
  lv_obj_set_pos(battery, 349, 20);
  lv_obj_set_style_radius(battery, 4, 0);
  lv_obj_set_style_bg_opa(battery, LV_OPA_TRANSP, 0);
  lv_obj_set_style_border_width(battery, 2, 0);
  lv_obj_set_style_border_color(battery, lv_color_hex(0xC9D3DE), 0);
  lv_obj_clear_flag(battery, LV_OBJ_FLAG_SCROLLABLE);

  lv_obj_t *batteryCap = lv_obj_create(gRoot);
  lv_obj_set_size(batteryCap, 4, 8);
  lv_obj_set_pos(batteryCap, 381, 24);
  lv_obj_set_style_radius(batteryCap, 2, 0);
  lv_obj_set_style_bg_color(batteryCap, lv_color_hex(0xC9D3DE), 0);
  lv_obj_set_style_border_width(batteryCap, 0, 0);

  if (batt > 10) {
    lv_obj_t *batteryFill = lv_obj_create(gRoot);
    int fillWidth = max(2, min(26, (batt * 26) / 100));
    lv_obj_set_size(batteryFill, fillWidth, 10);
    lv_obj_set_pos(batteryFill, 352, 23);
    lv_obj_set_style_radius(batteryFill, 2, 0);
    lv_obj_set_style_bg_color(batteryFill, lv_color_hex(0x38B26D), 0);
    lv_obj_set_style_border_width(batteryFill, 0, 0);
  }

  int level = wifiSignalLevel();
  int baseX = 399;
  int baseY = 34;
  for (int i = 0; i < 4; ++i) {
    lv_obj_t *bar = lv_obj_create(gRoot);
    int h = 4 + i * 4;
    lv_obj_set_size(bar, 5, h);
    lv_obj_set_pos(bar, baseX + i * 8, baseY - h);
    lv_obj_set_style_radius(bar, 2, 0);
    lv_obj_set_style_border_width(bar, 0, 0);
    uint32_t color = (level > i) ? 0x4FB3FF : 0x4A5560;
    if (level == 0) color = 0x4A5560;
    lv_obj_set_style_bg_color(bar, lv_color_hex(color), 0);
  }
  if (level == 0) {
    lv_obj_t *off = lv_label_create(gRoot);
    lv_label_set_text(off, "x");
    lv_obj_set_style_text_font(off, &lv_font_montserrat_18, 0);
    lv_obj_set_style_text_color(off, lv_color_hex(0xD26969), 0);
    lv_obj_set_pos(off, baseX + 10, 10);
  }
}

static void clearSecretValue() {
  gSecretConfigured = false;
  gSecretBase58 = "";
  memset(gSecretBytes, 0, sizeof(gSecretBytes));
  refreshDerivedKeys();
  refreshSelectedWalletBalanceState();
  saveAccountPrefs();
  markAccountStateDirty();
}

static void setSecretValue(const uint8_t *bytes32) {
  memcpy(gSecretBytes, bytes32, 32);
  char b58[64];
  shineSecretBase58Encode(bytes32, 32, b58, sizeof(b58));
  gSecretBase58 = b58;
  gSecretConfigured = true;
  refreshDerivedKeys();
  refreshSelectedWalletBalanceState();
  saveAccountPrefs();
  markAccountStateDirty();
}

static void updateWifiReconnectState() {
  wl_status_t status = WiFi.status();
  if (status == WL_CONNECTED) {
    if (gLastWifiStatus != WL_CONNECTED) {
      gWifiStatusMessage = String("Connected: ") + WiFi.localIP().toString();
    }
    gWifiDisconnectedSinceMs = 0;
    gLastWifiStatus = status;
    return;
  }

  if (gLastWifiStatus == WL_CONNECTED && gWifiReconnectEnabled) {
    gWifiDisconnectedSinceMs = millis();
    gWifiLastReconnectAttemptMs = 0;
    gWifiStatusMessage = "Wi-Fi lost. Reconnecting...";
  }
  gLastWifiStatus = status;
}

static void manageWifiReconnect() {
  updateWifiReconnectState();

  if (!gWifiReconnectEnabled || gWifiSavedSsid.isEmpty() || gWifiOperationBusy) {
    return;
  }

  if (WiFi.status() == WL_CONNECTED) {
    return;
  }

  if (gWifiDisconnectedSinceMs == 0) {
    gWifiDisconnectedSinceMs = millis();
  }

  unsigned long disconnectedFor = millis() - gWifiDisconnectedSinceMs;
  unsigned long interval = disconnectedFor >= WIFI_RECONNECT_SLOW_AFTER_MS
                               ? WIFI_RECONNECT_SLOW_MS
                               : WIFI_RECONNECT_FAST_MS;
  if (gWifiLastReconnectAttemptMs != 0 &&
      millis() - gWifiLastReconnectAttemptMs < interval) {
    return;
  }

  gWifiLastReconnectAttemptMs = millis();
  gWifiStatusMessage = disconnectedFor >= WIFI_RECONNECT_SLOW_AFTER_MS
                           ? "Wi-Fi retry every 30s"
                           : "Wi-Fi retry every 10s";
  WiFi.disconnect(false, false);
  WiFi.mode(WIFI_STA);
  WiFi.begin(gWifiSavedSsid.c_str(), gWifiSavedPassword.c_str());
}

static void scanWifiNetworks() {
  gScanResultCount = 0;
  gWifiStatusMessage = "Scanning networks...";
  gWifiOperationBusy = true;
  WiFi.mode(WIFI_STA);
  WiFi.disconnect(false, false);
  delay(100);

  int found = WiFi.scanNetworks();
  if (found <= 0) {
    gWifiStatusMessage = "No networks found";
    gWifiViewMode = WIFI_VIEW_OVERVIEW;
    gWifiOperationBusy = false;
    return;
  }

  gScanResultCount = min(found, MAX_SCAN_RESULTS);
  for (int i = 0; i < gScanResultCount; ++i) {
    gScanResults[i] = WiFi.SSID(i);
  }
  WiFi.scanDelete();
  gWifiStatusMessage = String("Found ") + found + " networks";
  gWifiViewMode = WIFI_VIEW_SCAN_RESULTS;
  gWifiOperationBusy = false;
}

static bool connectWifiNow(const String &ssid, const String &password) {
  gWifiStatusMessage = String("Connecting to ") + ssid + "...";
  rebuildScreen();
  lv_timer_handler();

  gWifiOperationBusy = true;
  WiFi.mode(WIFI_STA);
  WiFi.disconnect(false, false);
  delay(150);
  WiFi.begin(ssid.c_str(), password.c_str());

  unsigned long started = millis();
  while (millis() - started < WIFI_CONNECT_TIMEOUT_MS) {
    if (WiFi.status() == WL_CONNECTED) {
      gWifiSavedSsid = ssid;
      gWifiSavedPassword = password;
      upsertKnownWifi(ssid, password);
      gWifiKnownGood = true;
      gWifiReconnectEnabled = true;
      gWifiDisconnectedSinceMs = 0;
      gWifiLastReconnectAttemptMs = 0;
      gLastWifiStatus = WL_CONNECTED;
      saveWifiPrefs();
      gWifiStatusMessage = String("Connected: ") + WiFi.localIP().toString();
      gWifiOperationBusy = false;
      return true;
    }
    delay(200);
  }

  WiFi.disconnect(false, false);
  gWifiStatusMessage = "Connection failed";
  gWifiOperationBusy = false;
  return false;
}

static void openEditor(EditContext context,
                       Screen returnScreen,
                       const String &title,
                       const String &hint,
                       const String &value,
                       bool isPassword) {
  gEditContext = context;
  gEditReturnScreen = returnScreen;
  gEditTitle = title;
  gEditHint = hint;
  gEditValue = value;
  gEditIsPassword = isPassword;
  gKeyboardPage = 0;
  gKeyboardMode = KEYBOARD_MODE_ALPHA;
  gKeyboardShift = false;
  showScreen(SCREEN_TEXT_EDIT);
}

static void applyEditorValue() {
  String value = gInputTextArea ? String(lv_textarea_get_text(gInputTextArea)) : gEditValue;

  if (gEditContext == EDIT_CONTEXT_WIFI_PASSWORD) {
    bool ok = connectWifiNow(gWifiSelectedSsid, value);
    gWifiViewMode = WIFI_VIEW_OVERVIEW;
    if (ok) {
      showScreen(SCREEN_HOME);
    } else {
      showScreen(SCREEN_WIFI);
    }
    return;
  }

  if (gEditContext == EDIT_CONTEXT_SOLANA_RPC) {
    gSolanaRpcUrl = value;
    saveServerPrefs();
    gServerStatusMessage = "Solana RPC saved";
    markAccountStateDirty();
    showScreen(SCREEN_SERVER);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_SHINE_SERVER) {
    gShineServerLogin = normalizeLoginValue(value);
    if (!isValidShineServerLoginValue(gShineServerLogin)) {
      gShineServerLogin = kDefaultShineServerLogin;
    }
    gShineServerUrl = "";
    gResolvedShineServerLogin = "";
    saveServerPrefs();
    gServerStatusMessage = "SHiNE server login saved";
    clearShineSessionState(false);
    gShineReconnectDelayMs = SHINE_RECONNECT_MIN_MS;
    gLastShineAttemptMs = 0;
    gShineStatusLine = String("SHiNE: ") + gShineServerLogin + " reconnect pending";
    showScreen(SCREEN_SERVER);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_LOGIN) {
    value.trim();
    String oldLogin = gLoginValue;
    gLoginValue = value;
    if (gLoginValue != oldLogin) {
      clearSecretValue();
    } else {
      markAccountStateDirty();
    }
    saveAccountPrefs();
    gAccountStatusMessage = gLoginValue.isEmpty() ? "Login cleared" : "Login saved";
    showScreen(SCREEN_ACCOUNT);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_HOMESERVER) {
    value.trim();
    gHomeserverValue = value;
    refreshDerivedKeys();
    saveAccountPrefs();
    markAccountStateDirty();
    gAccountStatusMessage = gHomeserverValue.isEmpty() ? "Homeserver cleared" : "Homeserver saved";
    showScreen(SCREEN_ACCOUNT);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_WALLET_CUSTOM) {
    value.trim();
    gCustomWalletName = value;
    refreshDerivedKeys();
    gSelectedWalletType = WALLET_SELECTION_CUSTOM;
    refreshSelectedWalletBalanceState();
    saveAccountPrefs();
    showScreen(SCREEN_WALLET);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_SECRET_MANUAL) {
    value.trim();
    uint8_t decoded[64] = {};
    size_t decodedLen = 0;
    String error;
    if (!shineSecretBase58Decode(value.c_str(), decoded, &decodedLen, sizeof(decoded), error)) {
      gAccountStatusMessage = error;
      showScreen(SCREEN_ACCOUNT_SECRET);
      return;
    }
    if (decodedLen < 32) {
      gAccountStatusMessage = "secret too short";
      showScreen(SCREEN_ACCOUNT_SECRET);
      return;
    }
    if (decodedLen > 32) {
      gAccountStatusMessage = "secret too long";
      showScreen(SCREEN_ACCOUNT_SECRET);
      return;
    }
    setSecretValue(decoded);
    gAccountStatusMessage = "Secret saved";
    showScreen(SCREEN_SECRET_SHOW);
    return;
  }

  if (gEditContext == EDIT_CONTEXT_SECRET_GENERATE_PASSWORD) {
    String error;
    if (gLoginValue.isEmpty()) {
      gAccountStatusMessage = "Login not set";
      showScreen(SCREEN_SECRET_GENERATE_INFO);
      return;
    }
    if (!shineSecretStart(gLoginValue.c_str(), value.c_str(), error)) {
      gAccountStatusMessage = error;
      showScreen(SCREEN_SECRET_GENERATE_INFO);
      return;
    }
    gAccountStatusMessage = "Secret generation started";
    showScreen(SCREEN_SECRET_GENERATE_RUNNING);
    return;
  }
}

static void cancelEditor() {
  if (gEditContext == EDIT_CONTEXT_WIFI_PASSWORD) {
    showScreen(SCREEN_WIFI);
  } else {
    showScreen(gEditReturnScreen);
  }
}

static void syncEditValueFromTextarea() {
  if (gInputTextArea) {
    gEditValue = String(lv_textarea_get_text(gInputTextArea));
  }
}

static void keepCursorAtEnd() {
  if (gInputTextArea) {
    lv_textarea_set_cursor_pos(gInputTextArea, LV_TEXTAREA_CURSOR_LAST);
  }
}

static void restoreTextareaFromEditValue() {
  if (gInputTextArea) {
    lv_textarea_set_text(gInputTextArea, gEditValue.c_str());
    keepCursorAtEnd();
  }
}

static void networkSelectCb(lv_event_t *event) {
  if (lv_event_get_code(event) != LV_EVENT_CLICKED || gBlockClick || gLastHandledTouchSequence == gTouchSequence) {
    return;
  }
  gLastHandledTouchSequence = gTouchSequence;
  gSuppressTouchUntilRelease = true;
  gBlockClick = true;

  int index = static_cast<int>(reinterpret_cast<uintptr_t>(lv_event_get_user_data(event)));
  if (index < 0 || index >= gScanResultCount) {
    return;
  }

  gWifiSelectedSsid = gScanResults[index];
  openEditor(EDIT_CONTEXT_WIFI_PASSWORD,
             SCREEN_WIFI,
             "ENTER PASSWORD",
             String("SSID: ") + gWifiSelectedSsid,
             savedPasswordForSsid(gWifiSelectedSsid),
             true);
}

static void pairingSelectCb(lv_event_t *event) {
  if (lv_event_get_code(event) != LV_EVENT_CLICKED || gBlockClick || gLastHandledTouchSequence == gTouchSequence) {
    return;
  }
  gLastHandledTouchSequence = gTouchSequence;
  gSuppressTouchUntilRelease = true;
  gBlockClick = true;

  int index = static_cast<int>(reinterpret_cast<uintptr_t>(lv_event_get_user_data(event)));
  if (index < 0 || index >= (int)gPairingRequests.size()) {
    return;
  }
  gSelectedPairingRequestIndex = index;
  showScreen(SCREEN_PAIRING_REQUEST_DETAIL);
}

static void editorKeyCb(lv_event_t *event) {
  if (lv_event_get_code(event) != LV_EVENT_CLICKED || gBlockClick || gLastHandledTouchSequence == gTouchSequence || !gInputTextArea) {
    return;
  }
  gLastHandledTouchSequence = gTouchSequence;
  gSuppressTouchUntilRelease = true;
  gBlockClick = true;

  const char *token = static_cast<const char *>(lv_event_get_user_data(event));
  if (!token) {
    return;
  }

  if (strcmp(token, "<DEL>") == 0) {
    lv_textarea_del_char(gInputTextArea);
    syncEditValueFromTextarea();
    keepCursorAtEnd();
    return;
  }
  if (strcmp(token, "<CLR>") == 0) {
    lv_textarea_set_text(gInputTextArea, "");
    syncEditValueFromTextarea();
    keepCursorAtEnd();
    return;
  }
  if (strcmp(token, "<SAVE>") == 0) {
    applyEditorValue();
    return;
  }
  if (strcmp(token, "<CANCEL>") == 0) {
    cancelEditor();
    return;
  }
  if (strcmp(token, "<MODE>") == 0) {
    syncEditValueFromTextarea();
    gKeyboardMode = (gKeyboardMode == KEYBOARD_MODE_ALPHA) ? KEYBOARD_MODE_SYMBOLS : KEYBOARD_MODE_ALPHA;
    gKeyboardPage = 0;
    rebuildScreen();
    return;
  }
  if (strcmp(token, "<SHIFT>") == 0) {
    syncEditValueFromTextarea();
    gKeyboardShift = !gKeyboardShift;
    rebuildScreen();
    return;
  }

  String out = token;
  if (gKeyboardMode == KEYBOARD_MODE_ALPHA && gKeyboardShift) {
    out.toUpperCase();
  }

  keepCursorAtEnd();
  lv_textarea_add_text(gInputTextArea, out.c_str());
  syncEditValueFromTextarea();
  keepCursorAtEnd();
}

static void actionButtonCb(lv_event_t *event) {
  if (lv_event_get_code(event) != LV_EVENT_CLICKED || gBlockClick || gLastHandledTouchSequence == gTouchSequence) {
    return;
  }
  gLastHandledTouchSequence = gTouchSequence;
  gSuppressTouchUntilRelease = true;
  gBlockClick = true;

  ActionId action = static_cast<ActionId>(reinterpret_cast<uintptr_t>(lv_event_get_user_data(event)));
  switch (action) {
    case ACTION_OPEN_SETTINGS:
      showScreen(SCREEN_SETTINGS_MENU);
      break;
    case ACTION_OPEN_WALLET:
      showScreen(SCREEN_WALLET);
      break;
    case ACTION_WALLET_SELECT:
      showScreen(SCREEN_WALLET_SELECT);
      break;
    case ACTION_WALLET_SELECT_DEVICE:
      gSelectedWalletType = WALLET_SELECTION_DEVICE;
      refreshSelectedWalletBalanceState();
      saveAccountPrefs();
      showScreen(SCREEN_WALLET);
      break;
    case ACTION_WALLET_SELECT_ROOT:
      gSelectedWalletType = WALLET_SELECTION_ROOT;
      refreshSelectedWalletBalanceState();
      saveAccountPrefs();
      showScreen(SCREEN_WALLET);
      break;
    case ACTION_WALLET_SELECT_CUSTOM: {
      String customName = gCustomWalletName;
      customName.trim();
      if (customName.isEmpty() || gSelectedWalletType == WALLET_SELECTION_CUSTOM) {
        openEditor(EDIT_CONTEXT_WALLET_CUSTOM,
                   SCREEN_WALLET_SELECT,
                   "CUSTOM WALLET",
                   "",
                   gCustomWalletName,
                   false);
      } else {
        gSelectedWalletType = WALLET_SELECTION_CUSTOM;
        refreshSelectedWalletBalanceState();
        saveAccountPrefs();
        showScreen(SCREEN_WALLET);
      }
      break;
    }
    case ACTION_OPEN_WALLET_QR:
      showScreen(SCREEN_WALLET_QR);
      break;
    case ACTION_WALLET_SIGN_APPROVE:
      if (!respondToActiveWalletSignRequest(true)) {
        gWalletSignStatusMessage = "Approve failed";
        rebuildScreen();
      }
      break;
    case ACTION_WALLET_SIGN_REJECT:
      if (!respondToActiveWalletSignRequest(false)) {
        gWalletSignStatusMessage = "Reject failed";
        rebuildScreen();
      }
      break;
    case ACTION_OPEN_PAIRING_REQUESTS: {
      String error;
      if (!refreshPairingRequests(error)) {
        gPairingStatusMessage = error.isEmpty() ? "Failed to load requests" : error;
      }
      showScreen(SCREEN_PAIRING_REQUESTS);
      break;
    }
    case ACTION_REGISTER_ACCOUNT:
      prepareRegisterAccountScreen();
      showScreen(SCREEN_REGISTER_ACCOUNT_CONFIRM);
      break;
    case ACTION_REGISTER_ACCOUNT_EXECUTE:
      executeRegisterAccountFlow("manual", true);
      break;
    case ACTION_HOMESERVER_PDA_ACTION:
      prepareHomeserverPdaActionScreen();
      showScreen(SCREEN_HOMESERVER_PDA_CONFIRM);
      break;
    case ACTION_HOMESERVER_PDA_ADD_EXECUTE: {
      Serial.println("HOMESERVER_ADD_BUTTON_CLICK");
      gRegisterTriggerSource = "manual-homeserver-add";
      String updateMessage;
      Serial.println("HOMESERVER_ADD_CALL_BEGIN");
      if (!updateHomeserverSessionOnSolana(false, updateMessage)) {
        gHomeserverPdaResultSuccess = false;
        gHomeserverPdaResultMessage = updateMessage;
        gHomeserverPdaResultDetails = "";
      }
      Serial.println(String("HOMESERVER_ADD_CALL_END: ") + updateMessage);
      showScreen(SCREEN_HOMESERVER_PDA_RESULT);
      break;
    }
    case ACTION_HOMESERVER_PDA_FIX_EXECUTE: {
      Serial.println("HOMESERVER_FIX_BUTTON_CLICK");
      gRegisterTriggerSource = "manual-homeserver-fix";
      String updateMessage;
      Serial.println("HOMESERVER_FIX_CALL_BEGIN");
      if (!updateHomeserverSessionOnSolana(true, updateMessage)) {
        gHomeserverPdaResultSuccess = false;
        gHomeserverPdaResultMessage = updateMessage;
        gHomeserverPdaResultDetails = "";
      }
      Serial.println(String("HOMESERVER_FIX_CALL_END: ") + updateMessage);
      showScreen(SCREEN_HOMESERVER_PDA_RESULT);
      break;
    }
    case ACTION_OPEN_WIFI:
      gWifiViewMode = WIFI_VIEW_OVERVIEW;
      showScreen(SCREEN_WIFI);
      break;
    case ACTION_OPEN_SERVER:
      showScreen(SCREEN_SERVER);
      break;
    case ACTION_OPEN_ACCOUNT:
      showScreen(SCREEN_ACCOUNT);
      break;
    case ACTION_BACK_ACCOUNT:
      showScreen(SCREEN_ACCOUNT);
      break;
    case ACTION_BACK_HOME:
      showScreen(SCREEN_HOME);
      break;
    case ACTION_BACK_SETTINGS:
      gWifiViewMode = WIFI_VIEW_OVERVIEW;
      showScreen(SCREEN_SETTINGS_MENU);
      break;
    case ACTION_WIFI_SELECT_NETWORK:
      scanWifiNetworks();
      rebuildScreen();
      break;
    case ACTION_WIFI_CLEAR:
      clearWifiPrefs();
      gWifiViewMode = WIFI_VIEW_OVERVIEW;
      rebuildScreen();
      break;
    case ACTION_SERVER_EDIT_SOLANA:
      openEditor(EDIT_CONTEXT_SOLANA_RPC,
                 SCREEN_SERVER,
                 "EDIT SOLANA RPC",
                 "",
                 gSolanaRpcUrl,
                 false);
      break;
    case ACTION_SERVER_EDIT_SHINE:
      openEditor(EDIT_CONTEXT_SHINE_SERVER,
                 SCREEN_SERVER,
                 "EDIT SHINE SERVER LOGIN",
                 "",
                 gShineServerLogin,
                 false);
      break;
    case ACTION_ACCOUNT_EDIT_LOGIN:
      openEditor(EDIT_CONTEXT_LOGIN,
                 SCREEN_ACCOUNT,
                 "EDIT LOGIN",
                 "",
                 gLoginValue,
                 false);
      break;
    case ACTION_ACCOUNT_EDIT_HOMESERVER:
      showScreen(SCREEN_ACCOUNT_HOMESERVER);
      break;
    case ACTION_ACCOUNT_EDIT_SECRET:
      showScreen(SCREEN_ACCOUNT_SECRET);
      break;
    case ACTION_SECRET_SHOW:
      if (gSecretConfigured) {
        showScreen(SCREEN_SECRET_SHOW);
      }
      break;
    case ACTION_SECRET_MANUAL:
      openEditor(EDIT_CONTEXT_SECRET_MANUAL,
                 SCREEN_ACCOUNT_SECRET,
                 "ENTER SECRET",
                 "",
                 gSecretBase58,
                 false);
      break;
    case ACTION_SECRET_GENERATE:
      showScreen(SCREEN_SECRET_GENERATE_INFO);
      break;
    case ACTION_SECRET_GENERATE_START:
      openEditor(EDIT_CONTEXT_SECRET_GENERATE_PASSWORD,
                 SCREEN_SECRET_GENERATE_INFO,
                 "ENTER PASSWORD",
                 "",
                 "",
                 false);
      break;
    case ACTION_SECRET_GENERATE_CANCEL:
      showScreen(SCREEN_SECRET_GENERATE_CANCEL_CONFIRM);
      break;
    case ACTION_SECRET_GENERATE_CANCEL_YES:
      shineSecretAbort();
      gAccountStatusMessage = "Secret generation cancelled";
      showScreen(SCREEN_ACCOUNT_SECRET);
      break;
    case ACTION_SECRET_GENERATE_CANCEL_NO:
      showScreen(SCREEN_SECRET_GENERATE_RUNNING);
      break;
    case ACTION_ACCOUNT_HOMESERVER_USE_DEFAULT:
      gHomeserverValue = "homeserver1";
      refreshDerivedKeys();
      saveAccountPrefs();
      markAccountStateDirty();
      gAccountStatusMessage = "Homeserver set to homeserver1";
      showScreen(SCREEN_ACCOUNT);
      break;
    case ACTION_ACCOUNT_HOMESERVER_EDIT_MANUAL:
      openEditor(EDIT_CONTEXT_HOMESERVER,
                 SCREEN_ACCOUNT,
                 "EDIT HOMESERVER",
                 "",
                 gHomeserverValue,
                 false);
      break;
    case ACTION_BACK_SECRET_MENU:
      showScreen(SCREEN_ACCOUNT_SECRET);
      break;
    case ACTION_REFRESH_BALANCE: {
      String message;
      gBalanceStatusMessage = "Wallet: loading balance...";
      rebuildScreen();
      lv_timer_handler();
      refreshWalletBalance(message);
      if (gCurrentScreen == SCREEN_HOME || gCurrentScreen == SCREEN_WALLET) {
        rebuildScreen();
      }
      break;
    }
    case ACTION_PAIRING_REFRESH: {
      String error;
      if (!refreshPairingRequests(error)) {
        gPairingStatusMessage = error.isEmpty() ? "Failed to refresh requests" : error;
      }
      rebuildScreen();
      break;
    }
    case ACTION_PAIRING_APPROVE: {
      if (gSelectedPairingRequestIndex >= 0 && gSelectedPairingRequestIndex < (int)gPairingRequests.size()) {
        String error;
        if (approvePairingRequest(gPairingRequests[gSelectedPairingRequestIndex], error)) {
          gPairingStatusMessage = "Request approved";
          refreshPairingRequests(error);
          gSelectedPairingRequestIndex = -1;
          showScreen(SCREEN_PAIRING_REQUESTS);
        } else {
          gPairingStatusMessage = error.isEmpty() ? "Approve failed" : error;
          rebuildScreen();
        }
      }
      break;
    }
    case ACTION_PAIRING_REJECT: {
      if (gSelectedPairingRequestIndex >= 0 && gSelectedPairingRequestIndex < (int)gPairingRequests.size()) {
        String error;
        if (rejectPairingRequest(gPairingRequests[gSelectedPairingRequestIndex], error)) {
          gPairingStatusMessage = "Request rejected";
          refreshPairingRequests(error);
          gSelectedPairingRequestIndex = -1;
          showScreen(SCREEN_PAIRING_REQUESTS);
        } else {
          gPairingStatusMessage = error.isEmpty() ? "Reject failed" : error;
          rebuildScreen();
        }
      }
      break;
    }
    case ACTION_EDITOR_SAVE:
      applyEditorValue();
      break;
    case ACTION_EDITOR_CANCEL:
      cancelEditor();
      break;
    case ACTION_NONE:
    default:
      break;
  }
}

static lv_obj_t *makeButton(const char *text,
                            lv_coord_t x,
                            lv_coord_t y,
                            lv_coord_t w,
                            lv_coord_t h,
                            uint32_t bgColor,
                            ActionId action,
                            const lv_font_t *font = &lv_font_montserrat_22) {
  lv_obj_t *btn = lv_btn_create(gRoot);
  lv_obj_set_size(btn, w, h);
  lv_obj_set_pos(btn, x, y);
  lv_obj_set_style_radius(btn, 18, 0);
  lv_obj_set_style_bg_color(btn, lv_color_hex(bgColor), 0);
  lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(btn, 2, 0);
  lv_obj_set_style_border_color(btn, lv_color_hex(0x6E8AA3), 0);
  lv_obj_set_style_shadow_width(btn, 0, 0);
  lv_obj_add_event_cb(btn, actionButtonCb, LV_EVENT_CLICKED, reinterpret_cast<void *>(static_cast<uintptr_t>(action)));

  lv_obj_t *label = lv_label_create(btn);
  lv_label_set_text(label, text);
  lv_obj_set_width(label, w - 24);
  lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0);
  lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(label, font, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
  lv_obj_center(label);
  return btn;
}

static lv_obj_t *makeButtonLeftText(const char *text,
                                    lv_coord_t x,
                                    lv_coord_t y,
                                    lv_coord_t w,
                                    lv_coord_t h,
                                    uint32_t bgColor,
                                    ActionId action,
                                    const lv_font_t *font = &lv_font_montserrat_22) {
  lv_obj_t *btn = makeButton(text, x, y, w, h, bgColor, action, font);
  lv_obj_t *label = lv_obj_get_child(btn, 0);
  if (label) {
    lv_obj_set_width(label, w - 40);
    lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_LEFT, 0);
    lv_obj_align(label, LV_ALIGN_LEFT_MID, 20, 0);
  }
  return btn;
}

static void makeRichStatusLine(const String &text,
                               lv_coord_t x,
                               lv_coord_t y,
                               lv_coord_t w,
                               const lv_font_t *font = &lv_font_montserrat_18) {
  lv_obj_t *label = lv_label_create(gRoot);
  lv_label_set_recolor(label, true);
  lv_label_set_text(label, text.c_str());
  lv_obj_set_width(label, w);
  lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(label, font, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xD5DEE7), 0);
  lv_obj_set_pos(label, x, y);
}

static lv_obj_t *makeKeyboardButton(const char *label,
                                    const char *token,
                                    lv_coord_t x,
                                    lv_coord_t y,
                                    lv_coord_t w,
                                    lv_coord_t h,
                                    uint32_t bgColor,
                                    const lv_font_t *font = &lv_font_montserrat_18) {
  lv_obj_t *btn = lv_btn_create(gRoot);
  lv_obj_set_size(btn, w, h);
  lv_obj_set_pos(btn, x, y);
  lv_obj_set_style_radius(btn, 12, 0);
  lv_obj_set_style_bg_color(btn, lv_color_hex(bgColor), 0);
  lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(btn, 1, 0);
  lv_obj_set_style_border_color(btn, lv_color_hex(0x6E8AA3), 0);
  lv_obj_set_style_shadow_width(btn, 0, 0);
  lv_obj_add_event_cb(btn, editorKeyCb, LV_EVENT_CLICKED, const_cast<char *>(token));

  lv_obj_t *textObj = lv_label_create(btn);
  lv_label_set_text(textObj, label);
  lv_obj_set_style_text_font(textObj, font, 0);
  lv_obj_set_style_text_color(textObj, lv_color_hex(0xFFFFFF), 0);
  lv_obj_center(textObj);
  return btn;
}

static void makeVersionTag() {
  lv_obj_t *tag = lv_label_create(gRoot);
  lv_label_set_text(tag, TEST_VERSION);
  lv_obj_set_style_text_font(tag, &lv_font_montserrat_14, 0);
  lv_obj_set_style_text_color(tag, lv_color_hex(0x8398AD), 0);
  lv_obj_align(tag, LV_ALIGN_BOTTOM_MID, 0, -10);
}


static void drawHome() {
  setRootStyle();

  lv_obj_t *homeserver = lv_label_create(gRoot);
  lv_label_set_text(homeserver, homeserverDisplayValue().c_str());
  lv_obj_set_style_text_font(homeserver, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(homeserver, lv_color_hex(0xFFFFFF), 0);
  lv_obj_align(homeserver, LV_ALIGN_TOP_LEFT, 24, 18);

  lv_obj_t *login = lv_label_create(gRoot);
  lv_label_set_text(login, loginDisplayValue().c_str());
  lv_obj_set_style_text_font(login, &lv_font_montserrat_22, 0);
  lv_obj_set_style_text_color(login, lv_color_hex(0xD5DEE7), 0);
  lv_obj_align_to(login, homeserver, LV_ALIGN_OUT_BOTTOM_LEFT, 22, 6);

  lv_obj_t *accountDot = lv_obj_create(gRoot);
  lv_obj_set_size(accountDot, 14, 14);
  lv_obj_set_pos(accountDot, 24, 52);
  lv_obj_set_style_radius(accountDot, 7, 0);
  lv_obj_set_style_border_width(accountDot, 2, 0);
  lv_obj_set_style_bg_opa(accountDot, LV_OPA_COVER, 0);
  lv_obj_clear_flag(accountDot, LV_OBJ_FLAG_SCROLLABLE);

  uint32_t dotColor = 0x8AA2B7;
  uint32_t dotBg = 0x08111B;
  uint32_t statusColor = 0xAFC0D1;
  if (gAccountPdaStatus == ACCOUNT_PDA_OK) {
    dotColor = 0x38B26D;
    dotBg = 0x38B26D;
    statusColor = 0x38B26D;
  } else if (gAccountPdaStatus == ACCOUNT_PDA_MISMATCH) {
    dotColor = 0xD26969;
    dotBg = 0xD26969;
    statusColor = 0xD26969;
  } else if (gAccountPdaStatus == ACCOUNT_PDA_NOT_FOUND) {
    dotColor = 0xF0F4F8;
    dotBg = 0x08111B;
    statusColor = 0xF0F4F8;
  }
  lv_obj_set_style_border_color(accountDot, lv_color_hex(dotColor), 0);
  lv_obj_set_style_bg_color(accountDot, lv_color_hex(dotBg), 0);

  if (gAccountPdaStatus != ACCOUNT_PDA_OK) {
    lv_obj_t *accountStatus = lv_label_create(gRoot);
    lv_label_set_text(accountStatus, gAccountPdaStatusMessage.c_str());
    lv_obj_set_style_text_font(accountStatus, &lv_font_montserrat_14, 0);
    lv_obj_set_style_text_color(accountStatus, lv_color_hex(statusColor), 0);
    lv_obj_set_pos(accountStatus, 24, 80);
  }

  if (!gSecretConfigured) {
    lv_obj_t *secret = lv_label_create(gRoot);
    lv_label_set_text(secret, homeSecretStatus().c_str());
    lv_obj_set_style_text_font(secret, &lv_font_montserrat_16, 0);
    lv_obj_set_style_text_color(secret, lv_color_hex(0xB8C6D3), 0);
    lv_obj_align_to(secret, login, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 6);
  }

  drawTopStatusIndicators();
  makeTitle("STATUS", 112, &lv_font_montserrat_28);
  makeRichStatusLine(wifiHomeRichLine(), 24, 164, 432, &lv_font_montserrat_18);
  makeRichStatusLine(shineHomeRichLine(), 24, 202, 432, &lv_font_montserrat_16);
  String walletButtonLabel = String("Wallet: ") + selectedWalletDisplayName();
  makeButtonLeftText(walletButtonLabel.c_str(), 22, 254, 436, 56, 0x355C7D, ACTION_OPEN_WALLET, &lv_font_montserrat_18);
  if (gShowRegisterAccountButton) {
    makeButton("REGISTER ACCOUNT", 20, 360, 210, 78, 0x2A9D8F, ACTION_REGISTER_ACCOUNT, &lv_font_montserrat_20);
  } else if (gShowHomeserverPdaActionButton) {
    const char *label = gHomeserverPdaActionReason == "homeserver key mismatch"
                            ? "FIX HOMESERVER PASSWORD"
                            : "ADD HOMESERVER";
    makeButton(label, 20, 360, 210, 78, 0xC59B2A, ACTION_HOMESERVER_PDA_ACTION, &lv_font_montserrat_18);
  }
  makeButton("SETTINGS", 250, 360, 210, 78, 0x2A6F97, ACTION_OPEN_SETTINGS, &lv_font_montserrat_24);
  makeVersionTag();
}

static void drawWalletScreen() {
  setRootStyle();
  makeTitle("WALLET", 22, &lv_font_montserrat_24);
  String walletLabel = String("Wallet: ") + selectedWalletDisplayName();
  String walletAddress = selectedWalletPublicKeyB58();
  makeButtonLeftText(walletLabel.c_str(), 22, 88, 436, 64, 0x355C7D, ACTION_WALLET_SELECT, &lv_font_montserrat_20);
  makeBody(gBalanceStatusMessage.c_str(), 168, 420);
  if (!walletAddress.isEmpty()) {
    String keyLine = String("PubKey: ") + abbreviateValue(walletAddress, 16, 12);
    makeBody(keyLine.c_str(), 206, 420);
  } else {
    makeBody("Wallet is not available yet", 206, 420);
  }
  makeButton("SHOW BALANCE", 22, 264, 436, 62, 0x2A9D8F, ACTION_REFRESH_BALANCE, &lv_font_montserrat_18);
  makeButton("SHOW WALLET QR", 22, 338, 436, 62, 0x2A6F97, ACTION_OPEN_WALLET_QR, &lv_font_montserrat_18);
  makeVersionTag();
}

static void drawWalletSelectScreen() {
  setRootStyle();
  makeTitle("SELECT WALLET", 22, &lv_font_montserrat_24);
  String currentLine = String("Current: ") + selectedWalletDisplayName();
  makeBody(currentLine.c_str(), 88, 420);
  String deviceLabel = String(gSelectedWalletType == WALLET_SELECTION_DEVICE ? "✓ ClientKey" : "ClientKey");
  String rootLabel = String(gSelectedWalletType == WALLET_SELECTION_ROOT ? "✓ RootKey" : "RootKey");
  String customBase = gCustomWalletName;
  customBase.trim();
  if (customBase.isEmpty()) {
    customBase = "Custom";
  } else {
    customBase = String("Custom: ") + customBase;
  }
  String customLabel = gSelectedWalletType == WALLET_SELECTION_CUSTOM ? String("✓ ") + customBase : customBase;
  makeButton(deviceLabel.c_str(), 22, 146, 436, 64, 0x2A6F97, ACTION_WALLET_SELECT_DEVICE, &lv_font_montserrat_20);
  makeButton(rootLabel.c_str(), 22, 224, 436, 64, 0x355C7D, ACTION_WALLET_SELECT_ROOT, &lv_font_montserrat_20);
  makeButton(customLabel.c_str(), 22, 302, 436, 64, 0x7A5C9B, ACTION_WALLET_SELECT_CUSTOM, &lv_font_montserrat_18);
  makeBody("Tap Custom again to change its name", 386, 420);
  makeVersionTag();
}

static void drawWalletSignRequestScreen() {
  setRootStyle();
  makeTitle("SIGN REQUEST", 18, &lv_font_montserrat_24);

  if (!gActiveWalletSignRequest.active) {
    showMessageAt("No active sign request", 96);
    makeButton("BACK", 140, 360, 200, 72, 0x5A6570, ACTION_OPEN_WALLET, &lv_font_montserrat_22);
    makeVersionTag();
    return;
  }

  lv_obj_t *panel = lv_obj_create(gRoot);
  lv_obj_set_size(panel, 440, 244);
  lv_obj_set_pos(panel, 20, 82);
  lv_obj_set_style_bg_color(panel, lv_color_hex(0x0F1B27), 0);
  lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(panel, 1, 0);
  lv_obj_set_style_border_color(panel, lv_color_hex(0x425466), 0);
  lv_obj_set_style_radius(panel, 14, 0);
  lv_obj_set_style_pad_all(panel, 16, 0);
  lv_obj_clear_flag(panel, LV_OBJ_FLAG_SCROLLABLE);

  String question = String("Sign transaction with ") + selectedWalletDisplayName() + "?";
  String comment = gActiveWalletSignRequest.comment;
  comment.trim();
  if (comment.isEmpty()) {
    comment = "No comment provided";
  }
  String walletLine = String("Wallet: ") + abbreviateValue(gActiveWalletSignRequest.publicKeyBase58, 16, 12);
  String sourceLine = String("From: ") + abbreviateValue(gActiveWalletSignRequest.fromLogin, 14, 8);

  lv_obj_t *qLabel = lv_label_create(panel);
  lv_label_set_text(qLabel, question.c_str());
  lv_obj_set_width(qLabel, 404);
  lv_label_set_long_mode(qLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(qLabel, &lv_font_montserrat_22, 0);
  lv_obj_set_style_text_color(qLabel, lv_color_hex(0xFFFFFF), 0);
  lv_obj_set_pos(qLabel, 0, 0);

  lv_obj_t *walletLabel = lv_label_create(panel);
  lv_label_set_text(walletLabel, walletLine.c_str());
  lv_obj_set_width(walletLabel, 404);
  lv_label_set_long_mode(walletLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(walletLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(walletLabel, lv_color_hex(0xBED5F5), 0);
  lv_obj_set_pos(walletLabel, 0, 52);

  lv_obj_t *sourceLabel = lv_label_create(panel);
  lv_label_set_text(sourceLabel, sourceLine.c_str());
  lv_obj_set_width(sourceLabel, 404);
  lv_label_set_long_mode(sourceLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(sourceLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(sourceLabel, lv_color_hex(0xA8D6A2), 0);
  lv_obj_set_pos(sourceLabel, 0, 82);

  lv_obj_t *commentLabel = lv_label_create(panel);
  lv_label_set_text(commentLabel, comment.c_str());
  lv_obj_set_width(commentLabel, 404);
  lv_label_set_long_mode(commentLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(commentLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(commentLabel, lv_color_hex(0xD5DEE7), 0);
  lv_obj_set_pos(commentLabel, 0, 118);

  if (!gWalletSignStatusMessage.isEmpty()) {
    showMessageAt(gWalletSignStatusMessage, 336);
  }

  makeButton("REJECT", 20, 378, 208, 72, 0x6A2430, ACTION_WALLET_SIGN_REJECT, &lv_font_montserrat_22);
  makeButton("APPROVE", 252, 378, 208, 72, 0x2A9D8F, ACTION_WALLET_SIGN_APPROVE, &lv_font_montserrat_22);
  makeVersionTag();
}

static void drawWalletQrScreen() {
  setRootStyle();
  gWalletQrTapReturnPending = false;

  lv_obj_t *title = lv_label_create(gRoot);
  lv_label_set_text(title, "WALLET QR");
  lv_obj_set_style_text_font(title, &lv_font_montserrat_24, 0);
  lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
  lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 12);
  String qrPayload = walletQrUri();
  if (qrPayload.isEmpty()) {
    saveUiErrorDiag("Wallet QR unavailable", "wallet_address_empty=true\n");
    lv_obj_t *error = lv_label_create(gRoot);
    lv_label_set_text(error, "Wallet not set");
    lv_obj_set_width(error, 380);
    lv_obj_set_style_text_align(error, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_style_text_font(error, &lv_font_montserrat_20, 0);
    lv_obj_set_style_text_color(error, lv_color_hex(0xD26969), 0);
    lv_obj_set_pos(error, 50, 174);
  } else {
    lv_obj_t *panel = lv_obj_create(gRoot);
    lv_obj_set_size(panel, 336, 336);
    lv_obj_set_pos(panel, 72, 54);
    lv_obj_set_style_radius(panel, 18, 0);
    lv_obj_set_style_bg_color(panel, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
    lv_obj_set_style_border_width(panel, 0, 0);
    lv_obj_set_style_shadow_width(panel, 0, 0);
    lv_obj_clear_flag(panel, LV_OBJ_FLAG_SCROLLABLE);

    lv_obj_t *qr = lv_qrcode_create(panel, 320, lv_color_hex(0x111111), lv_color_hex(0xFFFFFF));
    if (qr == nullptr) {
      saveUiErrorDiag("Wallet QR create failed", "stage=create\n");
      lv_obj_t *error = lv_label_create(panel);
      lv_label_set_text(error, "QR create failed");
      lv_obj_set_width(error, 248);
      lv_label_set_long_mode(error, LV_LABEL_LONG_WRAP);
      lv_obj_set_style_text_align(error, LV_TEXT_ALIGN_CENTER, 0);
      lv_obj_set_style_text_font(error, &lv_font_montserrat_18, 0);
      lv_obj_set_style_text_color(error, lv_color_hex(0xA23232), 0);
      lv_obj_align(error, LV_ALIGN_CENTER, 0, 0);
    } else {
      lv_obj_center(qr);
      if (lv_qrcode_update(qr, qrPayload.c_str(), qrPayload.length()) != LV_RES_OK) {
        saveUiErrorDiag("Wallet QR update failed",
                        String("stage=update\npayload_len=") + String(qrPayload.length()) + "\n");
        lv_obj_del(qr);
        lv_obj_t *error = lv_label_create(panel);
        lv_label_set_text(error, "QR update failed");
        lv_obj_set_width(error, 248);
        lv_label_set_long_mode(error, LV_LABEL_LONG_WRAP);
        lv_obj_set_style_text_align(error, LV_TEXT_ALIGN_CENTER, 0);
        lv_obj_set_style_text_font(error, &lv_font_montserrat_18, 0);
        lv_obj_set_style_text_color(error, lv_color_hex(0xA23232), 0);
        lv_obj_align(error, LV_ALIGN_CENTER, 0, 0);
      }
    }
  }

  lv_obj_t *address = lv_label_create(gRoot);
  lv_label_set_text(address, walletQrAddressLine().c_str());
  lv_obj_set_width(address, 420);
  lv_label_set_long_mode(address, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_align(address, LV_TEXT_ALIGN_CENTER, 0);
  lv_obj_set_style_text_font(address, &lv_font_montserrat_24, 0);
  lv_obj_set_style_text_color(address, lv_color_hex(0xB8C6D3), 0);
  lv_obj_set_pos(address, 30, 404);
}

static void drawSettingsMenu() {
  setRootStyle();

  makeTitle("SETTINGS", 18, &lv_font_montserrat_24);
  makeBody("Swipe up/down to move. Swipe right to go home.", 56, 420);

  int totalItems = settingsMenuCount();
  if (totalItems <= 2) {
    gSettingsScrollIndex = 0;
  } else if (gSettingsScrollIndex > totalItems - 2) {
    gSettingsScrollIndex = totalItems - 2;
  }
  if (gSettingsScrollIndex < 0) {
    gSettingsScrollIndex = 0;
  }

  for (int visibleIndex = 0; visibleIndex < 2; ++visibleIndex) {
    int itemIndex = gSettingsScrollIndex + visibleIndex;
    if (itemIndex >= totalItems) {
      break;
    }
    String label = settingsMenuLabel(itemIndex);
    makeButton(label.c_str(), 22, 132 + visibleIndex * 126, 436, 104,
               0x355C7D, settingsMenuAction(itemIndex), &lv_font_montserrat_24);
  }

  lv_obj_t *hint = lv_label_create(gRoot);
  char hintText[48];
  snprintf(hintText, sizeof(hintText), "Items %d-%d of %d",
           gSettingsScrollIndex + 1,
           min(gSettingsScrollIndex + 2, totalItems),
           totalItems);
  lv_label_set_text(hint, hintText);
  lv_obj_set_style_text_font(hint, &lv_font_montserrat_16, 0);
  lv_obj_set_style_text_color(hint, lv_color_hex(0xA8B8C7), 0);
  lv_obj_align(hint, LV_ALIGN_BOTTOM_MID, 0, -34);

  makeVersionTag();
}

static void drawPairingRequestsScreen() {
  setRootStyle();
  makeTitle("REQUESTS:", 18, &lv_font_montserrat_24);
  lv_obj_t *titleLabel = lv_obj_get_child(gRoot, lv_obj_get_child_cnt(gRoot) - 1);
  if (titleLabel) {
    lv_obj_set_x(titleLabel, 194);
  }
  makeButton("REFRESH", 20, 18, 160, 44, 0x2A6F97, ACTION_PAIRING_REFRESH, &lv_font_montserrat_18);

  lv_obj_t *countLabel = lv_label_create(gRoot);
  String countText = String((int)gPairingRequests.size());
  lv_label_set_text(countLabel, countText.c_str());
  lv_obj_set_style_text_font(countLabel, &lv_font_montserrat_36, 0);
  lv_obj_set_style_text_color(countLabel, lv_color_hex(0xD5DEE7), 0);
  lv_obj_align(countLabel, LV_ALIGN_TOP_RIGHT, -22, 10);

  if (!gPairingStatusMessage.isEmpty()) {
    showMessageAt(gPairingStatusMessage, 72);
  }

  lv_obj_t *panel = lv_obj_create(gRoot);
  lv_obj_set_size(panel, 440, 324);
  lv_obj_set_pos(panel, 20, gPairingStatusMessage.isEmpty() ? 84 : 104);
  lv_obj_set_style_bg_color(panel, lv_color_hex(0x0F1B27), 0);
  lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(panel, 1, 0);
  lv_obj_set_style_border_color(panel, lv_color_hex(0x425466), 0);
  lv_obj_set_style_radius(panel, 14, 0);
  lv_obj_set_style_pad_all(panel, 10, 0);
  lv_obj_set_style_pad_row(panel, 10, 0);
  lv_obj_set_scroll_dir(panel, LV_DIR_VER);
  lv_obj_set_scrollbar_mode(panel, LV_SCROLLBAR_MODE_ACTIVE);
  lv_obj_set_flex_flow(panel, LV_FLEX_FLOW_COLUMN);
  lv_obj_set_flex_align(panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);

  if (gPairingRequests.empty()) {
    lv_obj_t *empty = lv_label_create(panel);
    lv_label_set_text(empty, "No active requests");
    lv_obj_set_width(empty, 392);
    lv_label_set_long_mode(empty, LV_LABEL_LONG_WRAP);
    lv_obj_set_style_text_font(empty, &lv_font_montserrat_20, 0);
    lv_obj_set_style_text_color(empty, lv_color_hex(0xA8B8C7), 0);
  } else {
    for (int i = 0; i < (int)gPairingRequests.size(); ++i) {
      const PairingRequestUiItem &item = gPairingRequests[i];
      String sessionNameText = String("Session: ") + pairingSessionNameLabel(item);
      String sessionKindText = String("Kind: ") + pairingSessionKindLabel(item.requesterSessionType);
      lv_obj_t *btn = lv_btn_create(panel);
      lv_obj_set_size(btn, 410, 146);
      lv_obj_set_style_radius(btn, 14, 0);
      lv_obj_set_style_bg_color(btn, lv_color_hex(0x203547), 0);
      lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
      lv_obj_set_style_border_width(btn, 2, 0);
      lv_obj_set_style_border_color(btn, lv_color_hex(0x4D6C82), 0);
      lv_obj_add_event_cb(btn, pairingSelectCb, LV_EVENT_CLICKED, reinterpret_cast<void *>(static_cast<uintptr_t>(i)));

      lv_obj_t *codeLabel = lv_label_create(btn);
      lv_label_set_text(codeLabel, formatPairingShortCode(item.shortCode).c_str());
      lv_obj_set_style_text_font(codeLabel, &lv_font_montserrat_24, 0);
      lv_obj_set_style_text_color(codeLabel, lv_color_hex(0xFFFFFF), 0);
      lv_obj_set_pos(codeLabel, 18, 12);

      lv_obj_t *nameLabel = lv_label_create(btn);
      lv_label_set_text(nameLabel, sessionNameText.c_str());
      lv_obj_set_width(nameLabel, 374);
      lv_label_set_long_mode(nameLabel, LV_LABEL_LONG_WRAP);
      lv_obj_set_style_text_font(nameLabel, &lv_font_montserrat_18, 0);
      lv_obj_set_style_text_color(nameLabel, lv_color_hex(0xD5DEE7), 0);
      lv_obj_set_pos(nameLabel, 18, 56);

      lv_obj_t *kindLabel = lv_label_create(btn);
      lv_label_set_text(kindLabel, sessionKindText.c_str());
      lv_obj_set_width(kindLabel, 374);
      lv_label_set_long_mode(kindLabel, LV_LABEL_LONG_WRAP);
      lv_obj_set_style_text_font(kindLabel, &lv_font_montserrat_18, 0);
      lv_obj_set_style_text_color(kindLabel, lv_color_hex(0xA8D6A2), 0);
      lv_obj_set_pos(kindLabel, 18, 88);
    }
  }
  makeVersionTag();
}

static void drawPairingRequestDetailScreen() {
  setRootStyle();
  makeTitle("REQUEST DETAIL", 18, &lv_font_montserrat_24);

  if (gSelectedPairingRequestIndex < 0 || gSelectedPairingRequestIndex >= (int)gPairingRequests.size()) {
    showMessageAt("Request not selected", 88);
    makeButton("BACK", 140, 360, 200, 72, 0x5A6570, ACTION_OPEN_PAIRING_REQUESTS, &lv_font_montserrat_22);
    makeVersionTag();
    return;
  }

  const PairingRequestUiItem &item = gPairingRequests[gSelectedPairingRequestIndex];
  String question = String("Connect session ") + pairingSessionNameLabel(item) + "?";
  String explain = item.requesterSessionType == 50
      ? "Wallet session. No keys will be transferred."
      : "Client session. Only client key will be transferred. No additional keys will be sent.";
  String sessionNameText = String("Session: ") + pairingSessionNameLabel(item);
  String sessionKindText = String("Kind: ") + pairingSessionKindLabel(item.requesterSessionType);

  lv_obj_t *panel = lv_obj_create(gRoot);
  lv_obj_set_size(panel, 440, 248);
  lv_obj_set_pos(panel, 20, 86);
  lv_obj_set_style_bg_color(panel, lv_color_hex(0x0F1B27), 0);
  lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(panel, 1, 0);
  lv_obj_set_style_border_color(panel, lv_color_hex(0x425466), 0);
  lv_obj_set_style_radius(panel, 14, 0);
  lv_obj_set_style_pad_all(panel, 16, 0);
  lv_obj_clear_flag(panel, LV_OBJ_FLAG_SCROLLABLE);

  lv_obj_t *qLabel = lv_label_create(panel);
  lv_label_set_text(qLabel, question.c_str());
  lv_obj_set_width(qLabel, 404);
  lv_label_set_long_mode(qLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(qLabel, &lv_font_montserrat_22, 0);
  lv_obj_set_style_text_color(qLabel, lv_color_hex(0xFFFFFF), 0);
  lv_obj_set_pos(qLabel, 0, 0);

  lv_obj_t *codeLabel = lv_label_create(panel);
  lv_label_set_text(codeLabel, formatPairingShortCode(item.shortCode).c_str());
  lv_obj_set_style_text_font(codeLabel, &lv_font_montserrat_24, 0);
  lv_obj_set_style_text_color(codeLabel, lv_color_hex(0xD5DEE7), 0);
  lv_obj_set_pos(codeLabel, 0, 48);

  lv_obj_t *nameLabel = lv_label_create(panel);
  lv_label_set_text(nameLabel, sessionNameText.c_str());
  lv_obj_set_width(nameLabel, 404);
  lv_label_set_long_mode(nameLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(nameLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(nameLabel, lv_color_hex(0xD5DEE7), 0);
  lv_obj_set_pos(nameLabel, 0, 92);

  lv_obj_t *kindLabel = lv_label_create(panel);
  lv_label_set_text(kindLabel, sessionKindText.c_str());
  lv_obj_set_width(kindLabel, 404);
  lv_label_set_long_mode(kindLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(kindLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(kindLabel, lv_color_hex(0xA8D6A2), 0);
  lv_obj_set_pos(kindLabel, 0, 124);

  lv_obj_t *explainLabel = lv_label_create(panel);
  lv_label_set_text(explainLabel, explain.c_str());
  lv_obj_set_width(explainLabel, 404);
  lv_label_set_long_mode(explainLabel, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_font(explainLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(explainLabel, lv_color_hex(0xB8C6D3), 0);
  lv_obj_set_pos(explainLabel, 0, 164);

  makeButton("YES", 40, 364, 180, 76, 0x2A9D8F, ACTION_PAIRING_APPROVE, &lv_font_montserrat_22);
  makeButton("NO", 260, 364, 180, 76, 0x7D3A3A, ACTION_PAIRING_REJECT, &lv_font_montserrat_22);
  makeVersionTag();
}

static lv_obj_t *makeNetworkButton(const char *text, int index, lv_coord_t y) {
  lv_obj_t *btn = lv_btn_create(gRoot);
  lv_obj_set_size(btn, 436, 52);
  lv_obj_set_pos(btn, 22, y);
  lv_obj_set_style_radius(btn, 14, 0);
  lv_obj_set_style_bg_color(btn, lv_color_hex(0x2A6F97), 0);
  lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(btn, 2, 0);
  lv_obj_set_style_border_color(btn, lv_color_hex(0x6E8AA3), 0);
  lv_obj_add_event_cb(btn, networkSelectCb, LV_EVENT_CLICKED, reinterpret_cast<void *>(static_cast<uintptr_t>(index)));

  lv_obj_t *label = lv_label_create(btn);
  lv_label_set_text(label, text);
  lv_obj_set_width(label, 404);
  lv_label_set_long_mode(label, LV_LABEL_LONG_DOT);
  lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
  lv_obj_center(label);
  return btn;
}

static void drawWifiOverview() {
  makeTitle("Wi-Fi", 18, &lv_font_montserrat_24);
  showMessageAt(wifiHomeStatus(), 60);
  showMessageAt(wifiSavedLabel(), 92);
  showMessageAt(gWifiStatusMessage, 124);
  makeButton("SELECT NETWORK", 22, 182, 436, 68, 0x2A6F97, ACTION_WIFI_SELECT_NETWORK, &lv_font_montserrat_22);
  makeButton("CLEAR SAVED WI-FI", 22, 270, 436, 68, 0x7D3A3A, ACTION_WIFI_CLEAR, &lv_font_montserrat_20);
  makeButton("BACK", 140, 360, 200, 72, 0x5A6570, ACTION_BACK_SETTINGS, &lv_font_montserrat_22);
}

static void drawWifiScanResults() {
  makeTitle("SELECT NETWORK", 18, &lv_font_montserrat_24);
  showMessageAt(gWifiStatusMessage, 58);
  if (gScanResultCount == 0) {
    showMessageAt("No networks available", 110);
  }
  for (int i = 0; i < gScanResultCount; ++i) {
    makeNetworkButton(gScanResults[i].c_str(), i, 100 + i * 58);
  }
  makeButton("SCAN AGAIN", 22, 370, 210, 64, 0x2A6F97, ACTION_WIFI_SELECT_NETWORK, &lv_font_montserrat_20);
  makeButton("BACK", 248, 370, 210, 64, 0x5A6570, ACTION_BACK_SETTINGS, &lv_font_montserrat_20);
}

static void drawWifiScreen() {
  setRootStyle();

  if (gWifiViewMode == WIFI_VIEW_OVERVIEW) {
    drawWifiOverview();
  } else {
    drawWifiScanResults();
  }

  makeVersionTag();
}

static void drawServerScreen() {
  setRootStyle();
  makeTitle("SERVER", 18, &lv_font_montserrat_24);
  showMessageAt(gServerStatusMessage, 56);
  showMessageAt(String("Solana: ") + gSolanaRpcUrl, 96);
  makeButton("SOLANA RPC", 22, 146, 436, 84, 0x355C7D, ACTION_SERVER_EDIT_SOLANA, &lv_font_montserrat_24);
  showMessageAt(String("SHiNE: ") + shineServerDisplayLabel(), 248);
  if (gUserPdaAddress.isEmpty()) {
    makeButton("SHiNE SERVER LOGIN", 22, 298, 436, 84, 0x355C7D, ACTION_SERVER_EDIT_SHINE, &lv_font_montserrat_22);
  } else {
    makeBody("SHiNE server login is read from PDA.", 312, 360);
  }
  makeBody("Swipe right to return to Settings.", 396, 420);
  makeVersionTag();
}

static void drawAccountScreen() {
  setRootStyle();

  makeTitle("ACCOUNT", 18, &lv_font_montserrat_24);
  showMessageAt(gAccountStatusMessage, 56);
  if (!gUserPdaAddress.isEmpty()) {
    showMessageAt(String("PDA: ") + abbreviateValue(gUserPdaAddress, 10, 6), 80);
  }
  if (!gRegistrationSignature.isEmpty()) {
    showMessageAt(String("TX: ") + abbreviateValue(gRegistrationSignature, 10, 6), 100);
  }

  String loginButton = String("Login (") + (gLoginValue.isEmpty() ? "not set" : gLoginValue) + ")";
  String homeserverButton = String("Homeserver (") + (gHomeserverValue.isEmpty() ? "not set" : gHomeserverValue) + ")";
  String secretButton = String("Secret (") + secretButtonValue() + ")";

  makeButton(loginButton.c_str(), 22, 118, 436, 84, 0x355C7D, ACTION_ACCOUNT_EDIT_LOGIN, &lv_font_montserrat_20);
  makeButton(homeserverButton.c_str(), 22, 222, 436, 84, 0x355C7D, ACTION_ACCOUNT_EDIT_HOMESERVER, &lv_font_montserrat_20);
  makeButton(secretButton.c_str(), 22, 326, 436, 84, 0x355C7D, ACTION_ACCOUNT_EDIT_SECRET, &lv_font_montserrat_20);
  makeBody("Swipe right to return to Settings.", 420, 420);
  makeVersionTag();
}

static void drawAccountHomeserverScreen() {
  setRootStyle();
  makeTitle("HOMESERVER", 18, &lv_font_montserrat_24);
  showMessageAt(String("Current: ") + homeserverDisplayValue(), 56);
  makeBody("If you only use one homeserver, keep the default name homeserver1.", 98, 420);
  makeButton("USE HOMESERVER1", 22, 202, 436, 84, 0x2A9D8F, ACTION_ACCOUNT_HOMESERVER_USE_DEFAULT, &lv_font_montserrat_22);
  makeButton("EDIT MANUALLY", 22, 306, 436, 84, 0x355C7D, ACTION_ACCOUNT_HOMESERVER_EDIT_MANUAL, &lv_font_montserrat_22);
  makeButton("BACK", 140, 402, 200, 54, 0x5A6570, ACTION_BACK_ACCOUNT, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawAccountSecretScreen() {
  setRootStyle();
  makeTitle("MASTER SECRET", 18, &lv_font_montserrat_24);
  showMessageAt(gAccountStatusMessage, 56);
  makeButton(gSecretConfigured ? "SHOW MASTER SECRET" : "MASTER SECRET NOT SET",
             22, 118, 436, 84, gSecretConfigured ? 0x2A6F97 : 0x4A5560,
             gSecretConfigured ? ACTION_SECRET_SHOW : ACTION_NONE, &lv_font_montserrat_22);
  makeButton("ENTER MASTER SECRET MANUALLY (NOT RECOMMENDED)",
             22, 222, 436, 84, 0x355C7D, ACTION_SECRET_MANUAL, &lv_font_montserrat_18);
  makeButton("GENERATE MASTER SECRET",
             22, 326, 436, 84, 0x2A9D8F, ACTION_SECRET_GENERATE, &lv_font_montserrat_22);
  makeBody("Swipe right to return to Account.", 420, 420);
  makeVersionTag();
}

static void drawSecretShowScreen() {
  setRootStyle();
  makeTitle("MASTER SECRET", 18, &lv_font_montserrat_24);
  if (gSecretConfigured) {
    lv_obj_t *panel = lv_obj_create(gRoot);
    lv_obj_set_size(panel, 440, 320);
    lv_obj_set_pos(panel, 20, 60);
    lv_obj_set_style_bg_color(panel, lv_color_hex(0x0F1B27), 0);
    lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
    lv_obj_set_style_border_width(panel, 1, 0);
    lv_obj_set_style_border_color(panel, lv_color_hex(0x425466), 0);
    lv_obj_set_style_radius(panel, 14, 0);
    lv_obj_set_style_pad_top(panel, 14, 0);
    lv_obj_set_style_pad_bottom(panel, 14, 0);
    lv_obj_set_style_pad_left(panel, 30, 0);
    lv_obj_set_style_pad_right(panel, 14, 0);
    lv_obj_set_style_pad_row(panel, 8, 0);
    lv_obj_set_scroll_dir(panel, LV_DIR_VER);
    lv_obj_set_scrollbar_mode(panel, LV_SCROLLBAR_MODE_ACTIVE);
    lv_obj_set_flex_flow(panel, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
    lv_obj_add_event_cb(panel, secretScrollEventCb, LV_EVENT_SCROLL_BEGIN, nullptr);
    lv_obj_add_event_cb(panel, secretScrollEventCb, LV_EVENT_SCROLL_END, nullptr);
    lv_obj_add_event_cb(panel, secretScrollEventCb, LV_EVENT_DELETE, nullptr);

    auto addKeyBlock = [&](const String &title, const String &value) {
      lv_obj_t *titleLabel = lv_label_create(panel);
      lv_label_set_text(titleLabel, title.c_str());
      lv_obj_set_width(titleLabel, 400);
      lv_obj_set_style_text_font(titleLabel, &lv_font_montserrat_18, 0);
      lv_obj_set_style_text_color(titleLabel, lv_color_hex(0xA7D8FF), 0);

      lv_obj_t *valueLabel = lv_label_create(panel);
      lv_label_set_text(valueLabel, value.c_str());
      lv_obj_set_width(valueLabel, 400);
      lv_label_set_long_mode(valueLabel, LV_LABEL_LONG_WRAP);
      lv_obj_set_style_text_font(valueLabel, &lv_font_montserrat_20, 0);
      lv_obj_set_style_text_color(valueLabel, lv_color_hex(0xD9E1EA), 0);
    };

    addKeyBlock("Master Secret", gSecretBase58);
    addKeyBlock("Recovery key", gRecoveryPubB58);
    addKeyBlock("Recovery key priv", gRecoveryPrivB58);
    addKeyBlock("Root key", gRootPubB58);
    addKeyBlock("Root key priv", gRootPrivB58);
    addKeyBlock("Blockchain key", gBlockchainPubB58);
    addKeyBlock("Blockchain key priv", gBlockchainPrivB58);
    addKeyBlock("Client key", gDevicePubB58);
    addKeyBlock("Client key priv", gDevicePrivB58);
    addKeyBlock("Homeserver key", gHomeserverPubB58);
    addKeyBlock("Homeserver key priv", gHomeserverPrivB58);
  } else {
    showMessageAt("Secret not set", 96);
  }
  makeButton("BACK", 140, 392, 200, 56, 0x5A6570, ACTION_BACK_SECRET_MENU, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawSecretGenerateInfoScreen() {
  setRootStyle();
  makeTitle("GENERATE SECRET", 18, &lv_font_montserrat_24);
  showMessageAt(String("Login: ") + (gLoginValue.isEmpty() ? "not set" : gLoginValue), 56);
  makeBody("SD card is required. After password input, secret generation will start and can take 10-30 min.", 100, 420);
  makeButton("ENTER PASSWORD AND START", 22, 248, 436, 84, 0x2A9D8F, ACTION_SECRET_GENERATE_START, &lv_font_montserrat_20);
  makeButton("BACK", 140, 360, 200, 72, 0x5A6570, ACTION_BACK_SECRET_MENU, &lv_font_montserrat_22);
  makeVersionTag();
}

static void drawSecretGenerateRunningScreen() {
  setRootStyle();
  makeTitle("GENERATING SECRET", 18, &lv_font_montserrat_24);
  ShineSecretGenerationStatus status = shineSecretStatus();
  showMessageAt(status.message, 56);
  showMessageAt(String("Login: ") + gLoginValue, 88);

  lv_obj_t *bar = lv_bar_create(gRoot);
  lv_obj_set_size(bar, 436, 34);
  lv_obj_set_pos(bar, 22, 150);
  lv_bar_set_range(bar, 0, 1000);
  int value = status.totalBlocks == 0 ? 0 : (int)((uint64_t)status.doneBlocks * 1000ULL / status.totalBlocks);
  lv_bar_set_value(bar, value, LV_ANIM_OFF);

  char progress[96];
  snprintf(progress, sizeof(progress), "%lu / %lu blocks", (unsigned long)status.doneBlocks, (unsigned long)status.totalBlocks);
  showMessageAt(progress, 204);
  char elapsed[64];
  snprintf(elapsed, sizeof(elapsed), "Elapsed: %lum %lus", (unsigned long)(status.elapsedSec / 60), (unsigned long)(status.elapsedSec % 60));
  showMessageAt(elapsed, 236);
  if (status.done) {
    showMessageAt("Secret generated successfully", 280);
    makeButton("SHOW SECRET", 22, 328, 210, 72, 0x2A6F97, ACTION_SECRET_SHOW, &lv_font_montserrat_20);
    makeButton("BACK", 248, 328, 210, 72, 0x5A6570, ACTION_BACK_SECRET_MENU, &lv_font_montserrat_20);
  } else {
    makeBody("Keep device powered and SD card inserted.", 328, 420);
    makeButton("CANCEL", 140, 372, 200, 56, 0x7D3A3A, ACTION_SECRET_GENERATE_CANCEL, &lv_font_montserrat_20);
  }
  makeVersionTag();
}

static void drawSecretGenerateCancelConfirmScreen() {
  setRootStyle();
  makeTitle("STOP GENERATION?", 26, &lv_font_montserrat_24);
  makeBody("Are you sure you want to stop secret generation?", 102, 420);
  makeBody("Existing saved secret will remain unchanged.", 146, 420);
  makeButton("YES, STOP", 22, 262, 200, 76, 0x7D3A3A, ACTION_SECRET_GENERATE_CANCEL_YES, &lv_font_montserrat_20);
  makeButton("NO, CONTINUE", 238, 262, 220, 76, 0x355C7D, ACTION_SECRET_GENERATE_CANCEL_NO, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawRegisterAccountConfirmScreen() {
  setRootStyle();
  makeTitle("REGISTER ACCOUNT", 22, &lv_font_montserrat_24);
  String topLine = gRegisterConfirmMessage.isEmpty() ? String("Registration check") : gRegisterConfirmMessage;
  makeBody(topLine.c_str(), 96, 420);
  if (!gRegisterConfirmPdaLine.isEmpty()) {
    makeBody(gRegisterConfirmPdaLine.c_str(), 138, 420);
  }
  if (!gRegisterConfirmBalanceLine.isEmpty()) {
    makeBody(gRegisterConfirmBalanceLine.c_str(), 180, 420);
  }
  if (!gRegisterConfirmHomeserverLine.isEmpty()) {
    makeBody(gRegisterConfirmHomeserverLine.c_str(), 222, 420);
  }
  if (gRegisterConfirmCanSubmit) {
    makeButton("REGISTER IN SHINE", 22, 296, 436, 74, 0x2A9D8F, ACTION_REGISTER_ACCOUNT_EXECUTE, &lv_font_montserrat_18);
  } else {
    makeButton("UNAVAILABLE", 22, 296, 436, 74, 0x4A5560, ACTION_NONE, &lv_font_montserrat_20);
  }
  makeButton("BACK", 140, 384, 200, 54, 0x5A6570, ACTION_BACK_HOME, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawRegisterAccountResultScreen() {
  setRootStyle();
  makeTitle("REGISTER RESULT", 22, &lv_font_montserrat_24);
  String resultTopLine = gRegisterResultSuccess ? String("Registration completed successfully") : String("Registration failed");
  makeBody(resultTopLine.c_str(), 96, 420);
  makeBody(gRegisterResultMessage.c_str(), 140, 420);
  if (!gRegisterResultDetails.isEmpty()) {
    makeBody(gRegisterResultDetails.c_str(), 184, 420);
  }
  if (gRegisterResultSuccess) {
    if (!gUserPdaAddress.isEmpty()) {
      String pdaLine = String("user_pda: ") + abbreviateValue(gUserPdaAddress, 12, 8);
      makeBody(pdaLine.c_str(), 228, 420);
    }
    if (!gRegistrationSignature.isEmpty()) {
      String txLine = String("tx: ") + abbreviateValue(gRegistrationSignature, 12, 8);
      makeBody(txLine.c_str(), 270, 420);
    }
  }
  makeButton("BACK HOME", 22, 372, 200, 58, 0x5A6570, ACTION_BACK_HOME, &lv_font_montserrat_20);
  makeButton("ACCOUNT", 258, 372, 200, 58, 0x2A6F97, ACTION_OPEN_ACCOUNT, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawHomeserverPdaConfirmScreen() {
  setRootStyle();
  makeTitle("HOMESERVER PDA", 22, &lv_font_montserrat_24);
  String topLine = gHomeserverPdaActionMessage.isEmpty() ? String("Homeserver action") : gHomeserverPdaActionMessage;
  makeBody(topLine.c_str(), 96, 420);
  if (!gHomeserverPdaActionDetail.isEmpty()) {
    makeBody(gHomeserverPdaActionDetail.c_str(), 146, 420);
  }
  String loginLine = String("Login: ") + loginDisplayValue();
  String homeserverLine = String("Homeserver: ") + homeserverDisplayValue();
  makeBody(loginLine.c_str(), 196, 420);
  makeBody(homeserverLine.c_str(), 236, 420);
  if (gHomeserverPdaCanAdd) {
    makeButton("ADD HOMESERVER", 22, 300, 436, 70, 0xC59B2A, ACTION_HOMESERVER_PDA_ADD_EXECUTE, &lv_font_montserrat_20);
  } else if (gHomeserverPdaCanFix) {
    makeButton("FIX HOMESERVER PASSWORD", 22, 300, 436, 70, 0xC59B2A, ACTION_HOMESERVER_PDA_FIX_EXECUTE, &lv_font_montserrat_16);
  } else {
    makeButton("UNAVAILABLE", 22, 300, 436, 70, 0x4A5560, ACTION_NONE, &lv_font_montserrat_20);
  }
  makeButton("BACK", 140, 386, 200, 54, 0x5A6570, ACTION_BACK_HOME, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawHomeserverPdaResultScreen() {
  setRootStyle();
  makeTitle("HOMESERVER RESULT", 22, &lv_font_montserrat_24);
  String resultTopLine = gHomeserverPdaResultSuccess ? String("Homeserver PDA updated") : String("Homeserver update failed");
  makeBody(resultTopLine.c_str(), 96, 420);
  makeBody(gHomeserverPdaResultMessage.c_str(), 146, 420);
  if (!gHomeserverPdaResultDetails.isEmpty()) {
    makeBody(gHomeserverPdaResultDetails.c_str(), 196, 420);
  }
  makeButton("BACK HOME", 22, 372, 200, 58, 0x5A6570, ACTION_BACK_HOME, &lv_font_montserrat_20);
  makeButton("ACCOUNT", 258, 372, 200, 58, 0x2A6F97, ACTION_OPEN_ACCOUNT, &lv_font_montserrat_20);
  makeVersionTag();
}

static void drawKeyRow(const char *const *tokens,
                       int count,
                       lv_coord_t x,
                       lv_coord_t y,
                       lv_coord_t w,
                       lv_coord_t h,
                       lv_coord_t gap,
                       uint32_t bgColor,
                       bool uppercase = false,
                       const lv_font_t *font = &lv_font_montserrat_18) {
  for (int i = 0; i < count; ++i) {
    String label = tokens[i];
    if (uppercase) {
      label.toUpperCase();
    }
    makeKeyboardButton(label.c_str(), tokens[i], x + i * (w + gap), y, w, h, bgColor, font);
  }
}

static void drawTextEditorKeyboard(lv_coord_t originY) {
  static const char *alphaLeftRow0[] = {"q", "w", "e", "r", "t"};
  static const char *alphaLeftRow1[] = {"a", "s", "d", "f", "g"};
  static const char *alphaLeftRow2[] = {"z", "x", "c", "v", "b"};
  static const char *alphaRightRow0[] = {"y", "u", "i", "o", "p"};
  static const char *alphaRightRow1[] = {"h", "j", "k", "l"};
  static const char *alphaRightRow2[] = {"n", "m", ".", "-"};

  static const char *symLeftRow0[] = {"1", "2", "3", "4", "5"};
  static const char *symLeftRow1[] = {"://", "/", ":", "_", "@"};
  static const char *symLeftRow2[] = {".com", ".net", ".org", ".me", ".io"};
  static const char *symRightRow0[] = {"6", "7", "8", "9", "0"};
  static const char *symRightRow1[] = {"?", "&", "=", "+", "-"};
  static const char *symRightRow2[] = {"%", "#", "~", ":", "/"};

  const lv_coord_t keyH = 62;
  const lv_coord_t keyW5 = 84;
  const lv_coord_t keyW4 = 84;
  const lv_coord_t gap = 8;
  const lv_coord_t row0Y = originY;
  const lv_coord_t row1Y = originY + 68;
  const lv_coord_t row2Y = originY + 136;
  const lv_coord_t row3Y = originY + 208;
  const bool uppercase = gKeyboardMode == KEYBOARD_MODE_ALPHA && gKeyboardShift;

  if (gKeyboardMode == KEYBOARD_MODE_ALPHA) {
    if (gKeyboardPage == 0) {
      drawKeyRow(alphaLeftRow0, 5, 20, row0Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
      drawKeyRow(alphaLeftRow1, 5, 20, row1Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
      drawKeyRow(alphaLeftRow2, 5, 20, row2Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
    } else {
      drawKeyRow(alphaRightRow0, 5, 20, row0Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
      drawKeyRow(alphaRightRow1, 4, 20, row1Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
      drawKeyRow(alphaRightRow2, 4, 20, row2Y, keyW5, keyH, gap, 0x2A6F97, uppercase);
    }
  } else {
    if (gKeyboardPage == 0) {
      drawKeyRow(symLeftRow0, 5, 20, row0Y, keyW5, keyH, gap, 0x2A6F97);
      drawKeyRow(symLeftRow1, 5, 20, row1Y, keyW5, keyH, gap, 0x2A6F97, false, &lv_font_montserrat_16);
      drawKeyRow(symLeftRow2, 5, 20, row2Y, keyW5, keyH, gap, 0x2A6F97, false, &lv_font_montserrat_16);
    } else {
      drawKeyRow(symRightRow0, 5, 20, row0Y, keyW5, keyH, gap, 0x2A6F97);
      drawKeyRow(symRightRow1, 5, 20, row1Y, keyW5, keyH, gap, 0x2A6F97, false, &lv_font_montserrat_16);
      drawKeyRow(symRightRow2, 5, 20, row2Y, keyW5, keyH, gap, 0x2A6F97, false, &lv_font_montserrat_16);
    }
  }

  makeKeyboardButton(gKeyboardMode == KEYBOARD_MODE_ALPHA ? "123" : "ABC", "<MODE>", 20, row3Y, 88, 64, 0x5C6F82, &lv_font_montserrat_18);
  makeKeyboardButton(gKeyboardShift ? "SHIFT*" : "SHIFT", "<SHIFT>", 116, row3Y, 88, 64, 0x7A5C9B, &lv_font_montserrat_16);
  makeKeyboardButton("DEL", "<DEL>", 212, row3Y, 76, 64, 0x7D3A3A, &lv_font_montserrat_18);
  makeKeyboardButton("SAVE", "<SAVE>", 296, row3Y, 76, 64, 0x2A9D8F, &lv_font_montserrat_18);
  makeKeyboardButton("CANCEL", "<CANCEL>", 380, row3Y, 80, 64, 0x5A6570, &lv_font_montserrat_16);
}

static void drawTextEditScreen() {
  setRootStyle();
  gInputTextArea = nullptr;

  makeTitle(gEditTitle.c_str(), 8, &lv_font_montserrat_24);

  gInputTextArea = lv_textarea_create(gRoot);
  lv_obj_set_size(gInputTextArea, 436, 58);
  lv_obj_set_pos(gInputTextArea, 22, 48);
  lv_textarea_set_one_line(gInputTextArea, true);
  lv_textarea_set_text(gInputTextArea, gEditValue.c_str());
  lv_textarea_set_cursor_pos(gInputTextArea, LV_TEXTAREA_CURSOR_LAST);
  lv_textarea_set_password_mode(gInputTextArea, false);
  lv_textarea_set_cursor_click_pos(gInputTextArea, false);
  lv_textarea_set_text_selection(gInputTextArea, false);
  lv_obj_set_style_text_font(gInputTextArea, &lv_font_montserrat_18, 0);
  lv_obj_set_style_bg_color(gInputTextArea, lv_color_hex(0x132131), 0);
  lv_obj_set_style_text_color(gInputTextArea, lv_color_hex(0xFFFFFF), 0);
  lv_obj_set_style_border_color(gInputTextArea, lv_color_hex(0x6E8AA3), 0);
  lv_obj_set_style_border_width(gInputTextArea, 2, 0);
  lv_obj_set_style_bg_opa(gInputTextArea, LV_OPA_TRANSP, LV_PART_CURSOR);
  lv_obj_set_style_border_opa(gInputTextArea, LV_OPA_TRANSP, LV_PART_CURSOR);
  lv_obj_set_style_outline_opa(gInputTextArea, LV_OPA_TRANSP, LV_PART_CURSOR);
  lv_obj_set_style_pad_left(gInputTextArea, 12, 0);
  lv_obj_set_style_pad_right(gInputTextArea, 12, 0);
  lv_obj_add_state(gInputTextArea, LV_STATE_FOCUSED);
  restoreTextareaFromEditValue();

  lv_obj_t *panel = lv_obj_create(gRoot);
  lv_obj_set_size(panel, TEXT_EDIT_PANEL_W, TEXT_EDIT_PANEL_H);
  lv_obj_set_pos(panel, TEXT_EDIT_PANEL_X, TEXT_EDIT_PANEL_Y);
  lv_obj_set_style_radius(panel, 16, 0);
  lv_obj_set_style_bg_color(panel, lv_color_hex(0x0F1A27), 0);
  lv_obj_set_style_bg_opa(panel, LV_OPA_COVER, 0);
  lv_obj_set_style_border_width(panel, 1, 0);
  lv_obj_set_style_border_color(panel, lv_color_hex(0x2E455A), 0);
  lv_obj_clear_flag(panel, LV_OBJ_FLAG_SCROLLABLE);

  drawTextEditorKeyboard(TEXT_EDIT_PANEL_Y + 8);

  makeVersionTag();
}

static void rebuildScreen() {
  if (!gRoot) {
    gRoot = lv_scr_act();
  }

  releaseTransientUiBuffers();
  lv_obj_clean(gRoot);

  switch (gCurrentScreen) {
    case SCREEN_HOME:
      drawHome();
      break;
    case SCREEN_WALLET:
      drawWalletScreen();
      break;
    case SCREEN_WALLET_SELECT:
      drawWalletSelectScreen();
      break;
    case SCREEN_WALLET_QR:
      drawWalletQrScreen();
      break;
    case SCREEN_WALLET_SIGN_REQUEST:
      drawWalletSignRequestScreen();
      break;
    case SCREEN_SETTINGS_MENU:
      drawSettingsMenu();
      break;
    case SCREEN_PAIRING_REQUESTS:
      drawPairingRequestsScreen();
      break;
    case SCREEN_PAIRING_REQUEST_DETAIL:
      drawPairingRequestDetailScreen();
      break;
    case SCREEN_WIFI:
      drawWifiScreen();
      break;
    case SCREEN_SERVER:
      drawServerScreen();
      break;
    case SCREEN_ACCOUNT:
      drawAccountScreen();
      break;
    case SCREEN_ACCOUNT_HOMESERVER:
      drawAccountHomeserverScreen();
      break;
    case SCREEN_ACCOUNT_SECRET:
      drawAccountSecretScreen();
      break;
    case SCREEN_SECRET_SHOW:
      drawSecretShowScreen();
      break;
    case SCREEN_SECRET_GENERATE_INFO:
      drawSecretGenerateInfoScreen();
      break;
    case SCREEN_SECRET_GENERATE_RUNNING:
      drawSecretGenerateRunningScreen();
      break;
    case SCREEN_SECRET_GENERATE_CANCEL_CONFIRM:
      drawSecretGenerateCancelConfirmScreen();
      break;
    case SCREEN_TEXT_EDIT:
      drawTextEditScreen();
      break;
    case SCREEN_REGISTER_ACCOUNT_CONFIRM:
      drawRegisterAccountConfirmScreen();
      break;
    case SCREEN_REGISTER_ACCOUNT_RESULT:
      drawRegisterAccountResultScreen();
      break;
    case SCREEN_HOMESERVER_PDA_CONFIRM:
      drawHomeserverPdaConfirmScreen();
      break;
    case SCREEN_HOMESERVER_PDA_RESULT:
      drawHomeserverPdaResultScreen();
      break;
  }
}

static void showScreen(Screen screen) {
  gCurrentScreen = screen;
  rebuildScreen();
}

static void handleHomeSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_LEFT) {
    showScreen(SCREEN_SETTINGS_MENU);
  }
}

static void handleWalletSwipe(SwipeDirection swipe) {
  if (gCurrentScreen == SCREEN_WALLET_SIGN_REQUEST && gActiveWalletSignRequest.active) {
    return;
  }
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_HOME);
  }
}

static void handleSettingsSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_HOME);
    return;
  }

  if (swipe == SWIPE_UP) {
    gSettingsScrollIndex++;
    if (gSettingsScrollIndex > settingsMenuCount() - 2) {
      gSettingsScrollIndex = settingsMenuCount() - 2;
    }
    rebuildScreen();
    return;
  }

  if (swipe == SWIPE_DOWN) {
    gSettingsScrollIndex--;
    if (gSettingsScrollIndex < 0) {
      gSettingsScrollIndex = 0;
    }
    rebuildScreen();
  }
}

static void handleWifiSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    gWifiViewMode = WIFI_VIEW_OVERVIEW;
    showScreen(SCREEN_SETTINGS_MENU);
  }
}

static void handlePairingRequestsSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_SETTINGS_MENU);
  }
}

static void handlePairingRequestDetailSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_PAIRING_REQUESTS);
  }
}

static void handleServerSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_SETTINGS_MENU);
  }
}

static void handleAccountSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_SETTINGS_MENU);
  }
}

static void handleAccountSubscreenSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_ACCOUNT);
  }
}

static void handleSecretSubscreenSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_RIGHT) {
    showScreen(SCREEN_ACCOUNT_SECRET);
  }
}

static void handleTextEditSwipe(SwipeDirection swipe) {
  if (!isTextEditKeyboardSwipeArea(gTouchStartX, gTouchStartY)) {
    return;
  }
  syncEditValueFromTextarea();
  if (swipe == SWIPE_LEFT) {
    gKeyboardPage = min(gKeyboardPage + 1, 1);
    rebuildScreen();
    return;
  }
  if (swipe == SWIPE_RIGHT) {
    gKeyboardPage = max(gKeyboardPage - 1, 0);
    rebuildScreen();
  }
}

static bool isTextEditKeyboardSwipeArea(int16_t x, int16_t y) {
  return x >= TEXT_EDIT_PANEL_X && x <= (TEXT_EDIT_PANEL_X + TEXT_EDIT_PANEL_W) &&
         y >= TEXT_EDIT_PANEL_Y && y <= (TEXT_EDIT_PANEL_Y + TEXT_EDIT_PANEL_H);
}

static void handleSwipe(SwipeDirection swipe) {
  if (swipe == SWIPE_NONE) {
    return;
  }

  switch (gCurrentScreen) {
    case SCREEN_HOME:
      handleHomeSwipe(swipe);
      break;
    case SCREEN_WALLET:
    case SCREEN_WALLET_SELECT:
    case SCREEN_WALLET_QR:
    case SCREEN_WALLET_SIGN_REQUEST:
      handleWalletSwipe(swipe);
      break;
    case SCREEN_SETTINGS_MENU:
      handleSettingsSwipe(swipe);
      break;
    case SCREEN_PAIRING_REQUESTS:
      handlePairingRequestsSwipe(swipe);
      break;
    case SCREEN_PAIRING_REQUEST_DETAIL:
      handlePairingRequestDetailSwipe(swipe);
      break;
    case SCREEN_WIFI:
      handleWifiSwipe(swipe);
      break;
    case SCREEN_SERVER:
      handleServerSwipe(swipe);
      break;
    case SCREEN_ACCOUNT:
      handleAccountSwipe(swipe);
      break;
    case SCREEN_ACCOUNT_HOMESERVER:
    case SCREEN_ACCOUNT_SECRET:
      handleAccountSubscreenSwipe(swipe);
      break;
    case SCREEN_SECRET_SHOW:
    case SCREEN_SECRET_GENERATE_INFO:
    case SCREEN_SECRET_GENERATE_RUNNING:
    case SCREEN_SECRET_GENERATE_CANCEL_CONFIRM:
      handleSecretSubscreenSwipe(swipe);
      break;
    case SCREEN_TEXT_EDIT:
      handleTextEditSwipe(swipe);
      break;
    case SCREEN_REGISTER_ACCOUNT_CONFIRM:
    case SCREEN_REGISTER_ACCOUNT_RESULT:
    case SCREEN_HOMESERVER_PDA_CONFIRM:
    case SCREEN_HOMESERVER_PDA_RESULT:
      handleHomeSwipe(swipe);
      break;
  }
}

void setup() {
  Serial.begin(115200);
  sodium_init();
  Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
  initPowerManagement();

  gfx->begin();
  gBus->writeC8D8(0x36, 0xA0);
  gfx->setBrightness(220);
  gfx->fillScreen(0x0000);

  gTouch.setPins(PIN_TP_INT, -1);
  gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
  gTouch.setMaxCoordinates(DISP_W, DISP_H);
  gTouch.setSwapXY(true);
  gTouch.setMirrorXY(true, false);

  gPrefs.begin("shine-nav-ui", false);
  loadPrefs();
  beginSavedWifi();
  gLastWifiStatus = WiFi.status();

  lv_init();

  uint32_t screenWidth = gfx->width();
  uint32_t screenHeight = gfx->height();
  uint32_t bufPixels = screenWidth * 40;
  gBuf1 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
  gBuf2 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
  lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, bufPixels);

  static lv_disp_drv_t dispDrv;
  lv_disp_drv_init(&dispDrv);
  dispDrv.hor_res = screenWidth;
  dispDrv.ver_res = screenHeight;
  dispDrv.flush_cb = lvglFlushCb;
  dispDrv.draw_buf = &gDrawBuf;
  lv_disp_drv_register(&dispDrv);

  static lv_indev_drv_t indevDrv;
  lv_indev_drv_init(&indevDrv);
  indevDrv.type = LV_INDEV_TYPE_POINTER;
  indevDrv.read_cb = lvglTouchRead;
  lv_indev_drv_register(&indevDrv);

  const esp_timer_create_args_t tickArgs = {
      .callback = &lvglTick,
      .name = "lvgl_tick"};
  esp_timer_handle_t tickTimer = nullptr;
  esp_timer_create(&tickArgs, &tickTimer);
  esp_timer_start_periodic(tickTimer, LVGL_TICK_MS * 1000);

  rebuildScreen();
  Serial.println("Minimal nav test ready");
  Serial.println("USB diag commands: last_error, last_diag, reg_diag, clear_error, help");
}

void loop() {
  handleUsbSerialCommands();
  lv_timer_handler();
  if (gWalletQrTapReturnPending) {
    gWalletQrTapReturnPending = false;
    showScreen(SCREEN_WALLET);
  }
  manageWifiReconnect();
  manageAccountPdaRefresh();
  manageShineConnection();

  if (gBalanceAutoRefreshPending && gSecretConfigured && WiFi.status() == WL_CONNECTED) {
    unsigned long now = millis();
    if (gLastBalanceAutoRefreshAttemptMs == 0 || now - gLastBalanceAutoRefreshAttemptMs >= 15000) {
      gLastBalanceAutoRefreshAttemptMs = now;
      String message;
      if (refreshWalletBalance(message)) {
        gBalanceAutoRefreshPending = false;
      }
      if (gCurrentScreen == SCREEN_HOME) {
        rebuildScreen();
      }
    }
  }

  static unsigned long lastHomeRefreshMs = 0;
  if (gCurrentScreen == SCREEN_HOME && !gTouchDown && millis() - lastHomeRefreshMs >= HOME_REFRESH_MS) {
    lastHomeRefreshMs = millis();
    rebuildScreen();
  }

  if (gCurrentScreen == SCREEN_SECRET_GENERATE_RUNNING) {
    ShineSecretGenerationStatus status = shineSecretStatus();
    if (status.running) {
      shineSecretStep(4);
      static unsigned long lastSecretUiMs = 0;
      if (millis() - lastSecretUiMs >= 500) {
        lastSecretUiMs = millis();
        rebuildScreen();
      }
    } else if (status.done) {
      setSecretValue(shineSecretBytes());
      gAccountStatusMessage = "Secret generated";
      showScreen(SCREEN_SECRET_SHOW);
    }
  }

  if (gPendingSwipe != SWIPE_NONE) {
    SwipeDirection swipe = gPendingSwipe;
    gPendingSwipe = SWIPE_NONE;
    handleSwipe(swipe);
  }

  delay(5);
}
