# Frontend Architecture & Technology Stack

## Overview

This document outlines the frontend architecture decisions for the Telegram Mini App, including framework selection, build processes, state management, routing, and Telegram Web App SDK integration.

---

## 1. Framework Selection

### **React** ⭐

**Strong Points:**
- **Excellent AI/LLM Support:** React has the largest ecosystem and most training data for AI code generation tools (GitHub Copilot, Cursor, ChatGPT, etc.)
- **Component-based architecture:** Perfect for building reusable UI components (InvestmentCard, ReferralLink, TransactionHistory, etc.)
- **Rich ecosystem:** Extensive library support (React Router, React Query, Zustand, etc.)
- **Strong TypeScript support:** Better type safety for financial calculations
- **Telegram Web App SDK compatibility:** Works seamlessly with Telegram's SDK
- **Large community:** Easier to find solutions and get help
- **Hooks pattern:** Clean state management and side effects handling

**AI Capability Context:**
- **Best AI assistance:** React has the most examples, documentation, and training data in AI models
- **Code generation:** AI tools can generate React components more accurately due to extensive training data
- **Debugging:** AI assistants can better understand and debug React code patterns
- **Best practices:** AI tools have better knowledge of React best practices and patterns

**Use Case Fit:**
- ✅ Complex state management (investment tracking, referral chains, transactions)
- ✅ Real-time updates (balance changes, reward distributions)
- ✅ Component reusability (investment cards, transaction lists)
- ✅ Financial calculations display (precise decimal handling)

**Why React for This Project:**
1. **Best AI assistance:** React has the most comprehensive AI support, making development faster with AI tools like Cursor
2. **Component architecture:** Perfect for building reusable components (InvestmentCard, ReferralLink, TransactionHistory)
3. **State management:** Excellent libraries (Zustand, Redux Toolkit) for complex state (investments, referrals, transactions)
4. **Telegram SDK:** Seamless integration with Telegram Web App SDK
5. **TypeScript support:** Strong typing for financial calculations and API responses
6. **Ecosystem:** Rich library ecosystem for charts, forms, date handling, etc.

---

## 2. Telegram Web App SDK Integration

### What is Telegram Web App SDK?

The Telegram Web App SDK provides JavaScript APIs to interact with the Telegram client, enabling:
- Access to user data (from `initData`)
- Theme detection (light/dark mode)
- Back button handling
- Viewport expansion
- Haptic feedback
- Closing the mini app
- Showing alerts/confirmations

### SDK Integration with React

**Yes, Telegram Web App SDK is essential and works excellently with React.**

**Why it's needed:**
1. **User Authentication:** Validates `initData` from Telegram to authenticate users
2. **Theme Support:** Automatically detects Telegram theme (light/dark) and applies to your app
3. **Native Feel:** Provides haptic feedback, back button handling, viewport management
4. **User Data:** Access to Telegram user information (name, photo, etc.)
5. **Deep Linking:** Handles referral link parameters from Telegram

**Integration Example:**

```typescript
// hooks/useTelegram.ts
import { useEffect, useState } from 'react';
import { WebApp } from '@twa-dev/types';

declare global {
  interface Window {
    Telegram?: {
      WebApp: WebApp;
    };
  }
}

export const useTelegram = () => {
  const [webApp, setWebApp] = useState<WebApp | null>(null);

  useEffect(() => {
    const tg = window.Telegram?.WebApp;
    if (tg) {
      tg.ready();
      tg.expand(); // Expand to full height
      setWebApp(tg);
    }
  }, []);

  return {
    webApp,
    user: webApp?.initDataUnsafe?.user,
    theme: webApp?.colorScheme,
    isDark: webApp?.colorScheme === 'dark',
  };
};
```

**Usage in Components:**

