Keep in the test files etc:
Make sure all the oauth connections work including using the native yiutube sdk and sending the api calls to backend ot register connetions:
Adapt it to tihs code integration for universal onboarding:
I'll extract all the YouTube SDK settings and OAuth connectors from the UniversalOnboarding component and related files to create a comprehensive export that you can recreate in another app.
Search files...
Read file: src/services/platformAuthService.ts
Read file: src/services/platformAuthService.ts
Read file: src/services/platformAuthService.ts
Read file: src/components/onairos/onboarding/OAuthWebView.tsx
Now I'll create a comprehensive export of all the YouTube SDK settings and OAuth connectors from your UniversalOnboarding system:

## 🚀 Complete OAuth & YouTube SDK Export Package

Here's everything you need to recreate the OAuth system and YouTube SDK integration in another app:

### 📋 **1. Platform Configuration (`platformAuthService.ts`)**

```typescript
/**
 * Platform Authentication Service
 * Handles OAuth flows for different platforms
 */

import { Platform, Linking } from 'react-native';
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';
import AsyncStorage from '@react-native-async-storage/async-storage';

type OAuthConfig = {
  [key: string]: {
    authUrl?: string;
    clientId?: string;
    redirectUri?: string;
    scope?: string;
    responseType?: string;
    hasNativeSDK: boolean;
  };
};

// 🔧 OAUTH CONFIGURATION FOR ALL PLATFORMS
const OAUTH_CONFIG: OAuthConfig = {
  instagram: {
    authUrl: 'https://api.instagram.com/oauth/authorize',
    clientId: 'demo_instagram_client_id', // Replace with your Instagram client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'user_profile,user_media',
    responseType: 'code',
    hasNativeSDK: false
  },
  youtube: {
    authUrl: 'https://api2.onairos.uk/youtube/authorize', // Replace with your backend URL
    clientId: '1030678346906-lovkuds2ouqmoc8eu5qpo98spa6edv4o.apps.googleusercontent.com', // Replace with your Google client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'https://www.googleapis.com/auth/youtube.readonly',
    responseType: 'code',
    hasNativeSDK: true // YouTube uses Google SDK
  },
  reddit: {
    authUrl: 'https://api2.onairos.uk/reddit/authorize', // Replace with your backend URL
    clientId: 'demo_reddit_client_id', // Replace with your Reddit client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'identity,read',
    responseType: 'code',
    hasNativeSDK: false
  },
  pinterest: {
    authUrl: 'https://api2.onairos.uk/pinterest/authorize', // Replace with your backend URL
    clientId: 'demo_pinterest_client_id', // Replace with your Pinterest client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'boards:read,pins:read',
    responseType: 'code',
    hasNativeSDK: false
  },
  facebook: {
    authUrl: 'https://www.facebook.com/v12.0/dialog/oauth',
    clientId: 'demo_facebook_client_id', // Replace with your Facebook client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'public_profile,email',
    responseType: 'code',
    hasNativeSDK: false
  },
  linkedin: {
    authUrl: 'https://api2.onairos.uk/linkedin/authorize', // Replace with your backend URL
    clientId: '', // Backend handles OAuth - no client ID needed
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'openid profile email',
    responseType: 'code',
    hasNativeSDK: false
  },
  gmail: {
    authUrl: 'https://api2.onairos.uk/gmail/authorize', // Replace with your backend URL
    clientId: 'demo_gmail_client_id', // Replace with your Gmail client ID
    redirectUri: 'onairosevents://auth/callback', // Replace with your app scheme
    scope: 'https://www.googleapis.com/auth/gmail.readonly',
    responseType: 'code',
    hasNativeSDK: false
  },
  email: {
    hasNativeSDK: false,
    authUrl: 'https://api2.onairos.uk/email/authorize' // Replace with your backend URL
  }
};

/**
 * Check if the platform has a native SDK
 */
export const hasNativeSDK = (platform: string): boolean => {
  return OAUTH_CONFIG[platform]?.hasNativeSDK || false;
};

/**
 * 🔧 GOOGLE SIGN-IN CONFIGURATION FOR YOUTUBE
 */
const initializeGoogleSignIn = () => {
  GoogleSignin.configure({
    webClientId: '1030678346906-lovkuds2ouqmoc8eu5qpo98spa6edv4o.apps.googleusercontent.com', // Replace with your web client ID
    iosClientId: '1030678346906-lovkuds2ouqmoc8eu5qpo98spa6edv4o.apps.googleusercontent.com', // Replace with your iOS client ID
    scopes: ['https://www.googleapis.com/auth/youtube.readonly'],
    offlineAccess: true, // CRITICAL: This ensures we get refresh tokens
    hostedDomain: '',
    forceCodeForRefreshToken: true, // CRITICAL: Force refresh token on first sign-in
    accountName: '', // Clear to avoid conflicts
  });
};

/**
 * 🔄 REFRESH GOOGLE TOKENS
 */
const refreshGoogleTokens = async (): Promise<{ accessToken: string; idToken?: string } | null> => {
  try {
    console.log('🔄 Attempting to refresh Google tokens...');
    
    const currentUser = await GoogleSignin.getCurrentUser();
    if (!currentUser) {
      console.log('❌ User not signed in to Google, cannot refresh tokens');
      return null;
    }
    
    const tokens = await GoogleSignin.getTokens();
    console.log('✅ Successfully refreshed Google tokens');
    
    return {
      accessToken: tokens.accessToken,
      idToken: tokens.idToken
    };
  } catch (error) {
    console.error('❌ Failed to refresh Google tokens:', error);
    
    // If refresh fails, try to sign in again
    try {
      console.log('🔄 Refresh failed, attempting re-authentication...');
      const userInfo = await GoogleSignin.signIn();
      const tokens = await GoogleSignin.getTokens();
      
      console.log('✅ Re-authentication successful');
      return {
        accessToken: tokens.accessToken,
        idToken: tokens.idToken
      };
    } catch (signInError) {
      console.error('❌ Re-authentication also failed:', signInError);
      return null;
    }
  }
};

/**
 * 🎯 INITIATE OAUTH FLOW FOR WEB-BASED PLATFORMS
 */
export const initiateOAuth = async (platform: string, username: string): Promise<string | null> => {
  try {
    if (platform === 'email') {
      console.log('Email platform selected, returning mock auth URL');
      return 'https://api2.onairos.uk/email/authorize?action=verify'; // Replace with your backend URL
    }
    
    const proxyUrl = `https://api2.onairos.uk/${platform}/authorize`; // Replace with your backend URL
    
    console.log(`Initiating OAuth for ${platform} with username: ${username}`);
    
    const response = await fetch(proxyUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        session: {
          username: username,
          platform: platform,
          timestamp: new Date().toISOString()
        }
      })
    });
    
    if (!response.ok) {
      console.error(`Error initiating OAuth for ${platform}: ${response.status}`);
      return null;
    }
    
    const data = await response.json();
    const urlKey = `${platform}URL`;
    const authUrl = data[urlKey] || data.url || null;
    
    console.log(`Auth URL for ${platform}:`, authUrl);
    return authUrl;
  } catch (error) {
    console.error(`Error initiating OAuth for ${platform}:`, error);
    return null;
  }
};

