Documentation

Smart Mobility Predictor - Quick Reference Card

Essential Commands

bash
npm run dev # Start dev server (http://localhost:3000) npm run build # Build for production npm run start # Start prod server npm run lint # Check code quality vercel deploy --prod # Deploy to Vercel git push origin main # Auto-deploy via GitHub

i18n (Translations)

Use Translation

tsx
import { useTranslation } from '@/lib/language-context'; const t = useTranslation(); <h1>{t('header.title')}</h1>

Get Current Language

tsx
import { useCurrentLanguage } from '@/lib/language-context'; const language = useCurrentLanguage(); // 'en' or 'fr'

Change Language

tsx
import { useLanguage } from '@/lib/language-context'; const { language, setLanguage } = useLanguage(); setLanguage('fr'); // Switch to French

Add Translation

  1. Open lib/i18n.ts
  2. Add key to both en and fr objects:
    typescript
    feature: { title: 'English', ... } feature: { titre: 'Français', ... }
  3. Use in component: t('feature.title')

Currency (TND - Tunisia Dinar)

Format as TND

tsx
import { formatTND, formatSimpleTND } from '@/lib/currency'; formatTND(150.5) // "د.ت 150.500" formatSimpleTND(150.5) // "د.ت 150.500" formatTND(null) // "د.ت0.000"

Calculate Savings

tsx
import { calculateSavings } from '@/lib/currency'; const { difference, percentageSavings } = calculateSavings(100, 75); // { difference: 25, percentageSavings: 25 }

Parse Currency

tsx
import { parseTND } from '@/lib/currency'; const amount = parseTND('د.ت 50.500'); // 50.5

TND Constants

  • Symbol: د.ت
  • Code: TND
  • Decimals: 3
  • Locale: ar-TN

Common Component Patterns

Client Component with Translations

tsx
'use client'; import { useTranslation } from '@/lib/language-context'; import { Card } from '@/components/ui/card'; export function MyComponent() { const t = useTranslation(); return ( <Card className="p-6"> <h2 className="text-lg font-semibold"> {t('feature.title')} </h2> </Card> ); }

API Call Pattern

