/**
 * Voice Recorder App for Tactility OS
 *
 * Records voice memos (16kHz 16-bit Mono WAV) to /sdcard/memos/
 * Uses audio-stream API with resampling (native codec 44100 -> app 16000)
 */
#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>

#include <tactility/device.h>
#include <tactility/drivers/audio_stream.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"

#define TAG "VoiceRecorder"

#define SAMPLE_RATE      16000
#define BITS_PER_SAMPLE  16
#define CHUNK_SAMPLES    512
#define CHUNK_BYTES      (CHUNK_SAMPLES * (BITS_PER_SAMPLE / 8)) // 1024 bytes
#define AUDIO_BUF_SIZE   4096

#define MAX_MEMOS        50
#define MAX_FILENAME_LEN 64

typedef enum {
    STATE_IDLE,
    STATE_RECORDING,
    STATE_PLAYING,
    STATE_PAUSED
} AudioState;

typedef struct {
    struct Device* stream_dev;
    AudioStreamHandle input_handle;
    AudioStreamHandle output_handle;
    uint8_t*       audio_buf;
    AudioState     state;
    int            volume;

    // Memo directory listing
    char           memos[MAX_MEMOS][MAX_FILENAME_LEN];
    int            memo_count;
    int            selected_index;

    // UI elements
    lv_obj_t*      lbl_status;
    lv_obj_t*      bar_progress;
    lv_obj_t*      lst_memos;
    lv_obj_t*      btn_record;
    lv_obj_t*      btn_play_pause;
    lv_obj_t*      btn_stop;
    lv_obj_t*      btn_delete;

    TaskHandle_t   task_handle;
} AppCtx;

typedef struct __attribute__((packed)) {
    char riff[4];
    uint32_t overall_size;
    char wave[4];
    char fmt_chunk_marker[4];
    uint32_t length_of_fmt;
    uint16_t format_type;
    uint16_t channels;
    uint32_t sample_rate;
    uint32_t byterate;
    uint16_t block_align;
    uint16_t bits_per_sample;
    char data_chunk_header[4];
    uint32_t data_size;
} WavHeader;

static AppCtx g_ctx;

/* ─── Forward Decls ─── */
static void update_ui(AppCtx* ctx);
static void refresh_memo_list(AppCtx* ctx);
static void on_memo_selected(lv_event_t* e);

static bool find_audio_stream_device(AppCtx* ctx) {
    struct Device* dev = device_find_by_name("audio-stream");
    if (dev) {
        ctx->stream_dev = dev;
        return true;
    }
    dev = device_find_first_by_type(&AUDIO_STREAM_TYPE);
    if (dev) {
        ctx->stream_dev = dev;
        return true;
    }
    return false;
}

/* ─── WAV Header Writer ─── */
static void write_wav_header(FILE* f, uint32_t sample_rate, uint16_t bits_per_sample, uint16_t channels, uint32_t data_size) {
    WavHeader header;
    memcpy(header.riff, "RIFF", 4);
    header.overall_size = 36 + data_size;
    memcpy(header.wave, "WAVE", 4);
    memcpy(header.fmt_chunk_marker, "fmt ", 4);
    header.length_of_fmt = 16;
    header.format_type = 1; // PCM
    header.channels = channels;
    header.sample_rate = sample_rate;
    header.byterate = sample_rate * channels * (bits_per_sample / 8);
    header.block_align = channels * (bits_per_sample / 8);
    header.bits_per_sample = bits_per_sample;
    memcpy(header.data_chunk_header, "data", 4);
    header.data_size = data_size;

    fwrite(&header, 1, sizeof(WavHeader), f);
}

/* ─── Next Filename Finder ─── */
static void get_next_memo_filename(char* out_filename, size_t max_len) {
    char datetime_buf[32];
    time_t rawtime = time(NULL);
    struct tm timeinfo;
    localtime_r(&rawtime, &timeinfo);

    strftime(datetime_buf, sizeof(datetime_buf), "%Y%m%d_%H%M%S", &timeinfo);

    snprintf(out_filename, max_len, "memo_%s.wav", datetime_buf);

    char filepath[256];
    snprintf(filepath, sizeof(filepath), "/sdcard/memos/%s", out_filename);

    struct stat st;
    if (stat(filepath, &st) != 0) {
        return;
    }

    int suffix = 1;
    while (1) {
        snprintf(out_filename, max_len, "memo_%s_%d.wav", datetime_buf, suffix);
        snprintf(filepath, sizeof(filepath), "/sdcard/memos/%s", out_filename);
        if (stat(filepath, &st) != 0) {
            return;
        }
        suffix++;
    }
}