```typescript
// components/Dashboard.tsx
import { useTelegram } from '../hooks/useTelegram';

const Dashboard = () => {
  const { user, isDark, webApp } = useTelegram();
  
  const handleShare = () => {
    webApp?.openTelegramLink(`https://t.me/share/url?url=${referralLink}`);
  };

  return (
    <div className={isDark ? 'dark-theme' : 'light-theme'}>
      <h1>Welcome, {user?.first_name}!</h1>
      {/* ... */}
    </div>
  );
};
```

**Benefits with React:**
- ✅ React hooks make SDK integration clean and reusable
- ✅ Context API can provide Telegram data throughout the app
- ✅ TypeScript types available for type safety
- ✅ Easy to create custom hooks for Telegram features

---

## 3. Build Process

### **Recommendation: Vite** ⭐

**Why Vite over Webpack:**

1. **Faster Development:**
   - **Instant server start:** Vite starts dev server in milliseconds vs Webpack's seconds
   - **Hot Module Replacement (HMR):** Near-instant updates during development
   - **On-demand compilation:** Only compiles files that are imported

2. **Better Performance:**
   - Uses native ES modules in development (no bundling)
   - Faster builds in production
   - Optimized code splitting

3. **Modern Tooling:**
   - Built-in TypeScript support
   - PostCSS, CSS preprocessing out of the box
   - Better error messages and debugging

4. **Smaller Bundle Size:**
   - Tree-shaking by default
   - Better code splitting
   - Important for Telegram Mini Apps (faster load times)

5. **Easier Configuration:**
   - Minimal config needed
   - Less complexity than Webpack
   - Better for AI code generation (simpler configs)

**Vite Configuration Example:**

```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: false, // Disable for production
    rollupOptions: {
      output: {
        manualChunks: {
          'react-vendor': ['react', 'react-dom', 'react-router-dom'],
          'telegram-sdk': ['@twa-dev/types'],
        },
      },
    },
  },
  server: {
    port: 3000,
    host: true, // Allow external access for Telegram testing
  },
});
```

**Why Build Process is Needed:**

1. **TypeScript Compilation:** Convert TS to JS
2. **JSX Transformation:** Convert React JSX to JavaScript
3. **Code Optimization:** Minification, tree-shaking, dead code elimination
4. **Asset Processing:** CSS preprocessing, image optimization
5. **Module Bundling:** Combine multiple files into optimized bundles
6. **Environment Variables:** Handle different configs for dev/prod
7. **Code Splitting:** Load only necessary code for faster initial load

**Production Build Benefits:**
- Smaller bundle size (faster Telegram Mini App load)
- Optimized code (better performance)
- Single file deployment (easier hosting)

---

## 4. State Management

### Overview

For a Telegram Mini App with investments, referrals, transactions, and real-time balance updates, we need robust state management.

### **Recommended Approach: Zustand** ⭐

**Why Zustand over Redux/Context API:**

1. **Simplicity:** Minimal boilerplate, easy to learn
2. **Performance:** Better than Context API (no unnecessary re-renders)
3. **TypeScript:** Excellent TypeScript support
4. **Small Bundle:** ~1KB (vs Redux ~10KB)
5. **AI-Friendly:** Simple patterns that AI tools understand well
6. **No Providers:** No need to wrap app in providers

### State Management Examples

#### **Example 1: User State**

```typescript
// stores/userStore.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface User {
  id: number;
  username?: string;
  first_name: string;
  last_name?: string;
  photo_url?: string;
  credit_balance: number;
}

interface UserState {
  user: User | null;
  isLoading: boolean;
  setUser: (user: User) => void;
  updateBalance: (amount: number) => void;
  logout: () => void;
}

export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      user: null,
      isLoading: true,
      setUser: (user) => set({ user, isLoading: false }),
      updateBalance: (amount) =>
        set((state) => ({
          user: state.user
            ? { ...state.user, credit_balance: state.user.credit_balance + amount }
            : null,
        })),
      logout: () => set({ user: null, isLoading: false }),
    }),
    {
      name: 'user-storage', // localStorage key
    }
  )
);
```

**Usage:**

```typescript
// components/Dashboard.tsx
import { useUserStore } from '../stores/userStore';