/**
 * 📱 YOUTUBE NATIVE AUTHENTICATION
 */
export const initiateNativeAuth = async (platform: string, username?: string): Promise<boolean> => {
  if (platform === 'youtube') {
    console.log('🔗 Initiating native Google Sign-In for YouTube');
    try {
      // Initialize Google Sign-In
      initializeGoogleSignIn();
      
      // Check if Google Play Services are available
      await GoogleSignin.hasPlayServices();
      
      // Sign in with Google
      const userInfo = await GoogleSignin.signIn();
      console.log('✅ Google Sign-In successful:', userInfo.data?.user?.email);
      
      // Get access token for API calls
      const tokens = await GoogleSignin.getTokens();
      console.log('🔑 Got Google tokens');
      
      // Get current user info with refresh token
      const currentUser = await GoogleSignin.getCurrentUser();
      console.log('👤 Current user info:', currentUser?.user?.email);
      
      // Extract refresh token from server auth code
      let refreshToken = null;
      if (currentUser?.serverAuthCode) {
        console.log('🔄 Server auth code available for refresh token');
        refreshToken = currentUser.serverAuthCode;
      }
      
      if (!refreshToken) {
        console.warn('⚠️ No refresh token available - token refresh may fail later');
      } else {
        console.log('✅ Refresh token available for YouTube connection');
      }
      
      // Fetch YouTube channel information
      let channelName = 'Unknown Channel';
      let channelId = null;
      try {
        console.log('📺 Fetching YouTube channel information...');
        const channelResponse = await fetch('https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true', {
          headers: {
            'Authorization': `Bearer ${tokens.accessToken}`,
            'Accept': 'application/json'
          }
        });
        
        if (channelResponse.ok) {
          const channelData = await channelResponse.json();
          if (channelData.items && channelData.items.length > 0) {
            channelName = channelData.items[0].snippet.title;
            channelId = channelData.items[0].id;
            console.log('✅ YouTube channel found:', channelName);
          }
        }
      } catch (channelError) {
        console.log('⚠️ Error fetching YouTube channel info:', channelError);
        channelName = userInfo.data?.user?.name || userInfo.data?.user?.email || 'Unknown Channel';
      }
      
      // Get authentication info
      let authToken = await AsyncStorage.getItem('onairos_jwt_token') || 
                     await AsyncStorage.getItem('enoch_token') || 
                     await AsyncStorage.getItem('auth_token');
      const storedUsername = await AsyncStorage.getItem('onairos_username');
      const finalUsername = storedUsername || username || userInfo.data?.user?.email || 'youtube_user';
      
      // Create auth token if needed
      if (!authToken || authToken.trim().length < 20) {
        console.log('🔐 Creating authentication token for YouTube...');
        
        try {
          const fallbackEmail = userInfo.data?.user?.email || `${finalUsername}@youtube.temp`;
          
          // Create user accounts and get JWT token
          const onairosSignupResponse = await fetch('https://api2.onairos.uk/register/enoch', { // Replace with your backend URL
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              email: fallbackEmail,
              username: finalUsername,
              name: finalUsername
            })
          });
          
          if (onairosSignupResponse.ok) {
            const onairosResponseData = await onairosSignupResponse.json();
            
            // Extract token from response
            authToken = onairosResponseData.token || onairosResponseData.data?.token || onairosResponseData.jwt;
            
            if (authToken) {
              // Store tokens
              await AsyncStorage.setItem('onairos_jwt_token', authToken);
              await AsyncStorage.setItem('enoch_token', authToken);
              await AsyncStorage.setItem('auth_token', authToken);
              await AsyncStorage.setItem('onairos_username', onairosResponseData.username || finalUsername);
              
              console.log('✅ Successfully created and stored authentication token');
            }
          }
        } catch (tokenError) {
          console.warn('⚠️ Error creating auth token:', tokenError);
        }
      }
      
      console.log('🔗 Linking YouTube data to user:', finalUsername);
      console.log('📺 YouTube channel name:', channelName);
      
      // Send tokens to backend for YouTube data processing
      const backendResponse = await fetch('https://api2.onairos.uk/youtube/native-auth', { // Replace with your backend URL
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(authToken && { 'Authorization': `Bearer ${authToken}` })
        },
        body: JSON.stringify({
          session: {
            username: finalUsername,
            platform: 'youtube',
            timestamp: new Date().toISOString(),
            channelName: channelName,
            channelId: channelId
          },
          googleUser: userInfo.data?.user,
          accessToken: tokens.accessToken,
          idToken: tokens.idToken,
          refreshToken: refreshToken, // CRITICAL: Include refresh token
          serverAuthCode: currentUser?.serverAuthCode,
          userAccountInfo: {
            username: finalUsername,
            email: userInfo.data?.user?.email,
            authToken: authToken,
            channelName: channelName,
            channelId: channelId,
            userIdentifier: authToken ? `user-${authToken.substring(0, 10)}` : `youtube-${userInfo.data?.user?.email}`,
            googleId: userInfo.data?.user?.id,
          },
          tokenExpiry: new Date(Date.now() + 3600 * 1000).toISOString(), // 1 hour from now
          requestRefreshToken: true
        })
      });
      
      if (backendResponse.ok) {
        const responseData = await backendResponse.json();
        console.log('✅ YouTube connection processed by backend:', responseData);
        return true;
      } else {
        const errorData = await backendResponse.text();
        console.error('❌ Backend processing failed:', backendResponse.status, errorData);
        return false;
      }
      
    } catch (error: any) {
      console.error('❌ Google Sign-In error:', error);
      
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User cancelled Google Sign-In');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('Google Sign-In already in progress');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Google Play Services not available');
      }
      
      return false;
    }
  }

  return false;
};

