<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const input = ref('');
const code = ref('');
const canvasRef = ref<HTMLCanvasElement | null>(null);
const honeypot = ref('');
const validated = ref(false);
const errorMsg = ref('');

const CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const CANVAS_W = 96;
const CANVAS_H = 36;

function generateCode() {
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += CHARS[Math.floor(Math.random() * CHARS.length)];
  }
  code.value = result;
}

function drawCaptcha() {
  const canvas = canvasRef.value;
  if (!canvas) return;
  canvas.width = CANVAS_W;
  canvas.height = CANVAS_H;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  ctx.fillStyle = '#0d0d0d';
  ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);

  for (let i = 0; i < 20; i++) {
    ctx.fillStyle = `rgba(255, 255, 255, ${0.03 + Math.random() * 0.06})`;
    ctx.beginPath();
    ctx.arc(Math.random() * CANVAS_W, Math.random() * CANVAS_H, Math.random() * 1.8, 0, Math.PI * 2);
    ctx.fill();
  }

  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgba(255, 255, 255, ${0.06 + Math.random() * 0.08})`;
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(Math.random() * CANVAS_W, Math.random() * CANVAS_H);
    ctx.lineTo(Math.random() * CANVAS_W, Math.random() * CANVAS_H);
    ctx.stroke();
  }

  const charWidth = CANVAS_W / (code.value.length + 1);
  for (let i = 0; i < code.value.length; i++) {
    ctx.save();
    const x = charWidth * (i + 0.5) + (Math.random() - 0.5) * 3;
    const y = CANVAS_H / 2 + (Math.random() - 0.5) * 4;
    ctx.translate(x, y);
    ctx.rotate((Math.random() - 0.5) * 0.35);
    ctx.font = `bold ${15 + Math.random() * 4}px 'Courier New', monospace`;
    ctx.fillStyle = `rgba(240, 216, 117, ${0.85 + Math.random() * 0.15})`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(code.value[i], 0, 0);
    ctx.restore();
  }
}

function refresh() {
  generateCode();
  input.value = '';
  validated.value = false;
  errorMsg.value = '';
  drawCaptcha();
}

function validate(): boolean {
  if (honeypot.value) { refresh(); return false; }
  if (!input.value.trim()) {
    errorMsg.value = t('auth.captcha_wrong');
    return false;
  }
  if (input.value.trim().toUpperCase() !== code.value.toUpperCase()) {
    errorMsg.value = t('auth.captcha_wrong');
    refresh();
    return false;
  }
  validated.value = true;
  errorMsg.value = '';
  return true;
}

onMounted(refresh);
defineExpose({ validate, refresh });
</script>

<template>
  <div class="captcha-wrap">
    <div class="captcha-row">
      <input
        v-model="honeypot"
        type="text"
        name="website"
        tabindex="-1"
        autocomplete="off"
        class="hp-field"
        aria-hidden="true"
      />
      <input
        v-model="input"
        type="text"
        maxlength="4"
        class="captcha-input"
        :placeholder="t('auth.captcha_placeholder')"
        autocomplete="off"
      />
      <canvas
        ref="canvasRef"
        class="captcha-canvas"
        :width="CANVAS_W"
        :height="CANVAS_H"
        :title="t('auth.captcha_refresh')"
        role="button"
        tabindex="0"
        @click="refresh"
        @keydown.enter="refresh"
      />
    </div>
    <p v-if="errorMsg" class="captcha-error">{{ errorMsg }}</p>
  </div>
</template>

<style scoped>
.captcha-wrap {
  width: 100%;
}

.captcha-row {
  display: flex;
  align-items: stretch;
  height: 36px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: #0d0d0d;
  overflow: hidden;
}

.captcha-row:focus-within {
  border-color: #555;
}

.hp-field {
  position: absolute;
  left: -9999px;
  width: 1px;
  height: 1px;
  opacity: 0;
  pointer-events: none;
}

.captcha-input {
  flex: 1;
  min-width: 0;
  padding: 0 10px;
  border: none;
  background: transparent;
  color: var(--text);
  font-size: 14px;
  font-weight: 700;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  outline: none;
  font-family: inherit;
}

.captcha-input::placeholder {
  color: rgba(255, 255, 255, 0.32);
  font-weight: 600;
  letter-spacing: 0.02em;
  text-transform: none;
}

.captcha-canvas {
  flex-shrink: 0;
  width: 96px;
  height: 36px;
  cursor: pointer;
  display: block;
  border: none;
  border-left: 1px solid var(--border);
}

.captcha-error {
  color: var(--danger);
  font-size: 12px;
  font-weight: 600;
  margin: 4px 0 0;
}
</style>
