// 图形验证码工具 - 纯前端 Canvas 生成，不依赖后端
// 生成4位数字+字母混合验证码，带干扰线和噪点
function generateCaptcha() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  let text = '';
  for (let i = 0; i < 4; i++) {
    text += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return { text, image: null }; // image 将由 Canvas 组件绘制
}

// 在 canvas 上绘制验证码
function drawCaptcha(canvas, text) {
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  const w = canvas.width;
  const h = canvas.height;

  // 背景
  ctx.fillStyle = '#f0ebe0';
  ctx.fillRect(0, 0, w, h);

  // 干扰线
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = `rgba(${rand(100, 180)}, ${rand(100, 180)}, ${rand(100, 180)}, 0.5)`;
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(Math.random() * w, Math.random() * h);
    ctx.bezierCurveTo(
      Math.random() * w, Math.random() * h,
      Math.random() * w, Math.random() * h,
      Math.random() * w, Math.random() * h
    );
    ctx.stroke();
  }

  // 噪点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgba(${rand(80, 160)}, ${rand(80, 160)}, ${rand(80, 160)}, 0.6)`;
    ctx.beginPath();
    ctx.arc(Math.random() * w, Math.random() * h, Math.random() * 1.5, 0, Math.PI * 2);
    ctx.fill();
  }

  // 文字
  const colors = ['#3a8f7a', '#d85a4a', '#4a7dac', '#e08b3a', '#7c5cd8'];
  const fonts = ['bold 26px serif', 'bold 24px "Courier New"', 'bold 28px Georgia'];
  const charW = w / text.length;

  for (let i = 0; i < text.length; i++) {
    const ch = text[i];
    ctx.save();
    ctx.translate(charW * i + charW / 2, h / 2 + rand(-3, 3));
    ctx.rotate((Math.random() - 0.5) * 0.5); // 随机旋转
    ctx.font = fonts[Math.floor(Math.random() * fonts.length)];
    ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(ch, 0, 0);
    ctx.restore();
  }
}

function rand(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// React 验证码组件
function CaptchaCanvas({ captchaText, onClick }) {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    if (canvasRef.current && captchaText) {
      drawCaptcha(canvasRef.current, captchaText);
    }
  }, [captchaText]);

  return (
    <canvas
      ref={canvasRef}
      width={120}
      height={40}
      onClick={onClick}
      style={{
        width: 120,
        height: 40,
        borderRadius: 10,
        cursor: 'pointer',
        border: '1.5px solid #ebe8e0',
        display: 'block',
      }}
      title="点击刷新验证码"
    />
  );
}

window.CaptchaCanvas = CaptchaCanvas;