/**
 * 🔍 CHECK IF URL IS OAUTH CALLBACK
 */
export const isOAuthCallback = (url: string): boolean => {
  return url.includes('auth/callback') || url.includes('code=');
};

/**
 * 🔄 REFRESH YOUTUBE TOKENS
 */
export const refreshYouTubeTokens = async (): Promise<boolean> => {
  try {
    console.log('🔄 Refreshing YouTube tokens...');
    
    // Get fresh tokens from Google SDK
    const freshTokens = await refreshGoogleTokens();
    if (!freshTokens) {
      console.error('❌ Failed to get fresh tokens from Google SDK');
      return false;
    }
    
    // Get current user info
    const currentUser = await GoogleSignin.getCurrentUser();
    if (!currentUser) {
      console.error('❌ No current Google user found');
      return false;
    }
    
    // Get stored auth token
    const authToken = await AsyncStorage.getItem('onairos_jwt_token') || 
                     await AsyncStorage.getItem('enoch_token') || 
                     await AsyncStorage.getItem('auth_token');
    
    if (!authToken) {
      console.error('❌ No auth token found for YouTube refresh');
      return false;
    }
    
    // Send refreshed tokens to backend
    const refreshResponse = await fetch('https://api2.onairos.uk/youtube/refresh-token', { // Replace with your backend URL
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      },
      body: JSON.stringify({
        accessToken: freshTokens.accessToken,
        idToken: freshTokens.idToken,
        refreshToken: currentUser.serverAuthCode,
        userEmail: currentUser.user?.email,
        tokenExpiry: new Date(Date.now() + 3600 * 1000).toISOString(),
        timestamp: new Date().toISOString()
      })
    });
    
    if (refreshResponse.ok) {
      const responseData = await refreshResponse.json();
      console.log('✅ YouTube tokens refreshed successfully:', responseData);
      return true;
    } else {
      const errorData = await refreshResponse.text();
      console.error('❌ YouTube token refresh failed:', refreshResponse.status, errorData);
      return false;
    }
  } catch (error) {
    console.error('❌ Error refreshing YouTube tokens:', error);
    return false;
  }
};
```

### 📱 **2. OAuth WebView Component (`OAuthWebView.tsx`)**

```typescript
import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  SafeAreaView,
  Dimensions,
} from 'react-native';
import { WebView } from 'react-native-webview';