/* ─── Record Task (audio-stream input, resampled to 16k mono) ─── */
static void record_task(void* arg) {
    AppCtx* ctx = (AppCtx*)arg;
    char filepath[256];
    char filename[64];

    get_next_memo_filename(filename, sizeof(filename));
    snprintf(filepath, sizeof(filepath), "/sdcard/memos/%s", filename);

    FILE* f = fopen(filepath, "wb");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for recording: %s", filepath);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: Cannot write file");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    write_wav_header(f, SAMPLE_RATE, BITS_PER_SAMPLE, 1, 0);

    // Open input stream via audio-stream (resampler provides 16k mono regardless of codec native rate)
    struct AudioStreamConfig in_cfg = {
        .sample_rate = SAMPLE_RATE,
        .bits_per_sample = BITS_PER_SAMPLE,
        .channels = 1
    };

    error_t err = audio_stream_open_input(ctx->stream_dev, &in_cfg, &ctx->input_handle);
    if (err == ERROR_NONE) {
        // Ensure mic is unmuted and at max gain (ES8311 0..24dB)
        audio_stream_set_mute(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, false);
        audio_stream_set_volume(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, 100.0f);
        ESP_LOGI(TAG, "Mic unmuted, gain 100%%");
    }
    if (err != ERROR_NONE) {
        ESP_LOGE(TAG, "audio_stream_open_input failed: %d", err);
        fclose(f);
        unlink(filepath);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: Mic Config Failed");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    ESP_LOGI(TAG, "Recording started -> %s (via audio-stream %u Hz)", filepath, (unsigned)SAMPLE_RATE);

    size_t total_written = 0;
    uint32_t start_time = xTaskGetTickCount();

    while (ctx->state == STATE_RECORDING) {
        size_t bytes_read = 0;
        err = audio_stream_read(ctx->input_handle, ctx->audio_buf, AUDIO_BUF_SIZE, &bytes_read, pdMS_TO_TICKS(200));
        if (err == ERROR_NONE && bytes_read > 0) {
            // Data already 16k mono from audio-stream resampler, no downmix needed
            size_t written = fwrite(ctx->audio_buf, 1, bytes_read, f);
            if (written != bytes_read) {
                ESP_LOGE(TAG, "SD write error: wrote %d of %d", (int)written, (int)bytes_read);
                break;
            }
            total_written += written;
        }

        uint32_t elapsed_sec = (xTaskGetTickCount() - start_time) / configTICK_RATE_HZ;
        char status_buf[64];
        snprintf(status_buf, sizeof(status_buf), "🔴 Recording... %02u:%02u", (unsigned)(elapsed_sec / 60), (unsigned)(elapsed_sec % 60));

        tt_lvgl_lock(portMAX_DELAY);
        lv_label_set_text(ctx->lbl_status, status_buf);
        lv_bar_set_value(ctx->bar_progress, (int)((elapsed_sec * 100 / 300)) % 100, LV_ANIM_OFF);
        tt_lvgl_unlock();
    }

    audio_stream_close(ctx->input_handle);
    ctx->input_handle = NULL;

    fseek(f, 0, SEEK_SET);
    write_wav_header(f, SAMPLE_RATE, BITS_PER_SAMPLE, 1, total_written);
    fclose(f);

    ESP_LOGI(TAG, "Recording finished: %u bytes", (unsigned)total_written);

    tt_lvgl_lock(portMAX_DELAY);
    ctx->state = STATE_IDLE;
    refresh_memo_list(ctx);

    ctx->selected_index = -1;
    for (int i = 0; i < ctx->memo_count; i++) {
        if (strcmp(ctx->memos[i], filename) == 0) {
            ctx->selected_index = i;
            break;
        }
    }

    update_ui(ctx);
    tt_lvgl_unlock();

    ctx->task_handle = NULL;
    vTaskDelete(NULL);
}

