# React Native Mobile App Setup Guide

## Overview
This guide covers setting up a React Native mobile app for CoinKrazy that shares business logic with the web platform while providing native mobile experiences.

## Project Structure
```
coinkrazy-mobile/
├── app/
│   ├── (auth)/
│   │   ├── login.tsx
│   │   └── register.tsx
│   ├── (tabs)/
│   │   ├── casino.tsx
│   │   ├── account.tsx
│   │   └── profile.tsx
│   └── _layout.tsx
├── components/
│   ├── GameCard.tsx
│   ├── CasinoLobby.tsx
│   └── shared/
├── hooks/
│   ├── useTRPC.ts
│   └── useRealtimeNotifications.ts
├── services/
│   ├── api.ts
│   └── auth.ts
└── app.json
```

## Installation

### Prerequisites
- Node.js 18+
- Expo CLI: `npm install -g expo-cli`
- iOS: Xcode (macOS) or EAS Build
- Android: Android Studio or EAS Build

### Setup Steps

```bash
# Create new Expo project
npx create-expo-app coinkrazy-mobile
cd coinkrazy-mobile

# Install dependencies
npm install expo-router expo-auth-session expo-secure-store
npm install @react-navigation/native @react-navigation/bottom-tabs
npm install react-native-screens react-native-safe-area-context
npm install @tanstack/react-query
npm install zustand
npm install react-native-svg react-native-gesture-handler

# Install dev dependencies
npm install --save-dev typescript @types/react-native
```

## Key Features

### 1. Authentication
```typescript
// services/auth.ts
import * as SecureStore from 'expo-secure-store';
import * as AuthSession from 'expo-auth-session';

export async function login(email: string, password: string) {
  const response = await fetch('https://api.coinkrazy.com/api/trpc/auth.login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  
  const { token } = await response.json();
  await SecureStore.setItemAsync('authToken', token);
  return token;
}

export async function getAuthToken() {
  return await SecureStore.getItemAsync('authToken');
}
```

### 2. tRPC Integration
```typescript
// hooks/useTRPC.ts
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/routers';

export const trpc = createTRPCReact<AppRouter>();

// Setup in app root
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';

const queryClient = new QueryClient();
const trpcClient = trpc.createClient({
  links: [
    httpBatchLink({
      url: 'https://api.coinkrazy.com/api/trpc',
      async headers() {
        const token = await getAuthToken();
        return {
          authorization: token ? `Bearer ${token}` : '',
        };
      },
    }),
  ],
});

export function RootLayout() {
  return (
    <trpc.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>
        {/* App content */}
      </QueryClientProvider>
    </trpc.Provider>
  );
}
```

### 3. Casino Lobby Component
```typescript
// components/CasinoLobby.tsx
import { FlatList, View, Text, TouchableOpacity, Image } from 'react-native';
import { trpc } from '@/hooks/useTRPC';

export function CasinoLobby() {
  const { data: games, isLoading } = trpc.allGames.getAll.useQuery();

  const renderGame = ({ item }) => (
    <TouchableOpacity className="m-2 rounded-lg overflow-hidden">
      <Image
        source={{ uri: item.thumbnail_url }}
        className="w-32 h-32"
        resizeMode="cover"
      />
      <View className="bg-slate-800 p-2">
        <Text className="text-white font-semibold text-sm">{item.name}</Text>
        <Text className="text-slate-400 text-xs">{item.provider}</Text>
      </View>
    </TouchableOpacity>
  );

  return (
    <FlatList
      data={games}
      renderItem={renderGame}
      keyExtractor={(item) => item.id}
      numColumns={2}
      isLoading={isLoading}
    />
  );
}
```

### 4. Push Notifications Setup
```typescript
// services/notifications.ts
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

export async function registerForPushNotifications() {
  if (!Device.isDevice) {
    console.log('Must use physical device for push notifications');
    return;
  }

  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  if (finalStatus !== 'granted') {
    console.log('Failed to get push token');
    return;
  }

  const token = (await Notifications.getExpoPushTokenAsync()).data;
  
  // Send token to backend
  await fetch('https://api.coinkrazy.com/api/trpc/notifications.registerDevice', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token }),
  });

  return token;
}

// Setup notification handler
Notifications.setNotificationHandler({
  handleNotification: async (notification) => {
    return {
      shouldShowAlert: true,
      shouldPlaySound: true,
      shouldSetBadge: true,
    };
  },
});
```

### 5. App Navigation
```typescript
// app/_layout.tsx
import { Stack } from 'expo-router';
import { useAuth } from '@/hooks/useAuth';

export default function RootLayout() {
  const { user, isLoading } = useAuth();

  if (isLoading) {
    return <LoadingScreen />;
  }

  return (
    <Stack>
      {user ? (
        <>
          <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        </>
      ) : (
        <>
          <Stack.Screen name="(auth)" options={{ headerShown: false }} />
        </>
      )}
    </Stack>
  );
}
```

## Building & Deployment

### EAS Build (Recommended)
```bash
# Install EAS CLI
npm install -g eas-cli

# Configure project
eas build:configure

# Build for iOS
eas build --platform ios

# Build for Android
eas build --platform android

# Submit to App Store
eas submit --platform ios

# Submit to Google Play
eas submit --platform android
```

### Local Build
```bash
# iOS (macOS only)
eas build --platform ios --local

# Android
eas build --platform android --local
```

## Performance Optimization

1. **Code Splitting**: Use lazy loading for screens
2. **Image Optimization**: Use `expo-image` for better caching
3. **State Management**: Use Zustand for lightweight state
4. **Query Caching**: Configure React Query for offline support

## Testing

```bash
# Run tests
npm test

# Run E2E tests with Detox
npm run e2e:build:ios
npm run e2e:test:ios
```

## Troubleshooting

- **Port conflicts**: `expo start --clear`
- **Build failures**: `eas build --platform ios --clear-cache`
- **Token expiration**: Implement refresh token rotation in auth service
- **Slow performance**: Profile with React Native Debugger

## Resources

- [Expo Documentation](https://docs.expo.dev)
- [React Native Docs](https://reactnative.dev)
- [tRPC React Native Guide](https://trpc.io/docs/client/react-native)
- [EAS Build Docs](https://docs.expo.dev/build/introduction/)