const { width, height } = Dimensions.get('window');

export interface OAuthWebViewProps {
  url: string;
  onClose: () => void;
  onSuccess: (code: string) => void;
  platform?: string;
  onComplete?: () => void;
}

export const OAuthWebView: React.FC<OAuthWebViewProps> = ({
  url,
  onClose,
  onSuccess,
  platform = 'platform',
  onComplete,
}) => {
  const [isLoading, setIsLoading] = useState(true);
  const [timeoutReached, setTimeoutReached] = useState(false);
  
  console.log('Opening OAuth WebView with URL:', url);
  
  // Set up timeout to prevent infinite waiting
  React.useEffect(() => {
    const timeout = setTimeout(() => {
      console.log(`⏰ OAuth timeout reached for ${platform} after 1 minute`);
      setTimeoutReached(true);
    }, 60000); // 1 minute timeout
    
    return () => clearTimeout(timeout);
  }, [platform]);

  /**
   * 🎯 CALLBACK RECOGNITION LOGIC
   * This handles detecting when OAuth flow is complete
   */
  const handleNavigationStateChange = (navState: any) => {
    console.log(`Navigation state changed for ${platform}:`, navState.url);
    
    // Check for final redirect to your domain (backend callback completed)
    const isFinalRedirect = (
      navState.url.includes('yourdomain.com/Home') || // Replace with your domain
      navState.url.includes('yourdomain.com/home') || // Replace with your domain
      navState.url.includes('yourdomain.com/success') || // Replace with your domain
      navState.url.startsWith('https://yourdomain.com/Home') || // Replace with your domain
      navState.url.startsWith('https://yourdomain.com/home') // Replace with your domain
    );
    
    // Wait for backend callback to complete
    if (isFinalRedirect) {
      console.log(`${platform} OAuth completed - backend callback finished`);
      onSuccess('success');
      
      // Close OAuth window after delay
      setTimeout(() => {
        if (onComplete) {
          console.log(`Closing ${platform} OAuth window after callback completion`);
          onComplete();
        }
      }, 1000);
      return;
    }
    
    // Log intermediate callback URLs for debugging
    const isIntermediateCallback = (
      navState.url.includes('/callback') ||
      navState.url.includes('code=') ||
      navState.url.includes('token=') ||
      navState.url.includes('access_token=')
    );
    
    if (isIntermediateCallback && !isFinalRedirect) {
      console.log(`Detected intermediate callback URL for ${platform}:`, navState.url);
      console.log('Waiting for backend processing to complete...');
      
      // Extract authorization code for logging
      const codeMatch = navState.url.match(/code=([^&]+)/);
      if (codeMatch && codeMatch[1]) {
        console.log('OAuth code detected:', codeMatch[1]);
      }
      
      // Don't close yet - wait for backend processing
      return;
    }
  };

  return (
    <View style={styles.modalContainer}>
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>Connect {platform}</Text>
          {timeoutReached && (
            <Text style={styles.timeoutText}>Taking longer than expected...</Text>
          )}
          <TouchableOpacity onPress={onClose} style={styles.closeButton}>
            <Text style={styles.closeButtonText}>✕</Text>
          </TouchableOpacity>
        </View>

        <View style={styles.webViewContainer}>
          {isLoading && (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color="#1BA9D4" />
              <Text style={styles.loadingText}>Loading...</Text>
            </View>
          )}

          <WebView
            source={{ uri: url }}
            onNavigationStateChange={handleNavigationStateChange}
            onLoadStart={() => setIsLoading(true)}
            onLoadEnd={() => setIsLoading(false)}
            style={styles.webView}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            cacheEnabled={true} // Remember previous logins
            incognito={false} // Don't use incognito mode
            thirdPartyCookiesEnabled={true}
            sharedCookiesEnabled={true} // Enable shared cookies
            userAgent="Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1"
            onError={(syntheticEvent) => {
              const { nativeEvent } = syntheticEvent;
              console.error(`WebView error for ${platform}:`, nativeEvent);
            }}
            onHttpError={(syntheticEvent) => {
              const { nativeEvent } = syntheticEvent;
              console.error(`WebView HTTP error for ${platform}: ${nativeEvent.statusCode}`, nativeEvent.url);
              
              // Handle potential success even with HTTP errors
              if (nativeEvent.url && nativeEvent.url.includes('yourdomain.com')) { // Replace with your domain
                console.log('HTTP error on your domain - treating as potential success');
                onSuccess('success');
                if (onComplete) {
                  setTimeout(() => onComplete(), 1000);
                }
              }
            }}
          />
        </View>
      </SafeAreaView>
    </View>
  );
};