/* ─── Playback Task (audio-stream output with resampling) ─── */
static void play_task(void* arg) {
    AppCtx* ctx = (AppCtx*)arg;
    if (ctx->selected_index < 0 || ctx->selected_index >= ctx->memo_count) {
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    char filepath[256];
    snprintf(filepath, sizeof(filepath), "/sdcard/memos/%s", ctx->memos[ctx->selected_index]);

    FILE* f = fopen(filepath, "rb");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for playback: %s", filepath);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: File not found");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    WavHeader header;
    if (fread(&header, 1, sizeof(WavHeader), f) != sizeof(WavHeader)) {
        ESP_LOGE(TAG, "Failed to read WAV header");
        fclose(f);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: Invalid WAV Header");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    if (memcmp(header.riff, "RIFF", 4) != 0 || memcmp(header.wave, "WAVE", 4) != 0) {
        ESP_LOGE(TAG, "Invalid WAV format");
        fclose(f);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: Unsupported WAV");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    /* Open output stream via audio-stream (resampler converts file rate -> native 44100) */
    struct AudioStreamConfig out_cfg = {
        .sample_rate = header.sample_rate,
        .bits_per_sample = header.bits_per_sample,
        .channels = header.channels
    };

    error_t err = audio_stream_open_output(ctx->stream_dev, &out_cfg, &ctx->output_handle);
    if (err != ERROR_NONE) {
        ESP_LOGE(TAG, "audio_stream_open_output failed for playback: %d (rate=%u)", err, (unsigned)header.sample_rate);
        fclose(f);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: Audio Setup Failed");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }

    ESP_LOGI(TAG, "Playing via audio-stream: %s, rate=%u Hz, ch=%u, size=%u",
             filepath, (unsigned)header.sample_rate, header.channels, (unsigned)header.data_size);

    size_t total_played = 0;
    size_t data_size = header.data_size;
    if (data_size == 0) {
        fseek(f, 0, SEEK_END);
        data_size = ftell(f) - sizeof(WavHeader);
        fseek(f, sizeof(WavHeader), SEEK_SET);
    }

    bool out_open = true;

    while (total_played < data_size && ctx->state != STATE_IDLE) {
        if (ctx->state == STATE_PAUSED) {
            if (out_open) {
                audio_stream_close(ctx->output_handle);
                ctx->output_handle = NULL;
                out_open = false;
            }
            vTaskDelay(pdMS_TO_TICKS(50));
            continue;
        }

        if (!out_open) {
            err = audio_stream_open_output(ctx->stream_dev, &out_cfg, &ctx->output_handle);
            if (err != ERROR_NONE) {
                ESP_LOGE(TAG, "Failed to reopen audio_stream on resume: %d", err);
                break;
            }
            out_open = true;
        }

        size_t to_read = (data_size - total_played < CHUNK_BYTES) ? (data_size - total_played) : CHUNK_BYTES;
        size_t read_bytes = fread(ctx->audio_buf, 1, to_read, f);
        if (read_bytes == 0) {
            break;
        }

        // Volume scaling
        int vol = ctx->volume;
        int16_t* samples_ptr = (int16_t*)ctx->audio_buf;
        size_t sample_count = read_bytes / sizeof(int16_t);
        for (size_t i = 0; i < sample_count; ++i) {
            int32_t scaled = (int32_t)samples_ptr[i] * vol / 100;
            samples_ptr[i] = (int16_t)scaled;
        }

        size_t offset = 0;
        bool write_err = false;
        while (offset < read_bytes && ctx->state == STATE_PLAYING) {
            size_t written = 0;
            err = audio_stream_write(ctx->output_handle, ctx->audio_buf + offset, read_bytes - offset, &written, pdMS_TO_TICKS(500));
            if (err != ERROR_NONE || written == 0) {
                ESP_LOGE(TAG, "audio_stream write error: %d", err);
                write_err = true;
                break;
            }
            offset += written;
        }

        if (write_err) break;

        total_played += read_bytes;

        int pct = (int)((total_played * 100) / data_size);
        uint32_t bytes_per_sec = header.sample_rate * header.channels * (header.bits_per_sample / 8);
        uint32_t elapsed_sec = total_played / bytes_per_sec;
        uint32_t total_sec = data_size / bytes_per_sec;

        char status_buf[64];
        snprintf(status_buf, sizeof(status_buf), "🔊 Playing... %02u:%02u / %02u:%02u",
                 (unsigned)(elapsed_sec / 60), (unsigned)(elapsed_sec % 60),
                 (unsigned)(total_sec / 60), (unsigned)(total_sec % 60));

        tt_lvgl_lock(portMAX_DELAY);
        lv_label_set_text(ctx->lbl_status, status_buf);
        lv_bar_set_value(ctx->bar_progress, pct, LV_ANIM_OFF);
        tt_lvgl_unlock();
    }

    fclose(f);
    ESP_LOGI(TAG, "Playback task complete");

    if (out_open && ctx->output_handle) {
        audio_stream_close(ctx->output_handle);
        ctx->output_handle = NULL;
    }

    tt_lvgl_lock(portMAX_DELAY);
    ctx->state = STATE_IDLE;
    update_ui(ctx);
    tt_lvgl_unlock();

    ctx->task_handle = NULL;
    vTaskDelete(NULL);
}

/* ─── Callbacks ─── */
static void on_record_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->state != STATE_IDLE) return;
    if (ctx->stream_dev == NULL) return;

    ctx->state = STATE_RECORDING;
    update_ui(ctx);

    xTaskCreate(record_task, "voice_rec", 8192, ctx, 5, &ctx->task_handle);
}

