#include "drill_click.h"
#include <string.h>
static bool source_ok(dc_source s) { return s == DC_MAIN_KEY || s == DC_HANDPIECE_KEY; }
bool dclick_init(dc_decoder *d, uint32_t window_ms) {
    if (!d) return false;
    memset(d, 0, sizeof(*d));
    if (window_ms < 100u || window_ms > 1000u) return false;
    d->window_ms = window_ms;
    return true;
}
void dclick_cancel(dc_decoder *d) {
    if (d) memset(d->channel, 0, sizeof(d->channel));
}
bool dclick_release(dc_decoder *d, dc_source source, uint32_t now_ms) {
    if (!d || !d->window_ms || !source_ok(source)) return false;
    dc_channel *c = &d->channel[source];
    if (c->pending && (uint32_t)(now_ms - c->last_ms) >= d->window_ms) return false;
    if (c->count < 4u) ++c->count; /* Four or more clicks reject the sequence. */
    c->last_ms = now_ms;
    c->pending = true;
    return true;
}
dc_command dclick_poll(dc_decoder *d, dc_source source, uint32_t now_ms) {
    if (!d || !d->window_ms || !source_ok(source)) return DC_NONE;
    dc_channel *c = &d->channel[source];
    if (!c->pending || (uint32_t)(now_ms - c->last_ms) < d->window_ms) return DC_NONE;
    uint8_t n = c->count;
    memset(c, 0, sizeof(*c));
    if (n == 1u) return DC_TOGGLE_RUN_REQUEST;
    if (n == 2u) return DC_REVERSE_REQUEST;
    if (n == 3u && source == DC_MAIN_KEY) return DC_MODE_REQUEST;
    return DC_REJECTED;
}
