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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { RefreshCw, ShieldCheck, ShieldAlert, Lock } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

interface CaptchaTextProps {
  onVerified: (verified: boolean) => void;
}

// Characters that are visually distinct to avoid confusion (removed O/0, I/l/1, etc.)
const CHARS = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz2345679';

/** Simple hash for internal token signing */
function hashToken(str: string): string {
  let h = 5381;
  for (let i = 0; i < str.length; i++) {
    h = ((h << 5) + h) ^ str.charCodeAt(i);
    h = h >>> 0;
  }
  return h.toString(36);
}

/** XOR-based obfuscation so the answer isn't stored in plaintext */
function obfuscate(text: string, key: string): string {
  return text
    .split('')
    .map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ key.charCodeAt(i % key.length)))
    .map(c => c.charCodeAt(0).toString(16).padStart(4, '0'))
    .join('');
}

function deobfuscate(hex: string, key: string): string {
  const chars: string[] = [];
  for (let i = 0; i < hex.length; i += 4) {
    chars.push(String.fromCharCode(parseInt(hex.substring(i, i + 4), 16)));
  }
  return chars
    .map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ key.charCodeAt(i % key.length)))
    .join('');
}

function generateCode(length = 5): string {
  let code = '';
  const arr = new Uint32Array(length);
  crypto.getRandomValues(arr);
  for (let i = 0; i < length; i++) {
    code += CHARS[arr[i] % CHARS.length];
  }
  return code;
}

/** Draw the actual code with heavy distortion on canvas */
function drawCaptcha(canvas: HTMLCanvasElement, code: string) {
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  const w = canvas.width;
  const h = canvas.height;

  // Dark textured background
  const bgGrad = ctx.createLinearGradient(0, 0, w, h);
  bgGrad.addColorStop(0, '#1a1a2e');
  bgGrad.addColorStop(0.5, '#16213e');
  bgGrad.addColorStop(1, '#0f3460');
  ctx.fillStyle = bgGrad;
  ctx.fillRect(0, 0, w, h);

  // Heavy noise dots
  for (let i = 0; i < 200; i++) {
    ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, ${0.03 + Math.random() * 0.08})`;
    ctx.beginPath();
    ctx.arc(Math.random() * w, Math.random() * h, Math.random() * 2.5, 0, Math.PI * 2);
    ctx.fill();
  }

  // Wavy confusing lines
  for (let i = 0; i < 6; i++) {
    ctx.strokeStyle = `rgba(${100 + Math.random() * 155}, ${100 + Math.random() * 155}, ${100 + Math.random() * 155}, ${0.15 + Math.random() * 0.2})`;
    ctx.lineWidth = 0.8 + Math.random() * 1.5;
    ctx.beginPath();
    const startY = Math.random() * h;
    ctx.moveTo(0, startY);
    for (let x = 0; x < w; x += 3) {
      const amplitude = 4 + Math.random() * 8;
      const freq = 0.03 + Math.random() * 0.06;
      ctx.lineTo(x, startY + Math.sin(x * freq + i * 2) * amplitude + (Math.random() - 0.5) * 3);
    }
    ctx.stroke();
  }

  // Bezier curves crossing text area
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgba(${150 + Math.random() * 100}, ${150 + Math.random() * 100}, ${200 + Math.random() * 55}, ${0.2 + Math.random() * 0.15})`;
    ctx.lineWidth = 1 + Math.random() * 2;
    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();
  }

  // Draw each character with individual distortion
  const charSpacing = w / (code.length + 1.5);
  const colors = [
    '#e94560', '#0f3460', '#533483', '#e94560', '#00b4d8',
    '#48cae4', '#f72585', '#7209b7', '#3a0ca3', '#4361ee',
  ];

  const fonts = [
    "'Arial Black', 'Arial', sans-serif",
    "'Courier New', monospace",
    "'Georgia', serif",
    "'Verdana', sans-serif",
    "'Impact', sans-serif",
    "'Trebuchet MS', sans-serif",
  ];

  code.split('').forEach((char, i) => {
    ctx.save();

    const x = charSpacing * (i + 1) + (Math.random() - 0.5) * 8;
    const y = h / 2 + (Math.random() - 0.5) * 14;

    // Aggressive transforms
    const angle = (Math.random() - 0.5) * 0.6;
    const scaleX = 0.7 + Math.random() * 0.5;
    const scaleY = 0.7 + Math.random() * 0.5;
    const skewX = (Math.random() - 0.5) * 0.25;
    const skewY = (Math.random() - 0.5) * 0.1;

    ctx.translate(x, y);
    ctx.rotate(angle);
    ctx.transform(scaleX, skewY, skewX, scaleY, 0, 0);

    const fontSize = 28 + Math.floor(Math.random() * 12);
    const bold = Math.random() > 0.3 ? 'bold' : '900';
    ctx.font = `${bold} ${fontSize}px ${fonts[i % fonts.length]}`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    // Multi-layer text rendering for depth
    // Shadow layer
    ctx.shadowColor = 'rgba(0,0,0,0.5)';
    ctx.shadowBlur = 3 + Math.random() * 4;
    ctx.shadowOffsetX = (Math.random() - 0.5) * 3;
    ctx.shadowOffsetY = (Math.random() - 0.5) * 3;

    // Main fill
    const color = colors[i % colors.length];
    ctx.fillStyle = color;
    ctx.fillText(char, 0, 0);

    // Outline with slight offset for 3D effect
    ctx.shadowBlur = 0;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    ctx.strokeStyle = `rgba(255, 255, 255, ${0.15 + Math.random() * 0.2})`;
    ctx.lineWidth = 0.5 + Math.random() * 0.8;
    ctx.strokeText(char, (Math.random() - 0.5) * 1.5, (Math.random() - 0.5) * 1.5);

    // Ghost duplicate for confusion
    if (Math.random() > 0.5) {
      ctx.fillStyle = `rgba(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200}, 0.08)`;
      ctx.fillText(char, (Math.random() - 0.5) * 6, (Math.random() - 0.5) * 6);
    }

    ctx.restore();
  });

  // Post-processing: pixel noise
  const imageData = ctx.getImageData(0, 0, w, h);
  const pixels = imageData.data;
  for (let i = 0; i < pixels.length; i += 4) {
    const noise = (Math.random() - 0.5) * 18;
    pixels[i] = Math.max(0, Math.min(255, pixels[i] + noise));
    pixels[i + 1] = Math.max(0, Math.min(255, pixels[i + 1] + noise));
    pixels[i + 2] = Math.max(0, Math.min(255, pixels[i + 2] + noise));
  }
  ctx.putImageData(imageData, 0, 0);

  // Scanlines
  for (let y = 0; y < h; y += 2) {
    ctx.fillStyle = `rgba(0, 0, 0, ${0.02 + Math.random() * 0.06})`;
    ctx.fillRect(0, y, w, 1);
  }

  // Vignette
  const vig = ctx.createRadialGradient(w / 2, h / 2, w * 0.2, w / 2, h / 2, w * 0.7);
  vig.addColorStop(0, 'rgba(0,0,0,0)');
  vig.addColorStop(1, 'rgba(0,0,0,0.3)');
  ctx.fillStyle = vig;
  ctx.fillRect(0, 0, w, h);

  // Quality reduction: slight blur simulation
  ctx.globalAlpha = 0.15;
  ctx.drawImage(canvas, 1, 1, w - 2, h - 2, 0, 0, w, h);
  ctx.globalAlpha = 1;
}