const Dashboard = () => {
  const { user, updateBalance } = useUserStore();
  
  const handleRewardReceived = (amount: number) => {
    updateBalance(amount);
  };

  return (
    <div>
      <h1>Balance: ${user?.credit_balance.toFixed(2)}</h1>
    </div>
  );
};
```

#### **Example 2: Investment State**

```typescript
// stores/investmentStore.ts
import { create } from 'zustand';

interface Investment {
  id: number;
  amount: number;
  tier: number;
  daily_reward_rate: number;
  duration_days: number;
  start_date: string;
  end_date: string;
  status: 'active' | 'completed';
}

interface InvestmentState {
  investments: Investment[];
  isLoading: boolean;
  addInvestment: (investment: Investment) => void;
  updateInvestment: (id: number, updates: Partial<Investment>) => void;
  getActiveInvestments: () => Investment[];
  getTotalInvested: () => number;
}

export const useInvestmentStore = create<InvestmentState>((set, get) => ({
  investments: [],
  isLoading: false,
  addInvestment: (investment) =>
    set((state) => ({
      investments: [...state.investments, investment],
    })),
  updateInvestment: (id, updates) =>
    set((state) => ({
      investments: state.investments.map((inv) =>
        inv.id === id ? { ...inv, ...updates } : inv
      ),
    })),
  getActiveInvestments: () =>
    get().investments.filter((inv) => inv.status === 'active'),
  getTotalInvested: () =>
    get()
      .investments.filter((inv) => inv.status === 'active')
      .reduce((sum, inv) => sum + inv.amount, 0),
}));
```

#### **Example 3: Transaction State**

```typescript
// stores/transactionStore.ts
import { create } from 'zustand';

interface Transaction {
  id: number;
  type: 'deposit' | 'withdrawal' | 'investment' | 'reward' | 'commission';
  amount: number;
  status: 'pending' | 'completed' | 'failed';
  created_at: string;
  description?: string;
}

interface TransactionState {
  transactions: Transaction[];
  isLoading: boolean;
  addTransaction: (transaction: Transaction) => void;
  getTransactionsByType: (type: Transaction['type']) => Transaction[];
  getRecentTransactions: (limit: number) => Transaction[];
}

export const useTransactionStore = create<TransactionState>((set, get) => ({
  transactions: [],
  isLoading: false,
  addTransaction: (transaction) =>
    set((state) => ({
      transactions: [transaction, ...state.transactions],
    })),
  getTransactionsByType: (type) =>
    get().transactions.filter((tx) => tx.type === type),
  getRecentTransactions: (limit) =>
    get().transactions.slice(0, limit),
}));
```

#### **Example 4: Referral State**

```typescript
// stores/referralStore.ts
import { create } from 'zustand';

interface Referral {
  id: number;
  username?: string;
  first_name: string;
  total_earned: number;
  level: number;
  joined_date: string;
}

interface ReferralState {
  referrals: Referral[];
  referralLink: string;
  totalCommission: number;
  isLoading: boolean;
  setReferrals: (referrals: Referral[]) => void;
  setReferralLink: (link: string) => void;
  updateCommission: (amount: number) => void;
  getReferralsByLevel: (level: number) => Referral[];
}

export const useReferralStore = create<ReferralState>((set, get) => ({
  referrals: [],
  referralLink: '',
  totalCommission: 0,
  isLoading: false,
  setReferrals: (referrals) => set({ referrals }),
  setReferralLink: (link) => set({ referralLink: link }),
  updateCommission: (amount) =>
    set((state) => ({ totalCommission: state.totalCommission + amount })),
  getReferralsByLevel: (level) =>
    get().referrals.filter((ref) => ref.level === level),
}));
```

### Alternative: React Query for Server State

For API data fetching and caching, consider **TanStack Query (React Query)**:

```typescript
// hooks/useInvestments.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';

export const useInvestments = () => {
  return useQuery({
    queryKey: ['investments'],
    queryFn: () => api.getInvestments(),
    staleTime: 30000, // Consider fresh for 30 seconds
  });
};