const styles = StyleSheet.create({
  modalContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    width: width,
    height: height,
    backgroundColor: '#fff',
    zIndex: 9999,
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E5E5',
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
    flex: 1,
    textAlign: 'center',
  },
  timeoutText: {
    fontSize: 12,
    color: '#FF6B6B',
    position: 'absolute',
    top: 35,
    left: 16,
  },
  closeButton: {
    padding: 8,
  },
  closeButtonText: {
    fontSize: 18,
    color: '#666',
    fontWeight: 'bold',
  },
  webViewContainer: {
    flex: 1,
    position: 'relative',
  },
  loadingContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    zIndex: 1000,
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  webView: {
    flex: 1,
  },
});
```

### 🔧 **3. Platform Connection Handler**

```typescript
/**
 * 🎯 UNIVERSAL PLATFORM CONNECTION HANDLER
 * Use this in your UniversalOnboarding component
 */

const handleConnectPlatform = async (platformId: string) => {
  // Trigger haptic feedback
  triggerHaptic(HapticType.BUTTON_PRESS);
  
  setConnectingPlatform(platformId);
  
  try {
    // Check if platform has native SDK
    if (hasNativeSDK(platformId)) {
      // Use native SDK authentication (YouTube/Google)
      setCurrentPlatform(platformId);
      const success = await initiateNativeAuth(platformId, username);
      
      if (success) {
        // Update connection state
        setConnections(prev => ({
          ...prev,
          [platformId]: { userName: username, connected: true }
        }));
        
        // Update platform toggles
        setPlatformToggles(prev => ({
          ...prev,
          [platformId]: true
        }));
        
        // Update connection statuses
        setConnectionStatuses(prev => ({
          ...prev,
          [platformId]: 'connected'
        }));

        // Store connected platform
        await storeConnectedPlatform(platformId);
      }
    } else {
      // Use web OAuth flow for other platforms
      setCurrentPlatform(platformId);
      const oauthUrl = await initiateOAuth(platformId, username);
      
      if (oauthUrl) {
        setOauthUrl(oauthUrl);
        setStep('oauth'); // Switch to OAuth WebView
      }
    }
  } catch (error) {
    console.error(`Error connecting to ${platformId}:`, error);
  } finally {
    setConnectingPlatform(null);
  }
};

