# Redirect Loop Fix

## What Was Fixed

The redirect loop was caused by:
1. Mismatch between localStorage token and cookie token
2. Middleware and AuthGuard both trying to redirect simultaneously
3. Google OAuth callback triggering immediate redirects before token sync

## Changes Made

### 1. Middleware (`middleware.js`)
- Added OAuth callback detection to skip redirect during Google sign-in
- Prevents middleware from redirecting while Google OAuth is completing

### 2. AuthGuard (`auth-guard.js`)
- Added token sync between localStorage and cookie
- Added small delay before redirect to prevent race conditions
- Better logging for debugging

### 3. Auth Hook (`use-auth.js`)
- Added delay after Google login to ensure cookie is set
- Improved cookie settings with Secure flag for HTTPS
- Better token synchronization

### 4. Debug Utilities (`lib/auth-debug.js`)
- Added browser console tools for debugging auth issues

## How to Clear Stuck Auth State

If you get stuck in a redirect loop, open browser console and run:

```javascript
// Check current auth state
window.authDebug.check()

// Sync tokens if mismatched
window.authDebug.sync()

// Clear everything and start fresh
window.authDebug.clear()
// Then refresh the page
```

## Testing Steps

1. Clear browser cookies and localStorage
2. Try logging in with email/password
3. Try logging in with Google
4. Verify no redirect loops occur
5. Check that tokens are synced (use `window.authDebug.check()`)

## If Issues Persist

1. Clear all site data in browser settings
2. Check that `NEXT_PUBLIC_GOOGLE_CLIENT_ID` is set correctly
3. Verify API endpoints are responding correctly
4. Check browser console for auth state logs