export const useCreateInvestment = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (amount: number) => api.createInvestment(amount),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['investments'] });
      queryClient.invalidateQueries({ queryKey: ['user'] });
    },
  });
};
```

**State Management Strategy:**

1. **Zustand:** Client-side state (UI state, form state, local preferences)
2. **React Query:** Server state (API data, caching, synchronization)
3. **Telegram Context:** Telegram-specific data (user info, theme)

---

## 5. Routing

### Do We Need Routing?

**Yes, routing is essential for a Telegram Mini App.**

### Purpose of Routing

1. **Navigation:** Move between different screens/pages
2. **Deep Linking:** Handle referral links and direct navigation
3. **URL State:** Maintain app state via URL (shareable links, browser back button)
4. **Code Splitting:** Load only necessary code for each route
5. **User Experience:** Smooth navigation without full page reloads

### Routing in Telegram Mini Apps

**Why it's important:**
- Users can share specific pages (e.g., referral page)
- Browser back button works correctly
- Deep links can navigate to specific sections
- Better user experience (feels like a native app)

### **Recommended: React Router v6** ⭐

**Why React Router:**
- Industry standard for React apps
- Excellent TypeScript support
- Code splitting support
- Works perfectly with Telegram Web App SDK
- AI tools understand it well

### Routing Structure Example

```typescript
// App.tsx
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useUserStore } from './stores/userStore';
import { useTelegram } from './hooks/useTelegram';

// Pages
import Dashboard from './pages/Dashboard';
import Investments from './pages/Investments';
import Referrals from './pages/Referrals';
import Transactions from './pages/Transactions';
import Profile from './pages/Profile';
import InvestmentDetail from './pages/InvestmentDetail';

// Layout
import Layout from './components/Layout';

function App() {
  const { user, isLoading } = useUserStore();
  const { webApp } = useTelegram();

  // Handle Telegram back button
  useEffect(() => {
    if (webApp) {
      const handleBackButton = () => {
        if (window.location.pathname === '/') {
          webApp.close();
        } else {
          window.history.back();
        }
      };
      webApp.BackButton.onClick(handleBackButton);
      webApp.BackButton.show();
    }
  }, [webApp]);

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

  return (
    <BrowserRouter>
      <Layout>
        <Routes>
          <Route path="/" element={<Dashboard />} />
          <Route path="/investments" element={<Investments />} />
          <Route path="/investments/:id" element={<InvestmentDetail />} />
          <Route path="/referrals" element={<Referrals />} />
          <Route path="/transactions" element={<Transactions />} />
          <Route path="/profile" element={<Profile />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </Layout>
    </BrowserRouter>
  );
}
```

### Handling Referral Links

```typescript
// hooks/useReferralLink.ts
import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTelegram } from './useTelegram';
import { api } from '../services/api';

export const useReferralLink = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { webApp } = useTelegram();

  useEffect(() => {
    // Check for referral code in URL
    const refCode = searchParams.get('ref') || 
                    webApp?.initDataUnsafe?.start_param;
    
    if (refCode) {
      // Register user with referral code
      api.registerWithReferral(refCode).then(() => {
        // Clear the ref parameter from URL
        navigate('/', { replace: true });
      });
    }
  }, [searchParams, webApp, navigate]);
};
```

### Route Protection Example

```typescript
// components/ProtectedRoute.tsx
import { Navigate } from 'react-router-dom';
import { useUserStore } from '../stores/userStore';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

export const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
  const { user, isLoading } = useUserStore();

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

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};
```

### Navigation Component Example

```typescript
// components/Navigation.tsx
import { Link, useLocation } from 'react-router-dom';

