// Board renderer — draws the backgammon board on canvas
import { WHITE, BLACK } from '../logic/rules.js';

const CHECKER_RADIUS = 16;
const MAX_VISIBLE = 5;

export function drawBoard(ctx, w, h, state, options = {}) {
  const { highlights = [], selectedPoint = null, theme = {} } = options;

  const boardColor = theme.board || '#2d5016';
  const borderColor = theme.border || '#5c3a1e';
  const pointDark = theme.pointDark || '#8B4513';
  const pointLight = theme.pointLight || '#D2691E';
  const barColor = theme.bar || '#3d2b1a';

  const margin = 8;
  const barWidth = w * 0.06;
  const bearOffWidth = w * 0.07;
  const boardW = w - margin * 2;
  const boardH = h - margin * 2;
  const innerW = boardW - bearOffWidth;
  const innerH = boardH;
  const pointW = (innerW - barWidth) / 12;
  const pointH = innerH * 0.42;

  ctx.clearRect(0, 0, w, h);

  // Board background
  ctx.fillStyle = boardColor;
  ctx.fillRect(margin, margin, boardW, boardH);

  // Border
  ctx.strokeStyle = borderColor;
  ctx.lineWidth = 3;
  ctx.strokeRect(margin, margin, boardW, boardH);

  // Bar
  const barX = margin + 6 * pointW;
  ctx.fillStyle = barColor;
  ctx.fillRect(barX, margin, barWidth, boardH);

  // Bear-off tray
  const bearX = margin + innerW;
  ctx.fillStyle = barColor;
  ctx.fillRect(bearX, margin, bearOffWidth, boardH);
  ctx.strokeStyle = 'rgba(255,255,255,0.1)';
  ctx.strokeRect(bearX, margin, bearOffWidth, boardH);

  // Draw points (triangles)
  for (let i = 0; i < 24; i++) {
    const { x, y, isTop } = getPointCoords(i, margin, pointW, pointH, barWidth, boardH);
    const color = i % 2 === 0 ? pointDark : pointLight;

    ctx.beginPath();
    if (isTop) {
      ctx.moveTo(x, y);
      ctx.lineTo(x + pointW, y);
      ctx.lineTo(x + pointW / 2, y + pointH);
    } else {
      ctx.moveTo(x, y);
      ctx.lineTo(x + pointW, y);
      ctx.lineTo(x + pointW / 2, y - pointH);
    }
    ctx.closePath();

    // Highlight valid destinations
    if (highlights.includes(i)) {
      ctx.fillStyle = 'rgba(34, 197, 94, 0.4)';
      ctx.fill();
      ctx.strokeStyle = '#22c55e';
      ctx.lineWidth = 2;
      ctx.stroke();
    } else if (selectedPoint === i) {
      ctx.fillStyle = 'rgba(251, 191, 36, 0.3)';
      ctx.fill();
      ctx.strokeStyle = '#fbbf24';
      ctx.lineWidth = 2;
      ctx.stroke();
    } else {
      ctx.fillStyle = color;
      ctx.fill();
    }
  }

  // Draw checkers on points
  for (let i = 0; i < 24; i++) {
    const pieces = state.points[i];
    if (pieces.length === 0) continue;
    const { x, y, isTop } = getPointCoords(i, margin, pointW, pointH, barWidth, boardH);
    const cx = x + pointW / 2;

    const count = pieces.length;
    const visibleCount = Math.min(count, MAX_VISIBLE);
    const spacing = Math.min(CHECKER_RADIUS * 2, pointH / visibleCount);

    for (let j = 0; j < visibleCount; j++) {
      const cy = isTop
        ? y + CHECKER_RADIUS + j * spacing
        : y - CHECKER_RADIUS - j * spacing;
      drawChecker(ctx, cx, cy, pieces[j].type, theme);
    }

    if (count > MAX_VISIBLE) {
      const lastY = isTop
        ? y + CHECKER_RADIUS + (visibleCount - 1) * spacing
        : y - CHECKER_RADIUS - (visibleCount - 1) * spacing;
      ctx.fillStyle = '#fff';
      ctx.font = 'bold 11px sans-serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(String(count), cx, lastY);
    }
  }

  // Draw bar pieces
  drawBarPieces(ctx, state, barX, barWidth, margin, boardH, theme);

  // Draw bear-off pieces
  drawBearOffPieces(ctx, state, bearX, bearOffWidth, margin, boardH, theme);

  // Highlight bear-off if valid destination
  if (highlights.includes('off')) {
    ctx.fillStyle = 'rgba(34, 197, 94, 0.3)';
    ctx.fillRect(bearX + 2, margin + 2, bearOffWidth - 4, boardH - 4);
    ctx.strokeStyle = '#22c55e';
    ctx.lineWidth = 2;
    ctx.strokeRect(bearX + 2, margin + 2, bearOffWidth - 4, boardH - 4);
  }

  return { margin, pointW, pointH, barWidth, barX, boardH, bearX, bearOffWidth, innerW };
}