/**
 * 🎉 OAUTH SUCCESS HANDLER
 * Called when OAuth WebView completes successfully
 */
const handleOAuthSuccess = useCallback(async (code: string) => {
  console.log(`🎉 OAuth success for ${currentPlatform}`);
  
  if (currentPlatform) {
    // Update connections state
    setConnections(prev => ({
      ...prev,
      [currentPlatform]: { userName: username, connected: true }
    }));
    
    // Update platform toggles
    setPlatformToggles(prev => ({
      ...prev,
      [currentPlatform]: true
    }));
    
    // Update connection statuses
    setConnectionStatuses(prev => ({
      ...prev,
      [currentPlatform]: 'connected'
    }));

    // Store connected platform
    await storeConnectedPlatform(currentPlatform);
  }
  
  // Close OAuth window
  setOauthUrl('');
  setStep('connect');
}, [currentPlatform, username]);

/**
 * 📱 DEEP LINK HANDLER
 * Handle OAuth callbacks from deep links
 */
const handleUrl = useCallback(({url}: {url: string}) => {
  if (isOAuthCallback(url)) {
    handleOAuthCallback(url);
  }
}, []);

const handleOAuthCallback = useCallback((url: string) => {
  try {
    const parsedUrl = new URL(url);
    const code = parsedUrl.searchParams.get('code');
    const platform = parsedUrl.searchParams.get('platform') || currentPlatform;
    
    if (code && platform) {
      // Update connections state
      setConnections(prev => ({
        ...prev,
        [platform]: { userName: username, connected: true }
      }));
      
      // Update platform toggles
      setPlatformToggles(prev => ({
        ...prev,
        [platform]: true
      }));
      
      // Return to connect step
      setStep('connect');
    }
  } catch (error) {
    console.error('Error handling OAuth callback:', error);
  }
}, [currentPlatform, username]);
```

### 📋 **4. Required Dependencies (`package.json`)**

```json
{
  "dependencies": {
    "@react-native-google-signin/google-signin": "^10.0.1",
    "@react-native-async-storage/async-storage": "^1.19.3",
    "react-native-webview": "^13.6.2"
  }
}
```

### 🔧 **5. iOS Configuration (`Info.plist`)**

```xml
<!-- Add to ios/YourApp/Info.plist -->
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLName</key>
    <string>GoogleSignIn</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <!-- Replace with your reversed client ID -->
      <string>com.googleusercontent.apps.1030678346906-lovkuds2ouqmoc8eu5qpo98spa6edv4o</string>
    </array>
  </dict>
  <dict>
    <key>CFBundleURLName</key>
    <string>OAuth</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <!-- Replace with your app scheme -->
      <string>onairosevents</string>
    </array>
  </dict>