static void on_play_pause_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->selected_index < 0) return;

    if (ctx->state == STATE_IDLE) {
        ctx->state = STATE_PLAYING;
        update_ui(ctx);
        xTaskCreate(play_task, "voice_play", 8192, ctx, 5, &ctx->task_handle);
    } else if (ctx->state == STATE_PLAYING) {
        ctx->state = STATE_PAUSED;
        update_ui(ctx);
    } else if (ctx->state == STATE_PAUSED) {
        ctx->state = STATE_PLAYING;
        update_ui(ctx);
    }
}

static void on_stop_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->state == STATE_IDLE) return;

    ctx->state = STATE_IDLE;
    update_ui(ctx);
}

static void on_delete_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->state != STATE_IDLE) return;
    if (ctx->selected_index < 0 || ctx->selected_index >= ctx->memo_count) return;

    char filepath[256];
    snprintf(filepath, sizeof(filepath), "/sdcard/memos/%s", ctx->memos[ctx->selected_index]);

    ESP_LOGI(TAG, "Deleting: %s", filepath);
    unlink(filepath);

    ctx->selected_index = -1;
    refresh_memo_list(ctx);
    update_ui(ctx);
}

static void on_memo_selected(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    lv_obj_t* btn = lv_event_get_target(e);

    uint32_t child_cnt = lv_obj_get_child_cnt(ctx->lst_memos);
    for (uint32_t i = 0; i < child_cnt; i++) {
        lv_obj_t* child = lv_obj_get_child(ctx->lst_memos, i);
        lv_obj_clear_state(child, LV_STATE_CHECKED);
    }

    lv_obj_add_state(btn, LV_STATE_CHECKED);

    const char* text = lv_list_get_btn_text(ctx->lst_memos, btn);
    for (int i = 0; i < ctx->memo_count; i++) {
        if (strcmp(ctx->memos[i], text) == 0) {
            ctx->selected_index = i;
            break;
        }
    }

    update_ui(ctx);
}

/* ─── UI Refresh & Sync ─── */
static void refresh_memo_list(AppCtx* ctx) {
    ctx->memo_count = 0;
    lv_obj_clean(ctx->lst_memos);

    DIR* dir = opendir("/sdcard/memos");
    if (dir == NULL) {
        ESP_LOGE(TAG, "Failed to open folder /sdcard/memos");
        return;
    }

    struct dirent* entry;
    while ((entry = readdir(dir)) != NULL && ctx->memo_count < MAX_MEMOS) {
        if (entry->d_name[0] == '.') continue;

        size_t len = strlen(entry->d_name);
        if (len > 4 && strcasecmp(entry->d_name + len - 4, ".wav") == 0) {
            strncpy(ctx->memos[ctx->memo_count], entry->d_name, MAX_FILENAME_LEN - 1);
            ctx->memos[ctx->memo_count][MAX_FILENAME_LEN - 1] = '\0';
            ctx->memo_count++;
        }
    }
    closedir(dir);

    for (int i = 0; i < ctx->memo_count - 1; i++) {
        for (int j = 0; j < ctx->memo_count - i - 1; j++) {
            if (strcmp(ctx->memos[j], ctx->memos[j + 1]) > 0) {
                char temp[MAX_FILENAME_LEN];
                strcpy(temp, ctx->memos[j]);
                strcpy(ctx->memos[j], ctx->memos[j + 1]);
                strcpy(ctx->memos[j + 1], temp);
            }
        }
    }

    for (int i = 0; i < ctx->memo_count; i++) {
        lv_obj_t* btn = lv_list_add_btn(ctx->lst_memos, LV_SYMBOL_AUDIO, ctx->memos[i]);
        lv_obj_add_event_cb(btn, on_memo_selected, LV_EVENT_CLICKED, ctx);
        if (i == ctx->selected_index) {
            lv_obj_add_state(btn, LV_STATE_CHECKED);
        }
    }
}

