import * as bus from './bus.js';

let startX, startY, startTime;
const SWIPE_THRESHOLD = 50;
const TAP_THRESHOLD = 10;

export function init() {
  const el = document.getElementById('game');

  el.addEventListener('touchstart', onStart, { passive: true });
  el.addEventListener('touchend', onEnd, { passive: true });
  el.addEventListener('mousedown', onStart);
  el.addEventListener('mouseup', onEnd);
}

function onStart(e) {
  const point = e.touches ? e.touches[0] : e;
  startX = point.clientX;
  startY = point.clientY;
  startTime = Date.now();
}

function onEnd(e) {
  const point = e.changedTouches ? e.changedTouches[0] : e;
  const dx = point.clientX - startX;
  const dy = point.clientY - startY;
  const dt = Date.now() - startTime;
  const dist = Math.sqrt(dx * dx + dy * dy);

  if (dist < TAP_THRESHOLD && dt < 300) {
    bus.emit('input:tap', { x: point.clientX, y: point.clientY });
    return;
  }

  if (dist > SWIPE_THRESHOLD && Math.abs(dx) > Math.abs(dy)) {
    const dir = dx > 0 ? 'right' : 'left';
    bus.emit('input:swipe', { direction: dir, distance: Math.abs(dx), duration: dt });
  }
}

export function onElement(el, event, handler) {
  el.addEventListener('click', handler);
  return () => el.removeEventListener('click', handler);
}