</array>

<!-- Add GoogleService-Info.plist file to your iOS project -->
```

### 🤖 **6. Android Configuration**

**`android/app/google-services.json`** - Download from Google Cloud Console

**`android/app/src/main/AndroidManifest.xml`:**
```xml
<!-- Add intent filters for deep links -->
<activity
    android:name=".MainActivity"
    android:exported="true"
    android:launchMode="singleTask">
    
    <!-- Existing intent filter -->
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    
    <!-- OAuth callback intent filter -->
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Replace with your app scheme -->
        <data android:scheme="onairosevents" />
    </intent-filter>
    
</activity>
```

### 🛠 **7. Backend API Endpoints Required**

Your backend needs these endpoints:

```javascript
// POST /youtube/authorize - Initiate YouTube OAuth
// POST /youtube/native-auth - Handle native Google Sign-In
// POST /youtube/refresh-token - Refresh YouTube tokens

// POST /reddit/authorize - Initiate Reddit OAuth
// POST /pinterest/authorize - Initiate Pinterest OAuth
// POST /linkedin/authorize - Initiate LinkedIn OAuth
// POST /gmail/authorize - Initiate Gmail OAuth
// POST /email/authorize - Handle email verification

// Each platform should redirect to: yourdomain.com/Home after completion
```

### 🔄 **8. Token Refresh Implementation**

```typescript
/**
 * 🔄 YOUTUBE TOKEN EXPIRY HANDLER
 * Call this when backend reports YouTube token expiry
 */
const handleYouTubeTokenExpiry = async () => {
  console.log('🔄 YouTube token expired, attempting refresh...');
  
  try {
    const refreshSuccess = await refreshYouTubeTokens();
    
    if (refreshSuccess) {
      console.log('✅ YouTube tokens refreshed successfully');
      // Resume your operation
    } else {
      console.log('❌ Token refresh failed, need to reconnect');
      // Trigger reconnection flow
      await handleConnectPlatform('youtube');
    }
  } catch (error) {
    console.error('❌ YouTube token refresh error:', error);
    // Fallback to full reconnection
    await handleConnectPlatform('youtube');
  }
};
```

### 📝 **9. Usage Instructions**

1. **Replace all placeholder values:**
   - `1030678346906-lovkuds2ouqmoc8eu5qpo98spa6edv4o.apps.googleusercontent.com` → Your Google Client ID
   - `onairosevents://auth/callback` → Your app's deep link scheme
   - `https://api2.onairos.uk` → Your backend URL
   - `yourdomain.com` → Your domain for final redirects

2. **Set up Google Cloud Console:**
   - Enable YouTube Data API v3
   - Create OAuth 2.0 credentials for iOS, Android, and Web
   - Download `GoogleService-Info.plist` and `google-services.json`

3. **Configure your backend:**
   - Implement all the required OAuth endpoints
   - Handle token refresh logic
   - Set up proper redirects to your domain

4. **Test the flow:**
   - Test each platform connection
   - Verify token refresh works
   - Test deep link callbacks

This complete package gives you everything needed to recreate the OAuth system with YouTube SDK integration in any React Native app! 🚀