import { createSignal, onCleanup, onMount } from 'solid-js'; import { AuthService } from '@/client'; import type { ApiResponse_CaptchaResponse } from '@/client'; export function useCaptcha() { const [captcha, setCaptcha] = createSignal({ image: '', rsaKey: null as string | null }); const [captchaError, setCaptchaError] = createSignal(''); const [captchaLoading, setCaptchaLoading] = createSignal(false); let requestId = 0; let disposed = false; const refresh = async (): Promise => { const currentRequest = ++requestId; setCaptchaLoading(true); setCaptchaError(''); try { const res: ApiResponse_CaptchaResponse = await AuthService.authGetCaptcha({ w: 200, h: 60, dark: false, rsa: true, }); if (disposed || currentRequest !== requestId) return false; setCaptcha({ image: res.data.base64, rsaKey: res.data.rsa?.public_key ?? null, }); return true; } catch { if (!disposed && currentRequest === requestId) { setCaptcha({ image: '', rsaKey: null }); setCaptchaError('Captcha failed to load. Please refresh and try again.'); } return false; } finally { if (!disposed && currentRequest === requestId) setCaptchaLoading(false); } }; onMount(() => { void refresh(); }); onCleanup(() => { disposed = true; requestId++; }); return { captcha, captchaError, captchaLoading, refresh }; }