#include "quantum.h"
#include "he_logic.h"
#include "pointing_device.h"

// Define WASD coordinates
#define W_ROW 0
#define W_COL 2

#define A_ROW 1
#define A_COL 1

#define S_ROW 1
#define S_COL 2

#define D_ROW 1
#define D_COL 3

static int16_t map_adc_to_velocity(uint16_t adc_val, he_switch_t *sw) {
    uint16_t travel = (adc_val > sw->lowest_val) ? (adc_val - sw->lowest_val) : 0;
    
    // Deadzone
    if (travel < 300) return 0;
    
    // Scale travel to velocity
    int16_t velocity = (travel - 300) / 100;
    if (velocity > 20) velocity = 20; // Max velocity
    
    return velocity;
}

report_mouse_t pointing_device_task_user(report_mouse_t mouse_report) {
    if (is_keyboard_left()) {
        int16_t x = 0;
        int16_t y = 0;
        
        // W
        if (he_switches[W_ROW][W_COL].is_pressed) {
            y -= map_adc_to_velocity(he_switches[W_ROW][W_COL].current_val, &he_switches[W_ROW][W_COL]);
        }
        // S
        if (he_switches[S_ROW][S_COL].is_pressed) {
            y += map_adc_to_velocity(he_switches[S_ROW][S_COL].current_val, &he_switches[S_ROW][S_COL]);
        }
        // A
        if (he_switches[A_ROW][A_COL].is_pressed) {
            x -= map_adc_to_velocity(he_switches[A_ROW][A_COL].current_val, &he_switches[A_ROW][A_COL]);
        }
        // D
        if (he_switches[D_ROW][D_COL].is_pressed) {
            x += map_adc_to_velocity(he_switches[D_ROW][D_COL].current_val, &he_switches[D_ROW][D_COL]);
        }
        
        if (x != 0 || y != 0) {
            mouse_report.x = x;
            mouse_report.y = y;
        }
    }
    
    return mouse_report;
}
