import { onMounted, onUnmounted } from 'vue';

export function useBarcodeScanner(options = {}) {
  const {
    onScan,
    minLength = 3,
    scanTimeout = 100,
    enterKey = true
  } = options;

  let barcode = '';
  let timeout;

  const handleKeyPress = (e) => {
    // Ignorar si está escribiendo en inputs
    if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) {
      return;
    }

    if (e.key === 'Enter' && enterKey) {
      if (barcode.length >= minLength) {
        onScan?.(barcode);
        barcode = '';
      }
    } else if (e.key.length === 1) {
      clearTimeout(timeout);
      barcode += e.key;
      
      timeout = setTimeout(() => {
        barcode = '';
      }, scanTimeout);
    }
  };

  onMounted(() => {
    document.addEventListener('keypress', handleKeyPress);
  });

  onUnmounted(() => {
    document.removeEventListener('keypress', handleKeyPress);
    clearTimeout(timeout);
  });

  return {};
}
