const PIXEL_CHARS = {
  stock: { body: '#4488cc', accent: '#cc4444', label: '주식', hair: '#332222' },
  music: { body: '#44aa88', accent: '#ffaa00', label: '음악', hair: '#443322' },
  claude: { body: '#8855cc', accent: '#cc88ff', label: 'Claude', hair: '#554466' },
};

const ANIM_FRAMES = {
  idle: { frames: 2, speed: 800 },
  working: { frames: 4, speed: 200 },
  waiting: { frames: 2, speed: 400 },
  break: { frames: 2, speed: 1000 },
  walk: { frames: 4, speed: 150 },
};

export function drawAgent(ctx, agentId, x, y, state, frameIndex, scale = 2) {
  const char = PIXEL_CHARS[agentId] || PIXEL_CHARS.claude;
  const s = scale;
  const anim = ANIM_FRAMES[state] || ANIM_FRAMES.idle;
  const frame = frameIndex % anim.frames;

  ctx.save();
  ctx.translate(x, y);

  // Shadow
  ctx.fillStyle = 'rgba(0,0,0,0.2)';
  ctx.fillRect(-4 * s, 14 * s, 8 * s, 2 * s);

  // Body
  ctx.fillStyle = char.body;
  ctx.fillRect(-3 * s, 2 * s, 6 * s, 8 * s);

  // Head
  ctx.fillStyle = '#ffcc99';
  ctx.fillRect(-3 * s, -4 * s, 6 * s, 6 * s);

  // Hair
  ctx.fillStyle = char.hair;
  ctx.fillRect(-3 * s, -5 * s, 6 * s, 2 * s);

  // Eyes
  ctx.fillStyle = '#222';
  const eyeOffset = state === 'break' && frame === 1 ? 0 : 1;
  ctx.fillRect(-2 * s, -1 * s, 1 * s, eyeOffset * s);
  ctx.fillRect(1 * s, -1 * s, 1 * s, eyeOffset * s);

  // Legs
  ctx.fillStyle = '#335';
  const legSpread = state === 'walk' ? (frame % 2 === 0 ? 1 : -1) : 0;
  ctx.fillRect(-2 * s, 10 * s, 2 * s, 4 * s);
  ctx.fillRect(0 + legSpread * s, 10 * s, 2 * s, 4 * s);

  // Accent
  ctx.fillStyle = char.accent;
  if (agentId === 'stock') {
    ctx.fillRect(0, 2 * s, 1 * s, 5 * s);
  } else if (agentId === 'music') {
    ctx.fillRect(-4 * s, -4 * s, 1 * s, 4 * s);
    ctx.fillRect(3 * s, -4 * s, 1 * s, 4 * s);
    ctx.fillRect(-4 * s, -5 * s, 8 * s, 1 * s);
  } else if (agentId === 'claude') {
    ctx.globalAlpha = 0.3 + 0.2 * Math.sin(Date.now() / 500);
    ctx.fillRect(-4 * s, -6 * s, 8 * s, 1 * s);
    ctx.globalAlpha = 1;
  }

  // Working: typing hands
  if (state === 'working') {
    ctx.fillStyle = '#ffcc99';
    const handY = 6 * s + (frame % 2) * s;
    ctx.fillRect(-4 * s, handY, 1 * s, 2 * s);
    ctx.fillRect(3 * s, handY, 1 * s, 2 * s);
  }

  // Waiting wobble
  if (state === 'waiting') {
    const wobble = Math.sin(Date.now() / 200) * s;
    ctx.translate(wobble, 0);
  }

  ctx.restore();
}

export function getAnimSpeed(state) {
  return (ANIM_FRAMES[state] || ANIM_FRAMES.idle).speed;
}

export function getCharLabel(agentId) {
  return (PIXEL_CHARS[agentId] || {}).label || agentId;
}
