// Dice renderer — draws animated dice for backgammon

const DIE_SIZE = 36;
const DOT_RADIUS = 3.5;
const ROLL_FRAMES = 18;
const ROLL_DURATION = 600;

export function drawDice(ctx, x, y, values, options = {}) {
  const { used = [], rolling = false, frame = 0 } = options;

  for (let i = 0; i < values.length; i++) {
    const dx = x + i * (DIE_SIZE + 10);
    const val = rolling ? Math.floor(Math.random() * 6) + 1 : values[i];
    const isUsed = used.includes(i);
    drawSingleDie(ctx, dx, y, val, isUsed, rolling ? frame : 0);
  }
}

function drawSingleDie(ctx, x, y, value, isUsed, frame) {
  const rotation = frame > 0 ? (frame / ROLL_FRAMES) * Math.PI * 4 : 0;

  ctx.save();
  ctx.translate(x + DIE_SIZE / 2, y + DIE_SIZE / 2);
  if (frame > 0) ctx.rotate(rotation);
  ctx.translate(-DIE_SIZE / 2, -DIE_SIZE / 2);

  // Die body
  ctx.fillStyle = isUsed ? 'rgba(200, 200, 200, 0.4)' : '#fffef0';
  ctx.strokeStyle = isUsed ? 'rgba(150, 150, 150, 0.5)' : '#8B4513';
  ctx.lineWidth = 1.5;

  roundRect(ctx, 0, 0, DIE_SIZE, DIE_SIZE, 5);
  ctx.fill();
  ctx.stroke();

  if (isUsed) {
    ctx.globalAlpha = 0.4;
  }

  // Dots
  ctx.fillStyle = '#1a1a1a';
  const positions = getDotPositions(value, DIE_SIZE);
  for (const [dx, dy] of positions) {
    ctx.beginPath();
    ctx.arc(dx, dy, DOT_RADIUS, 0, Math.PI * 2);
    ctx.fill();
  }

  ctx.restore();
}

function getDotPositions(value, size) {
  const s = size;
  const c = s / 2;
  const q1 = s * 0.25;
  const q3 = s * 0.75;

  switch (value) {
    case 1: return [[c, c]];
    case 2: return [[q1, q3], [q3, q1]];
    case 3: return [[q1, q3], [c, c], [q3, q1]];
    case 4: return [[q1, q1], [q1, q3], [q3, q1], [q3, q3]];
    case 5: return [[q1, q1], [q1, q3], [c, c], [q3, q1], [q3, q3]];
    case 6: return [[q1, q1], [q1, c], [q1, q3], [q3, q1], [q3, c], [q3, q3]];
    default: return [[c, c]];
  }
}

function roundRect(ctx, x, y, w, h, r) {
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.arcTo(x + w, y, x + w, y + h, r);
  ctx.arcTo(x + w, y + h, x, y + h, r);
  ctx.arcTo(x, y + h, x, y, r);
  ctx.arcTo(x, y, x + w, y, r);
  ctx.closePath();
}

export function createRollAnimation(onFrame, onComplete) {
  let frame = 0;
  const startTime = performance.now();

  function tick(now) {
    const elapsed = now - startTime;
    frame = Math.min(ROLL_FRAMES, Math.floor((elapsed / ROLL_DURATION) * ROLL_FRAMES));
    onFrame(frame);

    if (elapsed < ROLL_DURATION) {
      requestAnimationFrame(tick);
    } else {
      onComplete();
    }
  }

  requestAnimationFrame(tick);
}