static void update_ui(AppCtx* ctx) {
    if (ctx->lbl_status == NULL) return;

    switch (ctx->state) {
        case STATE_RECORDING:
            lv_obj_add_state(ctx->btn_record, LV_STATE_DISABLED);
            lv_obj_add_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED);
            lv_obj_add_state(ctx->btn_delete, LV_STATE_DISABLED);
            break;

        case STATE_PLAYING:
            lv_obj_add_state(ctx->btn_record, LV_STATE_DISABLED);
            lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PAUSE);
            lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED);
            lv_obj_add_state(ctx->btn_delete, LV_STATE_DISABLED);
            break;

        case STATE_PAUSED:
            lv_obj_add_state(ctx->btn_record, LV_STATE_DISABLED);
            lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY);
            lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED);
            lv_obj_add_state(ctx->btn_delete, LV_STATE_DISABLED);
            break;

        case STATE_IDLE:
        default:
            lv_obj_clear_state(ctx->btn_record, LV_STATE_DISABLED);

            if (ctx->selected_index >= 0 && ctx->selected_index < ctx->memo_count) {
                lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
                lv_obj_clear_state(ctx->btn_delete, LV_STATE_DISABLED);

                char status_buf[128];
                snprintf(status_buf, sizeof(status_buf), "Selected: %s", ctx->memos[ctx->selected_index]);
                lv_label_set_text(ctx->lbl_status, status_buf);
            } else {
                lv_obj_add_state(ctx->btn_play_pause, LV_STATE_DISABLED);
                lv_obj_add_state(ctx->btn_delete, LV_STATE_DISABLED);
                lv_label_set_text(ctx->lbl_status, "Select a memo or press Rec");
            }

            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY);
            lv_obj_add_state(ctx->btn_stop, LV_STATE_DISABLED);
            lv_bar_set_value(ctx->bar_progress, 0, LV_ANIM_OFF);
            break;
    }
}

