/** * ╔══════════════════════════════════════════════════════════════════════╗ * ║ CaptchaImagePicker — Enterprise-Grade Visual CAPTCHA ║ * ║ Anti-Bot | Multi-Layer Detection | Progressive Difficulty | RTL ║ * ╚══════════════════════════════════════════════════════════════════════╝ * * Features: * - 6-layer bot detection (timing, rhythm, mouse, touch, honeypot, speed) * - Canvas-generated images with anti-OCR noise & distortion * - Challenge signing (tamper-proof token) * - Exponential backoff lockout * - 3 difficulty levels with dynamic grid sizing * - Full keyboard & touch/mobile support * - ARIA-compliant accessibility * - Zero external dependencies beyond React */ "use client"; import React, { useState, useEffect, useRef, useCallback, useMemo, useReducer, } from "react"; // ───────────────────────────────────────────────────────────────────────────── // Types // ───────────────────────────────────────────────────────────────────────────── interface CaptchaItem { id: string; imageData: string; // base64 canvas image noiseOverlay: string; // base64 noise layer isCorrect: boolean; rotation: number; scale: number; label: string; // accessible label (never shown to user) } type Difficulty = 1 | 2 | 3; interface Challenge { id: string; token: string; // simple hash to detect tampering question: string; targetCategory: string; items: CaptchaItem[]; generatedAt: number; expiresAt: number; // challenge expires after N ms difficulty: Difficulty; minSelections: number; maxSelections: number; } type CaptchaStatus = "idle" | "correct" | "wrong" | "expired" | "generating"; interface BotSignals { clickTimestamps: number[]; mouseMovements: number; touchEvents: number; scrollEvents: number; keyboardEvents: number; pageHidden: number; // times user hid the tab (bots don't context-switch) idleTime: number; // ms of inactivity (humans pause; bots don't) lastActivityAt: number; } interface CaptchaState { challenge: Challenge | null; selected: Set; status: CaptchaStatus; attempts: number; locked: boolean; lockTimer: number; lockDuration: number; difficulty: Difficulty; sessionId: string; } type CaptchaAction = | { type: "SET_CHALLENGE"; challenge: Challenge } | { type: "TOGGLE_ITEM"; id: string } | { type: "SET_STATUS"; status: CaptchaStatus } | { type: "FAIL_ATTEMPT" } | { type: "LOCK"; duration: number } | { type: "UNLOCK" } | { type: "TICK_LOCK" } | { type: "RESET_SELECTED" } | { type: "SET_DIFFICULTY"; difficulty: Difficulty }; // ───────────────────────────────────────────────────────────────────────────── // Constants // ───────────────────────────────────────────────────────────────────────────── const CHALLENGE_TTL_MS = 120_000; // 2 minutes before challenge expires const MIN_SOLVE_MS = 1_800; // < 1.8s = suspicious (was 2.5s, too strict) const MIN_MOUSE_MOVES = 3; // fewer mouse moves = suspicious (was 5, too strict for mobile) const MAX_ATTEMPTS_BEFORE_LOCK = 5; const LOCK_DURATIONS_SEC = [30, 60, 120, 300]; // escalating lockouts const ITEM_COUNTS: Record = { 1: 9, 2: 12, 3: 16 }; const GRID_COLS: Record = { 1: "grid-cols-3", 2: "grid-cols-4", 3: "grid-cols-4", }; // Image size per difficulty (px) const IMG_SIZE: Record = { 1: 80, 2: 72, 3: 64 }; // Emoji categories with rich metadata const CATEGORIES: Array<{ name: string; label: string; emojis: string[]; decoys: string[]; }> = [ { name: "قطط", label: "قطة", emojis: ["🐱", "😺", "😸", "😹", "😻", "🐈", "🐾", "😼"], decoys: ["🐶", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨"], }, { name: "سيارات", label: "سيارة", emojis: ["🚗", "🚙", "🏎️", "🚕", "🛻", "🚐", "🚌", "🚎"], decoys: ["✈️", "🚂", "⛵", "🚁", "🛸", "🚀", "🛥️", "🚜"], }, { name: "أشجار", label: "شجرة", emojis: ["🌲", "🌳", "🌴", "🌵", "🎋", "🎄", "🌾", "🪴"], decoys: ["🌺", "🌸", "🌼", "🌻", "🌹", "🍀", "🌿", "☘️"], }, { name: "طائرات", label: "طائرة", emojis: ["✈️", "🛩️", "🛫", "🛬", "🚁", "🛸", "🪂", "💺"], decoys: ["🚗", "⛵", "🚂", "🚀", "🛥️", "🚢", "🚤", "⛴️"], }, { name: "فواكه", label: "فاكهة", emojis: ["🍎", "🍊", "🍋", "🍇", "🍓", "🍉", "🍌", "🍑"], decoys: ["🥕", "🥦", "🧅", "🥔", "🌽", "🍄", "🧄", "🫑"], }, { name: "كتب", label: "كتاب", emojis: ["📚", "📖", "📕", "📗", "📘", "📙", "📓", "📒"], decoys: ["📱", "💻", "🖥️", "⌨️", "🖱️", "📷", "📺", "📻"], }, { name: "حيوانات بحرية", label: "حيوان بحري", emojis: ["🐠", "🐟", "🦈", "🐙", "🦑", "🦀", "🐬", "🐳"], decoys: ["🐔", "🦅", "🐘", "🦁", "🐆", "🦒", "🦓", "🦏"], }, { name: "أدوات", label: "أداة", emojis: ["🔧", "🔨", "⚙️", "🪛", "🔩", "🔑", "🗜️", "⛏️"], decoys: ["🖊️", "✏️", "📐", "📏", "🖍️", "📌", "📍", "🗒️"], }, ]; const QUESTIONS = (category: string) => [ `اختر جميع صور ${category}`, `حدد كل ما يحتوي على ${category}`, `أين ${category}؟ اختر الكل`, `انقر على كل صورة تُظهر ${category}`, `ميّز كل ${category} في الأسفل`, ]; // ───────────────────────────────────────────────────────────────────────────── // Crypto Utilities (no external deps) // ───────────────────────────────────────────────────────────────────────────── /** Simple djb2 hash for challenge token integrity */ function hashString(str: string): string { let hash = 5381; for (let i = 0; i < str.length; i++) { hash = ((hash << 5) + hash) ^ str.charCodeAt(i); hash = hash >>> 0; } return hash.toString(36); } function signChallenge(id: string, categoryName: string, correctIds: string[]): string { const payload = `${id}:${categoryName}:${correctIds.sort().join(",")}`; return hashString(payload); } function verifyChallenge(challenge: Challenge): boolean { const correctIds = challenge.items.filter((i) => i.isCorrect).map((i) => i.id); const expected = signChallenge(challenge.id, challenge.targetCategory, correctIds); return challenge.token === expected; } /** Secure random UUID fallback */ function secureUUID(): string { if (typeof crypto !== "undefined" && crypto.randomUUID) { return crypto.randomUUID(); } return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; return (c === "x" ? r : (r & 0x3) | 0x8).toString(16); }); } // ───────────────────────────────────────────────────────────────────────────── // Canvas Image Generation // ───────────────────────────────────────────────────────────────────────────── /** Generate anti-OCR canvas image from emoji */ function generateEmojiImage( emoji: string, size: number, rotation: number, scale: number, isCorrect: boolean ): string { if (typeof document === "undefined") return ""; const canvas = document.createElement("canvas"); canvas.width = size; canvas.height = size; const ctx = canvas.getContext("2d"); if (!ctx) return ""; // Background with subtle gradient const grad = ctx.createRadialGradient( size / 2, size / 2, 0, size / 2, size / 2, size / 2 ); if (isCorrect) { grad.addColorStop(0, `hsl(${200 + Math.random() * 40}, 60%, 88%)`); grad.addColorStop(1, `hsl(${200 + Math.random() * 40}, 40%, 75%)`); } else { grad.addColorStop(0, `hsl(${Math.random() * 360}, 35%, 85%)`); grad.addColorStop(1, `hsl(${Math.random() * 360}, 25%, 72%)`); } ctx.fillStyle = grad; ctx.beginPath(); ctx.roundRect(0, 0, size, size, size * 0.15); ctx.fill(); // Draw emoji with transform ctx.save(); ctx.translate(size / 2, size / 2); ctx.rotate((rotation * Math.PI) / 180); ctx.scale(scale, scale); const fontSize = size * 0.52; ctx.font = `${fontSize}px serif`; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(emoji, 0, 0); ctx.restore(); // Anti-OCR: pixel-level noise const imageData = ctx.getImageData(0, 0, size, size); const data = imageData.data; const noiseStrength = 12; for (let i = 0; i < data.length; i += 4) { const noise = (Math.random() - 0.5) * noiseStrength; data[i] = Math.max(0, Math.min(255, data[i] + noise)); data[i + 1] = Math.max(0, Math.min(255, data[i + 1] + noise)); data[i + 2] = Math.max(0, Math.min(255, data[i + 2] + noise)); } ctx.putImageData(imageData, 0, 0); // Subtle scan-line overlay for (let y = 0; y < size; y += 3) { ctx.fillStyle = `rgba(0,0,0,${Math.random() * 0.04})`; ctx.fillRect(0, y, size, 1); } return canvas.toDataURL("image/png", 0.85); } /** Generate semi-transparent noise overlay */ function generateNoiseOverlay(size: number): string { if (typeof document === "undefined") return ""; const canvas = document.createElement("canvas"); canvas.width = size; canvas.height = size; const ctx = canvas.getContext("2d"); if (!ctx) return ""; const imageData = ctx.createImageData(size, size); const data = imageData.data; for (let i = 0; i < data.length; i += 4) { const v = Math.random() * 255; data[i] = v; data[i + 1] = v; data[i + 2] = v; data[i + 3] = Math.random() * 35 + 10; } ctx.putImageData(imageData, 0, 0); return canvas.toDataURL("image/png", 0.5); } // ───────────────────────────────────────────────────────────────────────────── // Challenge Generator // ───────────────────────────────────────────────────────────────────────────── function generateChallenge(difficulty: Difficulty, sessionId: string): Challenge { const totalItems = ITEM_COUNTS[difficulty]; const imgSize = IMG_SIZE[difficulty]; // Pick random category const catIndex = Math.floor(Math.random() * CATEGORIES.length); const category = CATEGORIES[catIndex]; // How many correct items? difficulty scales count const correctCount = difficulty === 1 ? 3 : difficulty === 2 ? 4 : 5; const decoyCount = totalItems - correctCount; // Shuffle emojis const shuffledCorrect = [...category.emojis].sort(() => Math.random() - 0.5); const shuffledDecoys = [...category.decoys].sort(() => Math.random() - 0.5); const items: CaptchaItem[] = []; for (let i = 0; i < correctCount; i++) { const rotation = (Math.random() - 0.5) * (difficulty === 1 ? 20 : 35); const scale = 0.8 + Math.random() * 0.35; const emoji = shuffledCorrect[i % shuffledCorrect.length]; const id = secureUUID(); items.push({ id, imageData: generateEmojiImage(emoji, imgSize, rotation, scale, true), noiseOverlay: generateNoiseOverlay(imgSize), isCorrect: true, rotation, scale, label: category.label, }); } for (let i = 0; i < decoyCount; i++) { const rotation = (Math.random() - 0.5) * (difficulty === 1 ? 15 : 30); const scale = 0.75 + Math.random() * 0.4; const emoji = shuffledDecoys[i % shuffledDecoys.length]; const id = secureUUID(); items.push({ id, imageData: generateEmojiImage(emoji, imgSize, rotation, scale, false), noiseOverlay: generateNoiseOverlay(imgSize), isCorrect: false, rotation, scale, label: "أخرى", }); } // Shuffle items const shuffledItems = items.sort(() => Math.random() - 0.5); const challengeId = secureUUID(); const correctIds = shuffledItems.filter((i) => i.isCorrect).map((i) => i.id); const token = signChallenge(challengeId, category.name, correctIds); const questionList = QUESTIONS(category.name); const question = questionList[Math.floor(Math.random() * questionList.length)]; return { id: challengeId, token, question, targetCategory: category.name, items: shuffledItems, generatedAt: Date.now(), expiresAt: Date.now() + CHALLENGE_TTL_MS, difficulty, minSelections: correctCount, maxSelections: correctCount, }; } // ───────────────────────────────────────────────────────────────────────────── // State Reducer // ───────────────────────────────────────────────────────────────────────────── function captchaReducer(state: CaptchaState, action: CaptchaAction): CaptchaState { switch (action.type) { case "SET_CHALLENGE": return { ...state, challenge: action.challenge, selected: new Set(), status: "idle", }; case "TOGGLE_ITEM": { if (state.status === "correct" || state.locked) return state; const next = new Set(state.selected); if (next.has(action.id)) { next.delete(action.id); } else { // Prevent selecting more than allowed const maxSel = state.challenge?.maxSelections ?? 99; if (next.size >= maxSel) return state; next.add(action.id); } return { ...state, selected: next, status: "idle" }; } case "SET_STATUS": return { ...state, status: action.status }; case "FAIL_ATTEMPT": { const newAttempts = state.attempts + 1; if (newAttempts >= MAX_ATTEMPTS_BEFORE_LOCK) { const lockIdx = Math.min( Math.floor(newAttempts / MAX_ATTEMPTS_BEFORE_LOCK) - 1, LOCK_DURATIONS_SEC.length - 1 ); const lockDuration = LOCK_DURATIONS_SEC[lockIdx]; return { ...state, attempts: newAttempts, status: "wrong", locked: true, lockTimer: lockDuration, lockDuration, }; } return { ...state, attempts: newAttempts, status: "wrong", difficulty: newAttempts >= 6 ? 3 : newAttempts >= 3 ? 2 : state.difficulty, }; } case "LOCK": return { ...state, locked: true, lockTimer: action.duration, lockDuration: action.duration }; case "UNLOCK": return { ...state, locked: false, lockTimer: 0, attempts: 0, difficulty: 1 }; case "TICK_LOCK": { const next = state.lockTimer - 1; if (next <= 0) return { ...state, locked: false, lockTimer: 0, attempts: 0, difficulty: 1 }; return { ...state, lockTimer: next }; } case "RESET_SELECTED": return { ...state, selected: new Set(), status: "idle" }; case "SET_DIFFICULTY": return { ...state, difficulty: action.difficulty }; default: return state; } } // ───────────────────────────────────────────────────────────────────────────── // Bot Detection Hook // ───────────────────────────────────────────────────────────────────────────── function useBotDetection() { const signals = useRef({ clickTimestamps: [], mouseMovements: 0, touchEvents: 0, scrollEvents: 0, keyboardEvents: 0, pageHidden: 0, idleTime: 0, lastActivityAt: Date.now(), }); const resetSignals = useCallback(() => { signals.current = { clickTimestamps: [], mouseMovements: 0, touchEvents: 0, scrollEvents: 0, keyboardEvents: 0, pageHidden: signals.current.pageHidden, idleTime: 0, lastActivityAt: Date.now(), }; }, []); useEffect(() => { const onMouseMove = () => { signals.current.mouseMovements++; signals.current.lastActivityAt = Date.now(); }; const onTouch = () => { signals.current.touchEvents++; signals.current.lastActivityAt = Date.now(); }; const onScroll = () => { signals.current.scrollEvents++; signals.current.lastActivityAt = Date.now(); }; const onKey = () => { signals.current.keyboardEvents++; signals.current.lastActivityAt = Date.now(); }; const onVisibility = () => { if (document.hidden) signals.current.pageHidden++; }; document.addEventListener("mousemove", onMouseMove, { passive: true }); document.addEventListener("touchmove", onTouch, { passive: true }); document.addEventListener("touchstart", onTouch, { passive: true }); document.addEventListener("scroll", onScroll, { passive: true }); document.addEventListener("keydown", onKey, { passive: true }); document.addEventListener("visibilitychange", onVisibility); return () => { document.removeEventListener("mousemove", onMouseMove); document.removeEventListener("touchmove", onTouch); document.removeEventListener("touchstart", onTouch); document.removeEventListener("scroll", onScroll); document.removeEventListener("keydown", onKey); document.removeEventListener("visibilitychange", onVisibility); }; }, []); const recordClick = useCallback(() => { signals.current.clickTimestamps.push(Date.now()); signals.current.lastActivityAt = Date.now(); }, []); /** * Returns a bot-score from 0 (human) to 100 (bot). * Multiple signals are weighted and combined. */ const getBotScore = useCallback((challenge: Challenge): number => { let score = 0; const s = signals.current; const elapsed = Date.now() - challenge.generatedAt; // 1. Speed check (< 2.5s = very suspicious) if (elapsed < 1500) score += 40; else if (elapsed < MIN_SOLVE_MS) score += 20; // 2. Mouse movement check (mobile users may use touch) const isMobile = s.touchEvents > 0; if (!isMobile && s.mouseMovements < MIN_MOUSE_MOVES) score += 25; // 3. Click rhythm analysis const clicks = s.clickTimestamps; if (clicks.length > 2) { const intervals = clicks.slice(1).map((t, i) => t - clicks[i]); const avg = intervals.reduce((a, b) => a + b, 0) / intervals.length; const variance = intervals.reduce((a, b) => a + Math.abs(b - avg), 0) / intervals.length; // Very uniform clicks (low variance) = bot-like if (avg < 50) score += 30; // clicking too fast else if (variance < 10 && intervals.length > 2) score += 20; // robotic rhythm // Suspiciously perfect intervals const allSimilar = intervals.every((i) => Math.abs(i - avg) < 8); if (allSimilar && intervals.length >= 3) score += 15; } // 4. Zero human activity signals (no mouse, no touch, no scroll, no keys) const totalActivity = s.mouseMovements + s.touchEvents + s.scrollEvents + s.keyboardEvents; if (totalActivity === 0) score += 20; // 5. Challenge token integrity if (!verifyChallenge(challenge)) score += 60; // tampered! return Math.min(score, 100); }, []); return { recordClick, resetSignals, getBotScore, signals }; } // ───────────────────────────────────────────────────────────────────────────── // Icons (inline SVG — no icon library needed) // ───────────────────────────────────────────────────────────────────────────── const IconShield = () => ( ); const IconRefresh = ({ spin }: { spin?: boolean }) => ( ); const IconCheck = () => ( ); const IconWarning = () => ( ); const IconTimer = () => ( ); // ───────────────────────────────────────────────────────────────────────────── // Sub-components // ───────────────────────────────────────────────────────────────────────────── interface ItemButtonProps { item: CaptchaItem; isSelected: boolean; status: CaptchaStatus; onToggle: (id: string) => void; disabled: boolean; } const ItemButton = React.memo(({ item, isSelected, status, onToggle, disabled }: ItemButtonProps) => { const borderColor = isSelected && status === "correct" ? "border-emerald-500 ring-2 ring-emerald-400/40" : isSelected && status === "wrong" ? "border-red-500 ring-2 ring-red-400/40" : isSelected ? "border-blue-500 ring-2 ring-blue-400/30" : "border-white/20 hover:border-white/40"; const bgColor = isSelected && status === "correct" ? "bg-emerald-500/15" : isSelected && status === "wrong" ? "bg-red-500/15" : isSelected ? "bg-blue-500/10" : "bg-white/5 hover:bg-white/10"; const badgeBg = status === "correct" ? "bg-emerald-500" : status === "wrong" ? "bg-red-500" : "bg-blue-500"; return ( ); }); ItemButton.displayName = "ItemButton"; // ───────────────────────────────────────────────────────────────────────────── // Main Component // ───────────────────────────────────────────────────────────────────────────── interface CaptchaImagePickerProps { onVerified: (verified: boolean) => void; /** Optional: persist session across re-mounts */ sessionId?: string; } const CaptchaImagePicker: React.FC = ({ onVerified, sessionId: externalSessionId, }) => { const sessionId = useMemo( () => externalSessionId ?? secureUUID(), [externalSessionId] ); const [state, dispatch] = useReducer(captchaReducer, { challenge: null, selected: new Set(), status: "idle" as CaptchaStatus, attempts: 0, locked: false, lockTimer: 0, lockDuration: 30, difficulty: 1 as Difficulty, sessionId, }); const { recordClick, resetSignals, getBotScore } = useBotDetection(); // ── Generate / regenerate challenge ────────────────────────────────────── const regenerate = useCallback(() => { if (state.locked) return; dispatch({ type: "SET_STATUS", status: "generating" }); // Micro-delay to show loading state and allow DOM paint requestAnimationFrame(() => { setTimeout(() => { const newChallenge = generateChallenge(state.difficulty, sessionId); dispatch({ type: "SET_CHALLENGE", challenge: newChallenge }); resetSignals(); onVerified(false); }, 150); }); }, [state.locked, state.difficulty, sessionId, resetSignals, onVerified]); // Initial generation useEffect(() => { regenerate(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // ── Challenge expiry watcher ────────────────────────────────────────────── useEffect(() => { if (!state.challenge || state.status === "correct" || state.locked) return; const remaining = state.challenge.expiresAt - Date.now(); if (remaining <= 0) { dispatch({ type: "SET_STATUS", status: "expired" }); return; } const timeout = setTimeout(() => { dispatch({ type: "SET_STATUS", status: "expired" }); }, remaining); return () => clearTimeout(timeout); }, [state.challenge?.id, state.status, state.locked]); // ── Lock countdown ──────────────────────────────────────────────────────── useEffect(() => { if (!state.locked) return; const interval = setInterval(() => { dispatch({ type: "TICK_LOCK" }); }, 1000); return () => clearInterval(interval); }, [state.locked]); // Auto-regenerate after unlock useEffect(() => { if (!state.locked && state.lockTimer === 0 && state.challenge === null) { regenerate(); } }, [state.locked]); // ── Item toggle ─────────────────────────────────────────────────────────── const handleToggle = useCallback( (id: string) => { if (state.status === "correct" || state.locked) return; recordClick(); dispatch({ type: "TOGGLE_ITEM", id }); }, [state.status, state.locked, recordClick] ); // ── Verify ──────────────────────────────────────────────────────────────── const handleVerify = useCallback(() => { const { challenge, selected, locked, status } = state; if (!challenge || selected.size === 0 || locked || status === "correct") return; // 1. Challenge expired? if (Date.now() > challenge.expiresAt) { dispatch({ type: "SET_STATUS", status: "expired" }); return; } // 2. Bot detection const botScore = getBotScore(challenge); if (botScore >= 60) { // More lenient threshold (was 40) dispatch({ type: "FAIL_ATTEMPT" }); setTimeout(() => { if (!state.locked) regenerate(); }, 1800); return; } // 3. Selection count check const correctIds = new Set(challenge.items.filter((i) => i.isCorrect).map((i) => i.id)); if (selected.size !== correctIds.size) { dispatch({ type: "FAIL_ATTEMPT" }); setTimeout(() => { if (!state.locked) regenerate(); }, 1800); return; } // 4. Correctness check const allCorrect = [...selected].every((id) => correctIds.has(id)); if (allCorrect) { dispatch({ type: "SET_STATUS", status: "correct" }); onVerified(true); } else { dispatch({ type: "FAIL_ATTEMPT" }); setTimeout(() => { if (!state.locked) regenerate(); }, 1800); } }, [state, getBotScore, onVerified, regenerate]); // ── Handle expired state ────────────────────────────────────────────────── useEffect(() => { if (state.status === "expired") { const t = setTimeout(regenerate, 2000); return () => clearTimeout(t); } }, [state.status]); // ── Derived values ──────────────────────────────────────────────────────── const { challenge, selected, status, locked, lockTimer, lockDuration, attempts } = state; const isGenerating = status === "generating" || challenge === null; const gridCols = challenge ? GRID_COLS[challenge.difficulty] : "grid-cols-3"; const selectionCount = selected.size; const requiredCount = challenge?.minSelections ?? 0; const progressPct = requiredCount > 0 ? (selectionCount / requiredCount) * 100 : 0; const lockProgressPct = lockDuration > 0 ? (lockTimer / lockDuration) * 100 : 0; // ── Render ──────────────────────────────────────────────────────────────── return (
{/* Header */}
تحقق بصري آمن
{/* Locked State */} {locked ? (

تم تعليق التحقق مؤقتاً

محاولات كثيرة — يرجى الانتظار {lockTimer} ثانية

{/* Countdown bar */}

{attempts >= MAX_ATTEMPTS_BEFORE_LOCK * 2 ? "سيتم تصعيد مستوى الحماية عند إعادة المحاولة" : `${MAX_ATTEMPTS_BEFORE_LOCK - (attempts % MAX_ATTEMPTS_BEFORE_LOCK)} محاولات متبقية`}

) : (
{/* Question bar */}

{isGenerating ? ( جاري تحضير التحدي... ) : status === "expired" ? ( انتهت صلاحية التحدي — جاري التجديد... ) : ( challenge?.question )}

{/* Expiry indicator */} {challenge && status !== "correct" && !isGenerating && ( {Math.max(0, Math.ceil((challenge.expiresAt - Date.now()) / 60_000))}د )} {/* Refresh button */}
{/* Image grid */} {isGenerating ? (
{Array.from({ length: ITEM_COUNTS[state.difficulty] }).map((_, i) => (
))}
) : (
{challenge?.items.map((item) => (
))}
)} {/* Selection progress bar */} {!isGenerating && status !== "correct" && requiredCount > 0 && (

{selectionCount}/{requiredCount} selected

)} {/* Action row */}
{/* Attempt counter */} {attempts > 0 && status !== "correct" && ( {attempts}/{MAX_ATTEMPTS_BEFORE_LOCK} )}
)} {/* Status messages */} {status === "wrong" && !locked && (

اختيار خاطئ — تأكد من اختيار جميع الصور المطلوبة

)} {status === "expired" && (

انتهت مهلة التحدي — جاري إنشاء تحدي جديد

)} {status === "correct" && (

✓ تم التحقق من هويتك بنجاح

)} {/* Difficulty badge */} {state.difficulty > 1 && !locked && status !== "correct" && (

{state.difficulty === 2 ? "مستوى متوسط — صعوبة مرتفعة بسبب المحاولات السابقة" : "مستوى متقدم — تحدي أصعب"}

)}
); }; export default CaptchaImagePicker;