// Move animator — smooth piece transitions
import { getPointCoords } from './board-renderer.js';

const MOVE_DURATION = 300;
const HIT_DURATION = 400;

export function createMoveAnimation(from, to, layout, onFrame, onComplete) {
  const startPos = getPixelPos(from, layout);
  const endPos = getPixelPos(to, layout);

  if (!startPos || !endPos) {
    onComplete();
    return;
  }

  const startTime = performance.now();
  const duration = from === 'bar' || to === 'bar' ? HIT_DURATION : MOVE_DURATION;

  function tick(now) {
    const elapsed = now - startTime;
    const t = Math.min(1, elapsed / duration);
    const ease = 1 - Math.pow(1 - t, 3); // ease-out cubic

    const x = startPos.x + (endPos.x - startPos.x) * ease;
    const y = startPos.y + (endPos.y - startPos.y) * ease;

    // Arc for hits (pieces going to bar)
    let arcY = 0;
    if (to === 'bar') {
      arcY = -40 * Math.sin(t * Math.PI);
    }

    onFrame({ x, y: y + arcY, progress: t });

    if (t < 1) {
      requestAnimationFrame(tick);
    } else {
      onComplete();
    }
  }

  requestAnimationFrame(tick);
}

function getPixelPos(location, layout) {
  if (!layout) return null;
  const { margin, pointW, pointH, barWidth, barX, boardH, bearX, bearOffWidth } = layout;

  if (location === 'bar') {
    return { x: barX + barWidth / 2, y: margin + boardH / 2 };
  }

  if (location === 'off') {
    return { x: bearX + bearOffWidth / 2, y: margin + boardH / 2 };
  }

  if (typeof location === 'number' && location >= 0 && location <= 23) {
    const { x, y, isTop } = getPointCoords(location, margin, pointW, pointH, barWidth, boardH);
    return {
      x: x + pointW / 2,
      y: isTop ? y + 20 : y - 20
    };
  }

  return null;
}