const CaptchaText: React.FC<CaptchaTextProps> = ({ onVerified }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [encryptedAnswer, setEncryptedAnswer] = useState('');
  const [sessionKey] = useState(() => crypto.randomUUID());
  const [input, setInput] = useState('');
  const [status, setStatus] = useState<'idle' | 'correct' | 'wrong' | 'locked'>('idle');
  const [attempts, setAttempts] = useState(0);
  const [generatedAt, setGeneratedAt] = useState(0);
  const [honeypot, setHoneypot] = useState('');
  const [lockTimer, setLockTimer] = useState(0);
  const [interactionTimestamps, setInteractionTimestamps] = useState<number[]>([]);
  const [mouseMovements, setMouseMovements] = useState(0);

  const regenerate = useCallback(() => {
    const code = generateCode(5);
    const encrypted = obfuscate(code, sessionKey);
    setEncryptedAnswer(encrypted);
    setInput('');
    setStatus('idle');
    setGeneratedAt(Date.now());
    setInteractionTimestamps([]);
    setMouseMovements(0);
    onVerified(false);

    // Draw on next frame to ensure canvas is ready
    requestAnimationFrame(() => {
      if (canvasRef.current) {
        drawCaptcha(canvasRef.current, code);
      }
    });
  }, [sessionKey, onVerified]);

  useEffect(() => {
    regenerate();
  }, [regenerate]);

  // Lock timer countdown
  useEffect(() => {
    if (lockTimer <= 0) return;
    const interval = setInterval(() => {
      setLockTimer(prev => {
        if (prev <= 1) {
          setStatus('idle');
          setAttempts(0);
          regenerate();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(interval);
  }, [lockTimer, regenerate]);

  // Track mouse movement for bot detection
  useEffect(() => {
    const handler = () => setMouseMovements(prev => prev + 1);
    window.addEventListener('mousemove', handler, { passive: true });
    return () => window.removeEventListener('mousemove', handler);
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (status === 'correct' || status === 'locked') return;
    setInput(e.target.value);
    setInteractionTimestamps(prev => [...prev, Date.now()]);
    if (status === 'wrong') setStatus('idle');
  };

  const handleVerify = () => {
    if (status === 'correct' || status === 'locked' || !input.trim()) return;

    // 1. Honeypot check
    if (honeypot) {
      failAttempt();
      return;
    }

    // 2. Timing check — solved too fast = bot
    const elapsed = Date.now() - generatedAt;
    if (elapsed < 1500) {
      failAttempt();
      return;
    }

    // 3. Mouse movement check — no mouse = likely bot
    if (mouseMovements < 3 && elapsed > 5000) {
      // Only suspicious if enough time passed but no mouse movement
      // Could be mobile, so we don't hard-fail — just note it
    }

    // 4. Typing pattern analysis
    if (interactionTimestamps.length > 2) {
      const intervals = interactionTimestamps.slice(1).map((t, i) => t - interactionTimestamps[i]);
      const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
      // Perfectly uniform typing = bot
      if (intervals.length >= 4 && intervals.every(iv => Math.abs(iv - avgInterval) < 15)) {
        failAttempt();
        return;
      }
      // Superhuman speed
      if (avgInterval < 30) {
        failAttempt();
        return;
      }
    }

    // 5. Decrypt and compare
    const answer = deobfuscate(encryptedAnswer, sessionKey);
    if (input === answer) {
      setStatus('correct');
      onVerified(true);
    } else {
      failAttempt();
    }
  };

  const failAttempt = () => {
    const newAttempts = attempts + 1;
    setAttempts(newAttempts);
    onVerified(false);

    if (newAttempts >= 8) {
      setStatus('locked');
      setLockTimer(120); // 2 minutes
    } else if (newAttempts >= 5) {
      setStatus('locked');
      setLockTimer(30); // 30 seconds
    } else {
      setStatus('wrong');
      setTimeout(regenerate, 1200);
    }
  };

  const isLocked = status === 'locked' && lockTimer > 0;

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-3">
        <div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
        <span className="text-[10px] font-black uppercase tracking-[0.2em] text-muted-foreground flex items-center gap-1">
          <ShieldCheck className="w-3 h-3" />
          التحقق الآمن
        </span>
        <div className="flex-1 h-px bg-gradient-to-r from-transparent via-primary/30 to-transparent" />
      </div>

      <div className="relative rounded-xl overflow-hidden border border-border bg-card shadow-lg">
        <canvas
          ref={canvasRef}
          width={360}
          height={90}
          className="w-full h-[90px] block select-none pointer-events-none"
          style={{ imageRendering: 'auto' }}
          onContextMenu={(e) => e.preventDefault()}
          draggable={false}
        />
        <button
          type="button"
          onClick={regenerate}
          disabled={isLocked}
          className="absolute top-2 left-2 p-1.5 rounded-lg bg-background/80 hover:bg-background text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30"
          title="رمز جديد"
        >
          <RefreshCw className="w-3.5 h-3.5" />
        </button>

        {attempts >= 3 && (
          <div className="absolute top-2 right-2">
            <ShieldAlert className="w-4 h-4 text-destructive animate-pulse" />
          </div>
        )}

        {isLocked && (
          <div className="absolute inset-0 bg-black/60 flex items-center justify-center backdrop-blur-sm">
            <div className="text-center">
              <Lock className="w-6 h-6 text-destructive mx-auto mb-1" />
              <p className="text-xs text-white font-bold">مقفل لمدة {lockTimer} ثانية</p>
            </div>
          </div>
        )}
      </div>

      {/* Honeypot */}
      <div className="absolute -left-[9999px] opacity-0 h-0 overflow-hidden" aria-hidden="true">
        <input
          type="text"
          tabIndex={-1}
          autoComplete="off"
          value={honeypot}
          onChange={(e) => setHoneypot(e.target.value)}
          name="website_url"
        />
      </div>

      <div className="flex gap-2">
        <Input
          value={input}
          onChange={handleInputChange}
          placeholder="أدخل الأحرف أعلاه"
          disabled={status === 'correct' || isLocked}
          className="bg-card border-border h-10 text-foreground font-mono tracking-widest text-center text-sm"
          dir="ltr"
          maxLength={5}
          autoComplete="off"
          spellCheck={false}
          onKeyDown={(e) => e.key === 'Enter' && handleVerify()}
          onPaste={(e) => e.preventDefault()}
          onCopy={(e) => e.preventDefault()}
          onCut={(e) => e.preventDefault()}
        />
        <Button
          type="button"
          onClick={handleVerify}
          disabled={!input || status === 'correct' || isLocked}
          size="sm"
          className={`h-10 px-4 font-bold transition-all ${
            status === 'correct'
              ? 'bg-green-600 text-white'
              : status === 'wrong'
              ? 'bg-destructive text-destructive-foreground animate-shake'
              : 'bg-primary text-primary-foreground'
          }`}
        >
          {status === 'correct' ? '✓' : status === 'wrong' ? '✗' : 'تحقق'}
        </Button>
      </div>

      <p className="text-[9px] text-muted-foreground/60 text-center">
        الأحرف حساسة لحالتها — أدخل ما تراه بالضبط
      </p>

      {status === 'wrong' && (
        <p className="text-xs text-destructive font-bold animate-in fade-in text-center">
          خطأ — جاري تحديث الرمز ({attempts} محاولة)
        </p>
      )}
      {status === 'correct' && (
        <p className="text-xs text-green-500 font-bold animate-in fade-in text-center">✓ تم التحقق بنجاح</p>
      )}
    </div>
  );
};

export default CaptchaText;