const Navigation = () => {
  const location = useLocation();

  const navItems = [
    { path: '/', icon: '🏠', label: 'Home' },
    { path: '/investments', icon: '💰', label: 'Invest' },
    { path: '/referrals', icon: '👥', label: 'Referrals' },
    { path: '/transactions', icon: '📊', label: 'History' },
    { path: '/profile', icon: '👤', label: 'Profile' },
  ];

  return (
    <nav className="bottom-nav">
      {navItems.map((item) => (
        <Link
          key={item.path}
          to={item.path}
          className={location.pathname === item.path ? 'active' : ''}
        >
          <span>{item.icon}</span>
          <span>{item.label}</span>
        </Link>
      ))}
    </nav>
  );
};
```

### Benefits of Routing

1. **Better UX:** Smooth navigation between screens
2. **Shareable Links:** Users can share specific pages
3. **Browser Integration:** Back button works correctly
4. **Code Splitting:** Load only necessary code per route
5. **State Management:** URL can hold state (filters, search params)
6. **Deep Linking:** Handle referral links and direct navigation

---

## 6. Technology Stack Summary

### Recommended Stack

- **Framework:** React 18+ with TypeScript
- **Build Tool:** Vite
- **State Management:** Zustand (client state) + TanStack Query (server state)
- **Routing:** React Router v6
- **Telegram SDK:** `@twa-dev/types` + `@twa-dev/sdk`
- **Styling:** Tailwind CSS (recommended) or CSS Modules
- **HTTP Client:** Axios or Fetch API
- **Form Handling:** React Hook Form
- **Date Handling:** date-fns or Day.js
- **Charts/Graphs:** Recharts or Chart.js (for investment analytics)

### Project Structure

```
src/
├── components/          # Reusable UI components
│   ├── InvestmentCard.tsx
│   ├── ReferralLink.tsx
│   └── TransactionItem.tsx
├── pages/              # Page components
│   ├── Dashboard.tsx
│   ├── Investments.tsx
│   └── Referrals.tsx
├── stores/             # Zustand stores
│   ├── userStore.ts
│   ├── investmentStore.ts
│   └── transactionStore.ts
├── hooks/              # Custom React hooks
│   ├── useTelegram.ts
│   ├── useInvestments.ts
│   └── useReferralLink.ts
├── services/           # API services
│   └── api.ts
├── types/              # TypeScript types
│   └── index.ts
├── utils/              # Utility functions
│   └── formatters.ts
└── App.tsx
```

---

## 7. PWA Capabilities

**Decision: No PWA capabilities required**

**Reasoning:**
- Telegram Mini Apps run within Telegram's native app
- No need for standalone web app installation
- Telegram handles app lifecycle and updates
- Focus on Telegram-specific features instead

---

## 8. Next Steps

1. **Set up project:** Initialize React + TypeScript + Vite project
2. **Install dependencies:** React Router, Zustand, Telegram SDK, etc.
3. **Configure Vite:** Set up build configuration and environment variables
4. **Create project structure:** Set up folders and initial files
5. **Integrate Telegram SDK:** Create hooks and context for Telegram integration
6. **Set up routing:** Configure React Router with all routes
7. **Create state stores:** Set up Zustand stores for user, investments, transactions
8. **Build core components:** Create reusable UI components
9. **Connect to backend API:** Set up API service layer
10. **Test Telegram integration:** Test in Telegram Mini App environment

---

## Additional Considerations

### Performance Optimization

- **Code Splitting:** Use React.lazy() for route-based code splitting
- **Image Optimization:** Use WebP format, lazy loading
- **Bundle Size:** Monitor bundle size (important for Telegram Mini Apps)
- **Memoization:** Use React.memo, useMemo, useCallback where appropriate

### Testing

- **Unit Tests:** Jest + React Testing Library
- **E2E Tests:** Playwright or Cypress (for critical flows)
- **Telegram Testing:** Use Telegram's test environment

### Accessibility

- **Keyboard Navigation:** Ensure all features are keyboard accessible
- **Screen Readers:** Proper ARIA labels
- **Color Contrast:** Follow WCAG guidelines

### Security

- **initData Validation:** Always validate Telegram initData on backend
- **XSS Prevention:** Sanitize user inputs
- **CSRF Protection:** Use tokens for API requests
- **Rate Limiting:** Implement on frontend (show loading states)
