'use client'; import { useState, useCallback, useRef, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import Script from 'next/script'; import { createClient } from '@/lib/supabase/client'; import Header from '@/components/Header'; declare global { interface Window { turnstile?: { render: (container: string | HTMLElement, options: { sitekey: string; callback: (token: string) => void; 'expired-callback': () => void; 'error-callback': () => void; theme?: 'light' | 'dark' | 'auto'; language?: string; }) => string; reset: (widgetId: string) => void; }; } } export default function AdminLoginPage() { const router = useRouter(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [captchaToken, setCaptchaToken] = useState(''); const [turnstileReady, setTurnstileReady] = useState(false); const turnstileWidgetId = useRef(null); const turnstileContainerRef = useRef(null); const renderTurnstile = useCallback(() => { if (window.turnstile && turnstileContainerRef.current && !turnstileWidgetId.current) { turnstileWidgetId.current = window.turnstile.render(turnstileContainerRef.current, { sitekey: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || '', callback: (token: string) => setCaptchaToken(token), 'expired-callback': () => setCaptchaToken(''), 'error-callback': () => setCaptchaToken(''), theme: 'light', language: 'de', }); } }, []); useEffect(() => { if (turnstileReady) { const timer = setTimeout(renderTurnstile, 100); return () => clearTimeout(timer); } }, [turnstileReady, renderTurnstile]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); if (!captchaToken) { setError('Bitte bestätigen Sie das CAPTCHA.'); return; } setLoading(true); // CAPTCHA serverseitig verifizieren try { const verifyRes = await fetch('/api/verify-captcha', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ captchaToken }), }); if (!verifyRes.ok) { setError('CAPTCHA-Verifizierung fehlgeschlagen. Bitte versuchen Sie es erneut.'); setCaptchaToken(''); if (turnstileWidgetId.current && window.turnstile) { window.turnstile.reset(turnstileWidgetId.current); } setLoading(false); return; } } catch { setError('Verbindungsfehler. Bitte versuchen Sie es erneut.'); setLoading(false); return; } const supabase = createClient(); const { error: authError } = await supabase.auth.signInWithPassword({ email, password, }); if (authError) { setError('Ungültige Anmeldedaten. Bitte versuchen Sie es erneut.'); setCaptchaToken(''); if (turnstileWidgetId.current && window.turnstile) { window.turnstile.reset(turnstileWidgetId.current); } setLoading(false); return; } router.push('/admin/dashboard'); }; return (