tsx
const [loading, setLoading] = useState(false); const [error, setError] = useState<string>(); const handleSubmit = async (data: Data) => { setLoading(true); try { const res = await fetch('/api/predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); const result = await res.json(); if (!result.success) throw new Error(result.error); // Use result.data } catch (err) { setError(err instanceof Error ? err.message : 'Error'); } finally { setLoading(false); } };

Form Input Pattern

tsx
import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; <div className="space-y-2"> <Label htmlFor="name">{t('form.name')}</Label> <Input id="name" name="name" value={formData.name} onChange={handleChange} placeholder="Enter name" className="border-primary/20" /> </div>

Type Definitions

Common Types

typescript
// From lib/types.ts interface TripRequest { origin: { name: string; coordinates: [number, number] }; destination: { name: string; coordinates: [number, number] }; departureTime: Date; } enum WeatherType { CLEAR = 'clear', CLOUDY = 'cloudy', RAINY = 'rainy', STORMY = 'stormy', FOGGY = 'foggy', } enum TrafficState { FLUIDE = 'fluide', NORMAL = 'normal', DENSE = 'dense', SATURATED = 'saturated', }

File Locations

FeatureFile
Componentscomponents/
Pagesapp/
Typeslib/types.ts
Translationslib/i18n.ts
Currencylib/currency.ts
i18n Contextlib/language-context.tsx
ML Enginelib/ml-engine.ts
ML Datalib/ml-data.ts
API Routesapp/api/
Hookshooks/
UI Componentscomponents/ui/

Styling Guide

Tailwind Classes

tsx
// Layout className="flex items-center justify-between gap-4" className="grid grid-cols-3 gap-4" // Spacing className="p-4 m-2 gap-6" // Colors (use design tokens) className="bg-background text-foreground" className="border border-primary/20" // Responsive className="md:grid-cols-2 lg:grid-cols-3" // Hover states className="hover:bg-primary/10 transition"

Design Tokens

css
--primary: oklch(0.52 0.2 260) /* Blue */ --accent: oklch(0.6 0.21 39) /* Orange */ --background: oklch(0.98 0.001 260) /* Off-white */ --foreground: oklch(0.18 0.005 260) /* Dark */ --destructive: oklch(0.63 0.21 25) /* Red */

Error Handling Checklist

typescript
// Always null-check before .toFixed() ❌ value.toFixed(3) ✅ value != null ? value.toFixed(3) : '0.000' // Validate API responses const data = await res.json(); if (!res.ok) throw new Error(data.error); // Type guard optional properties ❌ obj.optional.property ✅ obj?.optional?.property ?? default // Handle errors in try-catch try { /* ... */ } catch (err) { const message = err instanceof Error ? err.message : 'Error'; }

Debugging Tips

Log with Context

typescript
console.log('[v0] User data:', userData); console.log('[v0] API response:', response); console.log('[v0] Component state:', state);

Check in Browser Console

javascript
// Language localStorage.getItem('smart-mobility-language') // Type check typeof value === 'number' // Array check Array.isArray(arr) // API test fetch('/api/predict', { method: 'POST', body: JSON.stringify(data) }) .then(r => r.json()).then(console.log)

React DevTools

  • Check component props
  • Inspect state values
  • Monitor renders
  • Check hooks

Common Issues & Solutions

IssueSolution
Language not persistingEnable localStorage, clear cache
Currency not formattingCheck locale support, use fallback
Form not submittingCheck API endpoint, validate input
TypeScript errorsRun npx tsc --noEmit, check types
Build failsrm -rf .next && npm run build
Component not renderingCheck conditional rendering, props

Translation Key Hierarchy

header.
  ├── title
  ├── subtitle
  └── documentation

form.
  ├── origin
  ├── destination
  ├── departureTime
  ├── weather
  ├── temperature
  ├── humidity
  └── ...

results.
  ├── estimatedTime
  ├── confidence
  ├── trafficState
  └── ...

footer.
  ├── smartMobility
  ├── features
  ├── resources
  └── company

API Response Structure

typescript
interface PredictionResponse { success: boolean; data?: { regressionOutput: { estimatedTime: number; confidence: number; confidence_interval: { lower: number; upper: number }; }; classificationOutput: { state: TrafficState; probability: number; stateDistribution: Record<string, number>; }; clusteringOutput: { clusterId: number; clusterName: string; silhouetteScore: number; }; recommendation: { recommendedMode: TransportMode; routeAlternatives: RouteAlternative[]; }; metadata: { timestamp: Date; processingTime: number; }; }; error?: string; }

Performance Quick Tips

  • Use React.memo() for expensive components
  • Lazy load with dynamic() imports
  • Memoize callbacks with useCallback()
  • Cache data with useMemo()
  • Use <Image /> for optimization
  • Minimize re-renders with proper dependencies

Security Checklist

  • No sensitive data in localStorage
  • Validate all API inputs
  • Use HTTPS in production
  • Sanitize user input
  • Check CORS configuration
  • No hard-coded secrets
  • Proper error messages (no stack traces)

Deployment Shortcuts

bash
# Build and test locally npm run build && npm run start # Deploy to Vercel vercel deploy --prod # View deployments vercel ls # View logs vercel logs # Rollback # Via dashboard: Deployments → ... → Promote to Production

Quick Stats

MetricValue
Languages2 (EN, FR)
Currencies1 (TND)
ML Models3 (Regression, Classification, Clustering)
UI Components25+
Type Definitions15+
Documentation Pages6
Total Code~3000 lines

Resources


Quick start: npm run dev → Open http://localhost:3000 🚀

Version: 1.0.0 | Status: Production Ready ✅