/**
 * Caliper Status - Passive HID Monitor
 * USB digital calipers act as keyboard emulators (HID),
 * sending digits + Enter as keystrokes. This component
 * monitors numpad-confirm events with inputMethod === 'usb_caliper'
 * and provides visual feedback (no Web Serial needed).
 */

function caliperStatus() {
  return {
    active: false,        // Flash active (for animation)
    lastReading: null,    // Last value read from caliper
    readingCount: 0,      // Session reading counter
    _flashTimeout: null,
    _onConfirm: null,

    init() {
      // Listen for numpad confirmations with usb_caliper method
      this._onConfirm = (e) => {
        if (e.detail && e.detail.inputMethod === 'usb_caliper') {
          this.registerReading(e.detail.value);
        }
      };
      window.addEventListener('numpad-confirm', this._onConfirm);
    },

    registerReading(value) {
      this.lastReading = value;
      this.readingCount++;
      this.active = true;

      clearTimeout(this._flashTimeout);
      this._flashTimeout = setTimeout(() => {
        this.active = false;
      }, 1500);
    },

    destroy() {
      if (this._onConfirm) {
        window.removeEventListener('numpad-confirm', this._onConfirm);
      }
      clearTimeout(this._flashTimeout);
    }
  };
}