/* ─── App Lifecycle ─── */
static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
    memset(&g_ctx, 0, sizeof(g_ctx));
    g_ctx.volume = 80;
    g_ctx.selected_index = -1;

    mkdir("/sdcard/memos", 0755);

    g_ctx.audio_buf = (uint8_t*)malloc(AUDIO_BUF_SIZE);
    if (g_ctx.audio_buf == NULL) {
        ESP_LOGE(TAG, "Failed to allocate audio buffer");
    }

    if (!find_audio_stream_device(&g_ctx)) {
        ESP_LOGE(TAG, "audio-stream device not found!");
    }

    lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
    lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);

    lv_obj_t* card = lv_obj_create(parent);
    lv_obj_set_size(card, lv_pct(95), lv_pct(88));
    lv_obj_align(card, LV_ALIGN_CENTER, 0, 12);
    lv_obj_set_style_radius(card, 15, 0);
    lv_obj_set_style_bg_color(card, lv_color_hex(0x1E1E2E), 0);
    lv_obj_set_style_border_color(card, lv_color_hex(0x313244), 0);
    lv_obj_set_style_border_width(card, 2, 0);
    lv_obj_set_flex_flow(card, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(card, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_all(card, 10, 0);
    lv_obj_set_style_pad_gap(card, 8, 0);

    g_ctx.lbl_status = lv_label_create(card);
    lv_obj_set_width(g_ctx.lbl_status, lv_pct(95));
    lv_obj_set_style_text_align(g_ctx.lbl_status, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_style_text_color(g_ctx.lbl_status, lv_color_hex(0xCDD6F4), 0);
    lv_label_set_text(g_ctx.lbl_status, "Scanning memos...");

    g_ctx.bar_progress = lv_bar_create(card);
    lv_obj_set_size(g_ctx.bar_progress, lv_pct(90), 8);
    lv_bar_set_range(g_ctx.bar_progress, 0, 100);
    lv_bar_set_value(g_ctx.bar_progress, 0, LV_ANIM_OFF);
    lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x45475A), LV_PART_MAIN);
    lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x89B4FA), LV_PART_INDICATOR);

    g_ctx.lst_memos = lv_list_create(card);
    lv_obj_set_size(g_ctx.lst_memos, lv_pct(95), 85);
    lv_obj_set_style_bg_color(g_ctx.lst_memos, lv_color_hex(0x181825), 0);
    lv_obj_set_style_border_color(g_ctx.lst_memos, lv_color_hex(0x313244), 0);
    lv_obj_set_style_border_width(g_ctx.lst_memos, 1, 0);
    lv_obj_set_style_radius(g_ctx.lst_memos, 8, 0);

    lv_obj_t* ctrl_box = lv_obj_create(card);
    lv_obj_remove_style_all(ctrl_box);
    lv_obj_set_size(ctrl_box, lv_pct(95), 40);
    lv_obj_set_flex_flow(ctrl_box, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(ctrl_box, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);

    g_ctx.btn_record = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_record, 45, 32);
    lv_obj_set_style_radius(g_ctx.btn_record, 8, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_record, lv_color_hex(0xF38BA8), 0);
    lv_obj_set_style_text_color(g_ctx.btn_record, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_rec = lv_label_create(g_ctx.btn_record);
    lv_label_set_text(lbl_rec, LV_SYMBOL_AUDIO);
    lv_obj_center(lbl_rec);
    lv_obj_add_event_cb(g_ctx.btn_record, on_record_click, LV_EVENT_CLICKED, &g_ctx);

    g_ctx.btn_play_pause = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_play_pause, 45, 32);
    lv_obj_set_style_radius(g_ctx.btn_play_pause, 8, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_play_pause, lv_color_hex(0x89B4FA), 0);
    lv_obj_set_style_text_color(g_ctx.btn_play_pause, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_play = lv_label_create(g_ctx.btn_play_pause);
    lv_label_set_text(lbl_play, LV_SYMBOL_PLAY);
    lv_obj_center(lbl_play);
    lv_obj_add_event_cb(g_ctx.btn_play_pause, on_play_pause_click, LV_EVENT_CLICKED, &g_ctx);

    g_ctx.btn_stop = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_stop, 45, 32);
    lv_obj_set_style_radius(g_ctx.btn_stop, 8, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_stop, lv_color_hex(0xBAC2DE), 0);
    lv_obj_set_style_text_color(g_ctx.btn_stop, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_stop = lv_label_create(g_ctx.btn_stop);
    lv_label_set_text(lbl_stop, LV_SYMBOL_STOP);
    lv_obj_center(lbl_stop);
    lv_obj_add_event_cb(g_ctx.btn_stop, on_stop_click, LV_EVENT_CLICKED, &g_ctx);

    g_ctx.btn_delete = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_delete, 45, 32);
    lv_obj_set_style_radius(g_ctx.btn_delete, 8, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_delete, lv_color_hex(0x74C7EC), 0);
    lv_obj_set_style_text_color(g_ctx.btn_delete, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_del = lv_label_create(g_ctx.btn_delete);
    lv_label_set_text(lbl_del, LV_SYMBOL_TRASH);
    lv_obj_center(lbl_del);
    lv_obj_add_event_cb(g_ctx.btn_delete, on_delete_click, LV_EVENT_CLICKED, &g_ctx);

    if (g_ctx.stream_dev == NULL) {
        lv_label_set_text(g_ctx.lbl_status, "ERROR: audio-stream missing");
        lv_obj_add_state(g_ctx.btn_record, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_delete, LV_STATE_DISABLED);
    } else if (g_ctx.audio_buf == NULL) {
        lv_label_set_text(g_ctx.lbl_status, "ERROR: Out of Memory");
        lv_obj_add_state(g_ctx.btn_record, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_delete, LV_STATE_DISABLED);
    } else {
        g_ctx.state = STATE_IDLE;
        refresh_memo_list(&g_ctx);
        update_ui(&g_ctx);
    }
}

static void onHideApp(AppHandle app, void* data) {
    if (g_ctx.state != STATE_IDLE) {
        g_ctx.state = STATE_IDLE;
    }

    while (g_ctx.task_handle != NULL) {
        vTaskDelay(pdMS_TO_TICKS(10));
    }

    if (g_ctx.input_handle) {
        audio_stream_close(g_ctx.input_handle);
        g_ctx.input_handle = NULL;
    }
    if (g_ctx.output_handle) {
        audio_stream_close(g_ctx.output_handle);
        g_ctx.output_handle = NULL;
    }

    if (g_ctx.audio_buf != NULL) {
        free(g_ctx.audio_buf);
        g_ctx.audio_buf = NULL;
    }
}

int main(int argc, char* argv[]) {
    tt_app_register((AppRegistration) {
        .onShow = onShowApp,
        .onHide = onHideApp
    });
    return 0;
}
