export function generateCaptcha(length = 5) {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
  return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('')
}

export function drawCaptcha(canvas, code) {
  if (!canvas) return
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#f8fafc'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  for (let i = 0; i < 36; i += 1) {
    ctx.fillStyle = `rgba(${60 + Math.random() * 120}, ${80 + Math.random() * 120}, ${90 + Math.random() * 120}, .24)`
    ctx.beginPath()
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, Math.random() * 2.2 + 0.8, 0, Math.PI * 2)
    ctx.fill()
  }

  for (let i = 0; i < 4; i += 1) {
    ctx.strokeStyle = `rgba(15, 118, 110, ${0.2 + Math.random() * 0.35})`
    ctx.lineWidth = 1 + Math.random() * 1.5
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.bezierCurveTo(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      Math.random() * canvas.width,
      Math.random() * canvas.height,
    )
    ctx.stroke()
  }

  ;[...code].forEach((char, index) => {
    ctx.save()
    ctx.translate(20 + index * 23, 30 + (Math.random() - 0.5) * 8)
    ctx.rotate((Math.random() - 0.5) * 0.45)
    ctx.fillStyle = index % 2 ? '#0f766e' : '#172033'
    ctx.font = `${22 + Math.random() * 5}px Arial`
    ctx.fillText(char, 0, 0)
    ctx.restore()
  })
}
