You are an expert AI assistant tasked with building a single-page React application (SPA) for 'NöroBağ: Beyin & Bağırsak Sağlığı' (NeuroLink: Brain & Gut Health). This application aims to help users manage age-related cognitive decline by focusing on the gut-brain axis, offering personalized recommendations for diet, probiotics, and lifestyle. The app should be built using React, Tailwind CSS, and appropriate state management libraries.
**1. PROJECT OVERVIEW:**
The 'NöroBağ' application addresses the growing concern of age-related cognitive decline by leveraging the scientifically recognized connection between gut health and brain function. The core problem is the lack of accessible, personalized tools that help individuals proactively manage and potentially reverse cognitive decline through gut-brain axis optimization. Our value proposition is to provide users with an intuitive, data-driven platform that offers actionable insights and personalized plans to improve gut microbiome composition, thereby enhancing cognitive sharpness and overall brain health. The application will serve as a digital companion for individuals seeking to maintain or improve their cognitive function as they age, focusing on diet, supplementation, and lifestyle adjustments.
**2. TECH STACK:**
- **Frontend Framework:** React (using Create React App or Vite for setup)
- **Styling:** Tailwind CSS for rapid UI development and consistent design.
- **State Management:** Zustand or Redux Toolkit for managing global application state. Zustand is preferred for its simplicity in an SPA.
- **Routing:** React Router DOM for navigation within the SPA.
- **Form Handling:** React Hook Form with Zod for validation.
- **Date Handling:** date-fns or Moment.js (date-fns preferred for immutability and tree-shaking).
- **Charting:** Chart.js or Recharts for visualizing user progress.
- **Icons:** Heroicons or Font Awesome.
- **Animations:** Framer Motion for smooth UI transitions and micro-interactions.
- **Local Storage:** For persisting user preferences and offline data.
**3. CORE FEATURES:**
- **User Authentication (Simulated/Basic):** For MVP, we can simulate login or use basic local storage persistence. In a full version, JWT authentication would be implemented.
- **Personalized Dashboard:** The central hub displaying a summary of the user's current status, daily goals, and key insights.
- **User Flow:** Upon login/app load, the dashboard presents a snapshot including a "Gut Health Score" (calculated based on inputs), "Cognitive Readiness" indicator, and quick links to log daily activities. It shows upcoming recommendations.
- **Diet Logging & Recommendations:** Users can log meals, and the app provides personalized dietary suggestions.
- **User Flow:** User navigates to the "Diet" section. They can either manually log meals (e.g., 'Breakfast: Oatmeal with berries', 'Lunch: Chicken salad') or select from a predefined list. The app analyzes logged items against their profile and provides recommendations like 'Consider adding more fiber-rich foods like lentils' or 'This meal is low in prebiotics; try adding a banana.' Recommendations are tailored based on the user's profile (e.g., low FODMAP if specified).
- **Probiotic & Prebiotic Tracker:** Users can log their probiotic/prebiotic supplements and foods.
- **User Flow:** Navigate to "Supplements". User can add 'Lactobacillus acidophilus' with dosage and frequency. The app tracks adherence and provides information about the benefits of logged items, linking them to cognitive function.
- **Lifestyle Tracking (Sleep, Exercise, Stress):** Modules for users to input data about sleep duration/quality, exercise type/duration, and perceived stress levels.
- **User Flow:** In the "Lifestyle" section, users can log their sleep (e.g., '7.5 hours, good quality'), exercise (e.g., '30 min brisk walk'), and stress ('Moderate'). The app correlates this data with other inputs.
- **Cognitive Exercises:** A section with simple, engaging cognitive games (e.g., memory match, pattern recognition, quick math problems).
- **User Flow:** Access "Brain Games". User selects a game, plays it, and receives a score. The app tracks performance over time, showing improvement trends.
- **Progress & Insights:** Visualizations of tracked data over time.
- **User Flow:** Navigate to "Progress". Users see charts showing trends in their Gut Health Score, Cognitive Scores, adherence to diet plans, sleep quality, etc. Insights like 'Your cognitive scores improved by 10% this month, correlating with increased fiber intake' are displayed.
**4. UI/UX DESIGN:**
- **Layout:** Single-page application with a persistent sidebar navigation (desktop) or a bottom navigation bar (mobile). Main content area displays the active section. Clean, card-based design for displaying information snippets.
- **Color Palette:** Calming and trustworthy colors. Primary: A deep, reassuring blue (#1E3A8A). Secondary: A vibrant, healthy green (#10B981). Accent: A warm, energetic orange/yellow (#F59E0B) for calls to action and highlights. Neutrals: Grays (#F3F4F6, #6B7280, #1F2937) for backgrounds, text, and borders.
- **Typography:** Clean, readable sans-serif fonts. Headings: Inter (Bold, SemiBold). Body Text: Inter (Regular). Ensure good contrast and legible sizes.
- **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Components should adapt fluidly. Use Tailwind's responsive modifiers (sm:, md:, lg:).
- **Interactions:** Subtle hover effects on buttons and cards. Smooth page transitions using Framer Motion. Loading spinners or skeletons for data fetching.
**5. DATA MODEL (State Management using Zustand):**
- **`userProfile` store:**
- `userId`: string
- `age`: number
- `gender`: 'male' | 'female' | 'other'
- `dietaryPreferences`: string[] (e.g., 'vegetarian', 'low-carb')
- `healthConditions`: string[] (e.g., 'IBS', 'high-blood-pressure')
- `cognitiveGoals`: string[] (e.g., 'improve memory', 'increase focus')
- `gutHealthScore`: number (0-100)
- `cognitiveReadiness`: number (0-100)
- **`dietLog` store:**
- `entries`: Array<{ id: string, date: string, mealType: 'breakfast' | 'lunch' | 'dinner' | 'snack', description: string, nutrients?: object }>
- `recommendations`: string[]
- **`supplementLog` store:**
- `entries`: Array<{ id: string, name: string, type: 'probiotic' | 'prebiotic', dosage: string, frequency: string, dateAdded: string }>
- `info`: object (links to supplement details)
- **`lifestyleLog` store:**
- `sleep`: Array<{ id: string, date: string, duration: number, quality: 'poor' | 'average' | 'good' }>
- `exercise`: Array<{ id: string, date: string, activity: string, duration: number }>
- `stress`: Array<{ id: string, date: string, level: 'low' | 'moderate' | 'high' }>
- **`cognitiveGames` store:**
- `performance`: object { gameId: string, date: string, score: number, accuracy: number }
- `availableGames`: Array<{ id: string, name: string, description: string }>
**Mock Data Format Example (`dietLog.entries`):**
```json
[
{
"id": "d1",
"date": "2024-03-15T09:00:00Z",
"mealType": "breakfast",
"description": "Oatmeal with blueberries, chia seeds, and a drizzle of honey.",
"nutrients": { "fiber": 12, "protein": 8, "sugar": 15, "prebiotics": 3 }
},
{
"id": "d2",
"date": "2024-03-15T13:00:00Z",
"mealType": "lunch",
"description": "Grilled chicken salad with mixed greens, cucumber, tomatoes, and olive oil vinaigrette.",
"nutrients": { "protein": 30, "fiber": 5, "fat": 20 }
}
]
```
**6. COMPONENT BREAKDOWN:**
- **`App.js`:** Main application component, sets up routing, global layout, and state providers.
- **`NavigationSidebar.jsx` / `BottomNavigationBar.jsx`:** Handles main navigation links and active state.
- **`DashboardPage.jsx`:** Displays summary cards, recent logs, and key insights. Uses `SummaryCard.jsx`, `ActivityLoggerPrompt.jsx`.
- **`DietLogPage.jsx`:** Contains `MealLoggingForm.jsx`, `DietRecommendations.jsx`, `DietHistory.jsx`.
- **`SupplementTrackerPage.jsx`:** Contains `SupplementForm.jsx`, `SupplementList.jsx`, `SupplementInfoModal.jsx`.
- **`LifestyleTrackerPage.jsx`:** Contains `SleepForm.jsx`, `ExerciseForm.jsx`, `StressInput.jsx`, `LifestyleTrendsChart.jsx`.
- **`CognitiveGamesPage.jsx`:** Contains `GameSelection.jsx`, individual game components (`MemoryMatch.jsx`, `PatternRecognition.jsx`), `GameResults.jsx`.
- **`ProgressPage.jsx`:** Contains `ProgressChart.jsx` (reusable for different data types), `InsightDisplay.jsx`.
- **`UserProfileSettings.jsx`:** Form for editing user profile data.
- **`SummaryCard.jsx`:** Displays a single metric (e.g., Gut Health Score) with trend indicator. Props: `title`, `value`, `trend`.
- **`ActivityLoggerPrompt.jsx`:** Small modal or inline prompt to quickly log an activity. Props: `activityType`.
- **`ChartComponent.jsx`:** Reusable wrapper for Chart.js/Recharts. Props: `chartData`, `chartOptions`, `type`.
- **`Modal.jsx`:** Generic modal component. Props: `isOpen`, `onClose`, `children`.
- **`Button.jsx`:** Custom button component with styling variations. Props: `onClick`, `children`, `variant`, `size`.
- **`Input.jsx`:** Custom input field. Props: `label`, `value`, `onChange`, `type`, `error`.
**7. ANIMATIONS & INTERACTIONS:**
- **Page Transitions:** Use `AnimatePresence` from Framer Motion for fade or slide animations when navigating between sections.
- **Card/Element Entrance:** Elements fade in or slide up as they enter the viewport.
- **Button Hovers:** Subtle scale or background color change on hover.
- **Chart Interactions:** Tooltips appearing on hover over data points in charts.
- **Loading States:** Use skeleton loaders or spinners (e.g., `react-spinners`) while data is being fetched. Indicate loading states clearly.
- **Micro-interactions:** Animated checkmarks upon successful logging, subtle bounce effect on interactive elements.
**8. EDGE CASES:**
- **Empty States:** All sections (Diet, Supplements, Lifestyle, Games, Progress) must have clear, user-friendly empty states with prompts on how to get started (e.g., "Log your first meal to see recommendations!").
- **Error Handling:** Network errors (API failures) should display user-friendly messages. Form validation errors should be clearly highlighted next to the relevant fields using `React Hook Form` and `Zod`.
- **Data Validation:** Implement robust validation for all user inputs (numeric ranges, required fields, valid formats) using Zod.
- **Accessibility (a11y):** Ensure semantic HTML, proper ARIA attributes where needed, sufficient color contrast, keyboard navigability, and focus management.
- **Offline Support (Basic):** Utilize local storage to cache essential user data and settings. Logged activities can be stored locally and synced when connectivity is restored.
**9. SAMPLE DATA:**
- **`userProfile`:**
```json
{
"userId": "user123",
"age": 62,
"gender": "female",
"dietaryPreferences": ["vegetarian", "high-fiber"],
"healthConditions": ["mild-arthritis"],
"cognitiveGoals": ["improve memory", "maintain focus"],
"gutHealthScore": 75,
"cognitiveReadiness": 82
}
```
- **`dietLog.entries` (Example already provided in Data Model section)**
- **`supplementLog.entries`:**
```json
[
{ "id": "s1", "name": "Lactobacillus rhamnosus GG", "type": "probiotic", "dosage": "10 Billion CFU", "frequency": "Once daily", "dateAdded": "2024-03-10" },
{ "id": "s2", "name": "Inulin Fiber", "type": "prebiotic", "dosage": "5g", "frequency": "With breakfast", "dateAdded": "2024-03-12" }
]
```
- **`lifestyleLog` (Example: sleep entry):**
```json
{
"sleep": [
{ "id": "sl1", "date": "2024-03-14", "duration": 7.2, "quality": "good" },
{ "id": "sl2", "date": "2024-03-13", "duration": 6.5, "quality": "average" }
]
}
```
- **`cognitiveGames.performance`:**
```json
{
"memory_match_round1": { "date": "2024-03-14", "score": 8, "accuracy": 0.95 },
"quick_math_level2": { "date": "2024-03-15", "score": 15, "accuracy": 0.88 }
}
```
- **`cognitiveGames.availableGames`:**
```json
[
{ "id": "memory_match", "name": "Memory Match", "description": "Test your short-term memory." },
{ "id": "pattern_recognition", "name": "Pattern Recognition", "description": "Identify the next item in a sequence." },
{ "id": "quick_math", "name": "Quick Math", "description": "Solve basic arithmetic problems quickly." }
]
```
**10. DEPLOYMENT NOTES:**
- **Build Tool:** Vite is recommended for its speed. Use `npm run build` or `yarn build`.
- **Environment Variables:** Use `.env` files for configuration (e.g., API URLs if external APIs are added later). `VITE_API_URL`. Variables prefixed with `VITE_` are exposed to the client.
- **Performance Optimizations:**
- Code Splitting: Vite handles this automatically for routes and component imports.
- Image Optimization: Use appropriate formats and sizes. Consider a CDN for production.
- Memoization: Use `React.memo`, `useMemo`, `useCallback` judiciously to prevent unnecessary re-renders.
- Bundle Analysis: Use tools like `rollup-plugin-visualizer` to analyze bundle size and identify large dependencies.
- **HTTPS:** Ensure deployment is over HTTPS.
- **Caching:** Implement appropriate browser caching strategies for static assets.
- **Error Tracking:** Integrate a service like Sentry or LogRocket for production error monitoring.
- **CI/CD:** Set up a Continuous Integration/Continuous Deployment pipeline (e.g., using GitHub Actions, GitLab CI) for automated testing and deployment.