// OAuthCallbackView - Handles OAuth callback with token extraction

function OAuthCallbackView() {
    const { login } = useAuth();
    const [error, setError] = React.useState('');

    React.useEffect(() => {
        const handleCallback = async () => {
            // Get URL parameters from hash (after #/auth/callback?)
            const hash = window.location.hash;
            const queryStart = hash.indexOf('?');
            const queryString = queryStart >= 0 ? hash.substring(queryStart + 1) : '';
            const urlParams = new URLSearchParams(queryString);

            const accessToken = urlParams.get('access_token');
            const refreshToken = urlParams.get('refresh_token');
            const errorParam = urlParams.get('error');

            if (errorParam) {
                setError(errorParam);
                // Redirect to login after showing error
                setTimeout(() => {
                    window.location.hash = '#/login';
                }, 3000);
                return;
            }

            if (accessToken && refreshToken) {
                // Store tokens and fetch user data
                try {
                    localStorage.setItem('rosa_access_token', accessToken);
                    localStorage.setItem('rosa_refresh_token', refreshToken);

                    // Fetch user data
                    const response = await fetch('/api/auth/me', {
                        headers: { 'Authorization': `Bearer ${accessToken}` }
                    });

                    if (response.ok) {
                        const userData = await response.json();
                        localStorage.setItem('rosa_user', JSON.stringify(userData));

                        // Redirect to welcome page
                        window.location.hash = '#/welcome';
                        window.location.reload();
                    } else {
                        setError('Impossibile recuperare i dati utente');
                        setTimeout(() => {
                            window.location.hash = '#/login';
                        }, 3000);
                    }
                } catch (err) {
                    console.error('OAuth callback error:', err);
                    setError('Errore durante l\'autenticazione');
                    setTimeout(() => {
                        window.location.hash = '#/login';
                    }, 3000);
                }
            } else {
                setError('Token mancanti nella risposta OAuth');
                setTimeout(() => {
                    window.location.hash = '#/login';
                }, 3000);
            }
        };

        handleCallback();
    }, []);

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
            <div className="text-center">
                {error ? (
                    <>
                        <div className="inline-flex items-center justify-center w-16 h-16 bg-red-500/10 rounded-full mb-4">
                            <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <h2 className="text-xl font-semibold text-white mb-2">Errore di autenticazione</h2>
                        <p className="text-slate-400">{error}</p>
                        <p className="text-slate-500 text-sm mt-4">Reindirizzamento alla pagina di login...</p>
                    </>
                ) : (
                    <>
                        <div className="w-16 h-16 border-4 border-brand-200 border-t-brand-500 rounded-full animate-spin mx-auto mb-4"></div>
                        <h2 className="text-xl font-semibold text-white mb-2">Completamento autenticazione...</h2>
                        <p className="text-slate-400">Attendere prego</p>
                    </>
                )}
            </div>
        </div>
    );
}

window.OAuthCallbackView = OAuthCallbackView;
