import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from './useAuth';

const Logout: React.FC = () => {
  const navigate = useNavigate();
  const { logout } = useAuth();
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        await logout();
      } catch (err) {
        if (mounted) {
          const msg = err instanceof Error ? err.message : 'Logout fehlgeschlagen';
          setError(msg);
        }
      } finally {
        // Weiter zur Login-Seite, auch wenn Logout-Request fehlschlägt
        navigate('/login', { replace: true });
      }
    })();
    return () => {
      mounted = false;
    };
  }, [logout, navigate]);

  return (
    <div className="flex items-center justify-center h-screen">
      <div className="text-center">
        <h2 className="text-2xl font-bold mb-4">Abmeldung</h2>
        <p>{error ? `Hinweis: ${error}` : 'Sie werden abgemeldet …'}</p>
        <p style={{ marginTop: 16 }}>Falls nichts passiert: <a href="/login">Zur Login-Seite</a></p>
      </div>
    </div>
  );
};

export default Logout;
