import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { authStorage } from "@/lib/authStorage";
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

/**
 * ForceLogout - Hidden endpoint for completely clearing auth session
 * Access via: /force-logout
 * Not linked anywhere in the UI - for manual navigation only
 */
const ForceLogout = () => {
  useDocumentTitle('Signing Out');
  const navigate = useNavigate();

  useEffect(() => {
    const performFullLogout = async () => {
      console.log('[ForceLogout] Starting complete auth cleanup...');
      
      try {
        // 1. Sign out from Supabase
        console.log('[ForceLogout] Signing out from Supabase...');
        await supabase.auth.signOut();
        
        // 2. Clear all auth-related storage
        console.log('[ForceLogout] Clearing all auth storage...');
        authStorage.clearAll();
        
        // 3. Brief delay to ensure cleanup completes
        await new Promise(resolve => setTimeout(resolve, 500));
        
        console.log('[ForceLogout] ✓ Auth cleanup complete, redirecting to home...');
        
        // 4. Redirect to home page
        navigate('/', { replace: true });
      } catch (error) {
        console.error('[ForceLogout] Error during logout:', error);
        // Still redirect even if there's an error
        navigate('/', { replace: true });
      }
    };

    performFullLogout();
  }, [navigate]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-background">
      <div className="text-center space-y-4">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
        <p className="text-lg text-muted-foreground">Clearing session...</p>
        <p className="text-sm text-muted-foreground">You will be redirected shortly.</p>
      </div>
    </div>
  );
};

export default ForceLogout;