function drawChecker(ctx, x, y, type, theme) {
  const whiteColor = theme.checkerWhite || '#f8fafc';
  const blackColor = theme.checkerBlack || '#1e293b';
  const color = type === WHITE ? whiteColor : blackColor;
  const borderCol = type === WHITE ? '#94a3b8' : '#475569';

  ctx.beginPath();
  ctx.arc(x, y, CHECKER_RADIUS - 1, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
  ctx.strokeStyle = borderCol;
  ctx.lineWidth = 2;
  ctx.stroke();

  // Inner ring
  ctx.beginPath();
  ctx.arc(x, y, CHECKER_RADIUS - 5, 0, Math.PI * 2);
  ctx.strokeStyle = type === WHITE ? '#cbd5e1' : '#64748b';
  ctx.lineWidth = 1;
  ctx.stroke();
}

function drawBarPieces(ctx, state, barX, barWidth, margin, boardH, theme) {
  const cx = barX + barWidth / 2;

  // White bar pieces (bottom half)
  const whiteBar = state.bar[WHITE];
  for (let i = 0; i < whiteBar.length; i++) {
    const cy = margin + boardH / 2 + 20 + i * (CHECKER_RADIUS * 2 + 2);
    drawChecker(ctx, cx, cy, WHITE, theme);
  }

  // Black bar pieces (top half)
  const blackBar = state.bar[BLACK];
  for (let i = 0; i < blackBar.length; i++) {
    const cy = margin + boardH / 2 - 20 - i * (CHECKER_RADIUS * 2 + 2);
    drawChecker(ctx, cx, cy, BLACK, theme);
  }
}

function drawBearOffPieces(ctx, state, bearX, bearOffWidth, margin, boardH, theme) {
  const cx = bearX + bearOffWidth / 2;

  // White bear-off (bottom)
  const whiteOff = state.outside[WHITE].length;
  if (whiteOff > 0) {
    const startY = margin + boardH - 10;
    for (let i = 0; i < Math.min(whiteOff, 8); i++) {
      ctx.fillStyle = theme.checkerWhite || '#f8fafc';
      ctx.fillRect(cx - 10, startY - i * 8 - 8, 20, 6);
      ctx.strokeStyle = '#94a3b8';
      ctx.strokeRect(cx - 10, startY - i * 8 - 8, 20, 6);
    }
    if (whiteOff > 0) {
      ctx.fillStyle = '#fff';
      ctx.font = 'bold 10px sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText(String(whiteOff), cx, startY - Math.min(whiteOff, 8) * 8 - 12);
    }
  }

  // Black bear-off (top)
  const blackOff = state.outside[BLACK].length;
  if (blackOff > 0) {
    const startY = margin + 10;
    for (let i = 0; i < Math.min(blackOff, 8); i++) {
      ctx.fillStyle = theme.checkerBlack || '#1e293b';
      ctx.fillRect(cx - 10, startY + i * 8, 20, 6);
      ctx.strokeStyle = '#475569';
      ctx.strokeRect(cx - 10, startY + i * 8, 20, 6);
    }
    if (blackOff > 0) {
      ctx.fillStyle = '#fff';
      ctx.font = 'bold 10px sans-serif';
      ctx.textAlign = 'center';
      ctx.fillText(String(blackOff), cx, startY + Math.min(blackOff, 8) * 8 + 14);
    }
  }
}

export function getPointCoords(pointIndex, margin, pointW, pointH, barWidth, boardH) {
  let x, y, isTop;

  if (pointIndex >= 12) {
    // Top row: 12-23 left to right
    const col = pointIndex - 12;
    x = margin + col * pointW + (col >= 6 ? barWidth : 0);
    y = margin;
    isTop = true;
  } else {
    // Bottom row: 11-0 left to right
    const col = 11 - pointIndex;
    x = margin + col * pointW + (col >= 6 ? barWidth : 0);
    y = margin + boardH;
    isTop = false;
  }

  return { x, y, isTop };
}

export function hitTest(canvasX, canvasY, layout, state) {
  if (!layout) return null;
  const { margin, pointW, pointH, barWidth, barX, boardH, bearX, bearOffWidth } = layout;

  // Check bar area
  if (canvasX >= barX && canvasX <= barX + barWidth) {
    if (canvasY > margin + boardH / 2) return { type: 'bar', player: WHITE };
    return { type: 'bar', player: BLACK };
  }

  // Check bear-off area
  if (canvasX >= bearX && canvasX <= bearX + bearOffWidth) {
    return { type: 'bearoff' };
  }

  // Check points
  for (let i = 0; i < 24; i++) {
    const { x, y, isTop } = getPointCoords(i, margin, pointW, pointH, barWidth, boardH);
    if (canvasX >= x && canvasX <= x + pointW) {
      if (isTop && canvasY >= margin && canvasY <= margin + pointH + CHECKER_RADIUS * 2) {
        return { type: 'point', index: i };
      }
      if (!isTop && canvasY >= margin + boardH - pointH - CHECKER_RADIUS * 2 && canvasY <= margin + boardH) {
        return { type: 'point', index: i };
      }
    }
  }

  return null;
}
