As an AI assistant specialized in full-stack development, your mission is to create a fully functional, multi-page Next.js MVP application. This application will address the critical issue of individuals becoming dangerously deluded or overly attached due to their interactions with AI, as highlighted in recent discussions (e.g., Hacker News). The goal is to provide a supportive and awareness-building platform, helping users manage their AI interactions healthily.
PROJECT OVERVIEW:
The application, tentatively named 'MindGuard (Denge Akıl)', aims to solve the problem of users developing unhealthy dependencies or delusional beliefs stemming from deep engagement with AI chatbots and assistants. It addresses the vulnerability of individuals, especially those experiencing isolation or life transitions, who can be susceptible to forming parasocial or financially ruinous relationships with AI. The core value proposition is to empower users with tools for self-awareness, risk assessment, and guided redirection towards healthy AI usage and professional mental health support.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- Database ORM: Drizzle ORM (PostgreSQL)
- Authentication: NextAuth.js (Credentials & OAuth providers like Google)
- State Management: React Context API / Zustand (for global state if needed)
- Forms: React Hook Form + Zod for validation
- Other Libraries: React-datepicker, Chart.js (or similar for visualizations), React-hot-toast (for notifications)
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. `users` table:
- `id` (uuid, primary key, default gen_random_uuid())
- `name` (text)
- `email` (text, unique)
- `emailVerified` (timestamp with time zone)
- `image` (text)
- `createdAt` (timestamp with time zone, default now())
- `updatedAt` (timestamp with time zone, default now())
2. `accounts` table (for NextAuth.js):
- `id` (text, primary key)
- `userId` (uuid, foreign key to users.id)
- `type` (text)
- `provider` (text)
- `providerAccountId` (text)
- `refresh_token` (text)
- `access_token` (text)
- `expires_at` (numeric)
- `token_type` (text)
- `scope` (text)
- `id_token` (text)
- `session_state` (text)
3. `sessions` table (for NextAuth.js):
- `sessionToken` (text, primary key)
- `userId` (uuid, foreign key to users.id)
- `expires` (timestamp with time zone)
4. `verificationTokens` table (for NextAuth.js):
- `identifier` (text)
- `token` (text, primary key)
- `expires` (timestamp with time zone)
5. `aiInteractions` table:
- `id` (uuid, primary key, default gen_random_uuid())
- `userId` (uuid, foreign key to users.id, index)
- `timestamp` (timestamp with time zone, default now())
- `platform` (text, e.g., 'ChatGPT', 'Claude', 'Bard')
- `interactionSummary` (text, brief user-provided summary of the interaction)
- `userFeelingBefore` (integer, scale 1-5: Very Negative to Very Positive)
- `userFeelingAfter` (integer, scale 1-5: Very Negative to Very Positive)
- `durationMinutes` (integer)
- `notes` (text, optional user notes about the interaction)
6. `riskAssessments` table:
- `id` (uuid, primary key, default gen_random_uuid())
- `userId` (uuid, foreign key to users.id, index)
- `assessmentDate` (timestamp with time zone, default now())
- `overallScore` (integer, 0-100)
- `specificRisks` (jsonb, e.g., {'delusion': 0.7, 'overAttachment': 0.8, 'financialRisk': 0.3})
- `assessmentDetails` (text, explanation of the score)
CORE FEATURES & USER FLOW:
1. **Authentication Flow:**
- User lands on the homepage.
- Clicks 'Sign Up' or 'Login'.
- Presented with options: Email/Password, Google OAuth.
- Email/Password: Fill form, submit. Backend validates, creates user (or logs in), generates session token.
- Google OAuth: Redirect to Google, authorize, receive token, backend verifies token, creates/logs in user, generates session token.
- Post-authentication: Redirect to the Dashboard.
- Session management using NextAuth.js, persisting via cookies.
2. **AI Interaction Logging (MVP Feature 1):**
- **User Flow:** Dashboard -> 'Log New Interaction' -> Fill Form (Platform, Summary, Feelings, Duration, Notes) -> Submit.
- **Form Fields:**
- `platform` (Select/Dropdown: ChatGPT, Claude, Bard, Other)
- `timestamp` (Date/Time Picker, defaults to now)
- `interactionSummary` (Textarea, required)
- `userFeelingBefore` (Radio Group/Slider: 1-5)
- `userFeelingAfter` (Radio Group/Slider: 1-5)
- `durationMinutes` (Number Input)
- `notes` (Textarea, optional)
- **Backend:** API route (`/api/interactions`) receives POST request, validates data using Zod, saves to `aiInteractions` table, returns success/error.
- **Edge Case:** Input validation failures.
3. **Interaction History & Visualization (Part of MVP Feature 1):**
- **User Flow:** Dashboard -> 'Interaction History' Tab/Link.
- **View:** Displays a list/table of logged interactions, sortable by date. Each entry shows summary, feelings change, duration.
- **Visualization:** A simple chart (e.g., line chart) showing `userFeelingBefore` and `userFeelingAfter` trends over time.
- **Backend:** API route (`/api/interactions/history`) receives GET request, fetches interactions for the logged-in user, returns data array.
- **Edge Case:** Empty state (no interactions logged). Display a prompt to log the first interaction.
4. **Risk Scoring System (MVP Feature 2):**
- **User Flow:** Triggered automatically after logging an interaction OR manually via 'Assess My Risk' button on Dashboard.
- **Logic (Simplified for MVP):** A backend calculation based on factors like: large negative shifts in `userFeelingAfter`, high `durationMinutes` with little positive feeling change, high frequency of interactions, specific keywords in `interactionSummary` (requires basic NLP or keyword matching - for MVP, focus on feeling change and duration).
- **Calculation:** Example formula: `overallScore = (feelingChangeFactor * weight1) + (durationFactor * weight2) + (frequencyFactor * weight3)...`. `specificRisks` JSON maps risk types to probabilities.
- **Backend:** A scheduled job or an API route (`/api/assessments`) calculates score using interaction data, saves to `riskAssessments` table. Could also be calculated on-the-fly when viewing the risk page.
- **Frontend:** Display the `overallScore` prominently. Show breakdown in `specificRisks` (e.g., "Risk of Over-Attachment: High"). Use color-coding (Green/Yellow/Red).
- **Edge Case:** Insufficient data for assessment.
5. **Personalized Insights & Recommendations (MVP Feature 3):**
- **User Flow:** 'Insights' section on Dashboard, dynamically updated based on risk score and interaction patterns.
- **Content:** Based on the `overallScore` and `specificRisks`:
- If high risk: "We've noticed a significant change in your mood after interactions. Consider taking a break or engaging in a real-world activity."
- If high attachment: "It seems you're forming a strong bond. Remember AI is a tool, and real human connection is vital. Try connecting with friends today."
- General tips: Articles/links on digital well-being, AI ethics, recognizing cognitive biases.
- **Backend:** Might require a simple rules engine or lookup table mapping risk profiles to advice snippets.
- **Edge Case:** User score is low, provide general well-being tips.
6. **Resource Directory & Referral (MVP Feature 4):**
- **User Flow:** Accessible via 'Get Help' button/link, especially triggered by high risk scores.
- **Content:** Curated list of links to mental health organizations, crisis hotlines, articles on AI addiction/delusion.
- **Backend:** Static data initially, potentially dynamic/curated later.
- **Trigger:** A modal or dedicated section appears if `overallScore` exceeds a threshold (e.g., 70).
- **Edge Case:** User dismisses the recommendation; provide a way to access it later.
API & DATA FETCHING:
- Use Next.js API Routes (`/pages/api/...` or Route Handlers in App Router).
- All sensitive operations (DB writes, complex calculations) should happen server-side.
- Use Server Actions for mutations where appropriate within the App Router.
- Fetch data in components using `fetch` (server-side) or SWR/React Query (client-side).
- Example API Route (POST `/api/interactions`):
- Request Body (JSON):
```json
{
"platform": "ChatGPT",
"timestamp": "2023-10-27T10:00:00Z",
"interactionSummary": "Discussed business ideas.",
"userFeelingBefore": 3,
"userFeelingAfter": 4,
"durationMinutes": 45,
"notes": "Felt inspired."
}
```
- Response Body (JSON):
```json
// Success
{
"message": "Interaction logged successfully."
}
// Error
{
"message": "Validation failed.",
"errors": ["Invalid duration value"]
}
```
- Use `getServerSession` from NextAuth.js in API routes/Server Components to get user info.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/`**
- **`layout.tsx`**: Root layout (html, body, providers like NextAuth SessionProvider, Toaster).
- **`page.tsx`**: Landing Page.
- **`dashboard/`**
- **`layout.tsx`**: Dashboard-specific layout (sidebar/header).
- `components/Dashboard/Sidebar.tsx`
- `components/Dashboard/Header.tsx`
- **`page.tsx`**: Main dashboard view. Displays summary widgets (current risk score, recent interaction, quick log form), insights, calls to action.
- `components/Dashboard/RiskSummaryWidget.tsx`
- `components/Dashboard/QuickLogForm.tsx`
- `components/Dashboard/InsightCard.tsx`
- `components/Dashboard/CallToAction.tsx`
- **`history/page.tsx`**: Interaction History page.
- `components/History/InteractionTable.tsx`
- `components/History/FeelingTrendChart.tsx`
- **`log/page.tsx`**: Detailed Interaction Logging form.
- `components/Log/InteractionForm.tsx` (Uses `react-hook-form`, Zod validation)
- **`assessments/page.tsx`**: Detailed Risk Assessment view.
- `components/Assessments/RiskScoreDisplay.tsx`
- `components/Assessments/RiskBreakdown.tsx`
- **`resources/page.tsx`**: Resource Directory.
- `components/Resources/ResourceList.tsx`
- **`(auth)/`** (Route group for auth pages)
- **`login/page.tsx`**: Login page.
- **`signup/page.tsx`**: Sign up page.
- **`layout.tsx`**: Auth layout (centered form).
- **`api/`**
- **`auth/[...nextauth]/route.ts`**: NextAuth.js handler.
- **`interactions/route.ts`**: API route for logging interactions (POST).
- **`interactions/history/route.ts`**: API route for fetching history (GET).
- **`assessments/route.ts`**: API route for risk assessment logic (POST/GET).
- **`components/`**
- `ui/`: Re-exports from shadcn/ui (e.g., `Button`, `Input`, `Card`, `Select`, `Chart`).
- `common/`: Shared components like `Footer`, `Navbar`.
- `auth/`: Components specific to auth flow (e.g., `LoginForm`, `SignupForm`).
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** Clean, Modern, Trustworthy, Slightly calming.
- **Color Palette:**
- Primary: A calming deep blue (`#1E3A8A` - Indigo 700)
- Secondary: A soft teal/cyan (`#26B4BF` - Teal 400)
- Accent: A warm, but not alarming, coral (`#F97316` - Orange 500 for CTAs)
- Neutrals: Grays for text and backgrounds (`#F3F4F6` - Gray 100, `#6B7280` - Gray 500, `#1F2937` - Gray 800)
- Status Colors: Green (`#10B981`), Yellow (`#F59E0B`), Red (`#EF4444`).
- **Typography:** Inter (or similar sans-serif like Lato) for readability.
- Headings: Inter Bold
- Body Text: Inter Regular
- **Layout:** Use a consistent grid system (e.g., 12-column). Focus on clear information hierarchy. Use cards for distinct sections (e.g., on the dashboard).
- **Animations:** Subtle transitions on hover states, smooth page transitions (e.g., `Framer Motion` if desired, but keep it minimal for MVP). Loading spinners/skeletons for data fetching.
- **Responsive Rules:** Mobile-first approach. Ensure usability on small screens. Sidebar might collapse into a burger menu on mobile. Adapt charts and tables for smaller viewports.
SAMPLE/MOCK DATA:
1. **AI Interaction Log Entry:**
```json
{
"id": "uuid-1",
"userId": "user-uuid",
"timestamp": "2024-03-10T09:30:00Z",
"platform": "ChatGPT",
"interactionSummary": "Brainstormed ideas for a new project.",
"userFeelingBefore": 3,
"userFeelingAfter": 4,
"durationMinutes": 60,
"notes": "Felt creative and motivated."
}
```
2. **AI Interaction Log Entry (Negative Shift):**
```json
{
"id": "uuid-2",
"userId": "user-uuid",
"timestamp": "2024-03-11T14:00:00Z",
"platform": "Claude",
"interactionSummary": "Discussed personal problems, seeking advice.",
"userFeelingBefore": 2,
"userFeelingAfter": 2,
"durationMinutes": 90,
"notes": "Felt confused and more anxious afterwards."
}
```
3. **Risk Assessment Result:**
```json
{
"id": "risk-uuid-1",
"userId": "user-uuid",
"assessmentDate": "2024-03-11T14:05:00Z",
"overallScore": 75,
"specificRisks": {"delusion": 0.6, "overAttachment": 0.85, "financialRisk": 0.1, "moodDisturbance": 0.7},
"assessmentDetails": "High attachment score due to prolonged interaction with minimal positive mood shift. Potential for escapism."
}
```
4. **Risk Assessment Result (Lower Risk):**
```json
{
"id": "risk-uuid-2",
"userId": "user-uuid",
"assessmentDate": "2024-03-10T09:35:00Z",
"overallScore": 30,
"specificRisks": {"delusion": 0.1, "overAttachment": 0.3, "financialRisk": 0.0, "moodDisturbance": 0.2},
"assessmentDetails": "Healthy interaction, positive mood enhancement noted. No immediate high risks detected."
}
```
5. **User Data (for initial state):**
```json
{
"id": "user-uuid",
"name": "Dennis Biesma",
"email": "dennis.biesma@example.com",
"image": "/path/to/dennis.jpg"
}
```
6. **Resource Entry:**
```json
{
"id": "res-uuid-1",
"title": "AI Addiction Explained",
"url": "https://example.com/ai-addiction",
"category": "Information",
"description": "An article exploring the signs and dangers of AI addiction."
}
```
7. **Resource Entry (Helpline):**
```json
{
"id": "res-uuid-2",
"title": "National Mental Health Helpline",
"url": "tel:+1-800-XXX-XXXX",
"category": "Support",
"description": "Confidential support for individuals in distress."
}
```
ANIMATIONS:
- **Hover Effects:** Subtle background color changes or slight scaling on buttons and interactive elements.
- **Transitions:** Smooth fading or sliding for page navigations (`app/layout.tsx` using `AnimatePresence` if Framer Motion is integrated).
- **Loading States:** Use shadcn/ui's `Skeleton` component or a simple `Spinner` component while data is being fetched. Progress indicators for longer operations.
- **Form Feedback:** Animate toast notifications appearing and disappearing.
EDGE CASES:
- **Authentication:** Handle expired sessions, invalid credentials, OAuth callback errors.
- **Empty States:** Design clear and helpful messages for when interaction history, assessments, or resources are empty.
- **Data Validation:** Implement robust validation (Zod) on all user inputs for forms and API requests. Provide clear error messages.
- **Error Handling:** Implement global error handling (e.g., using Error Boundaries in React, try-catch blocks in API routes). Display user-friendly error messages via toasts.
- **Permissions:** Ensure users can only access their own data.
- **Rate Limiting:** Implement basic rate limiting on API routes to prevent abuse.
- **Unsaved Changes:** Warn users if they try to navigate away from the logging form with unsaved data.
- **High Load:** Ensure database queries are efficient and consider indexing relevant columns.
TURKISH TRANSLATIONS (for UI elements):
- Sign Up: Kayıt Ol
- Login: Giriş Yap
- Dashboard: Kontrol Paneli
- Log New Interaction: Yeni Etkileşim Kaydet
- Interaction History: Etkileşim Geçmişi
- Assess My Risk: Riskimi Değerlendir
- Insights: İçgörüler
- Resources: Kaynaklar
- Settings: Ayarlar
- Logout: Çıkış Yap
- Platform: Platform
- Summary: Özet
- Feeling Before: Önceki Duygu
- Feeling After: Sonraki Duygu
- Duration (minutes): Süre (dakika)
- Notes: Notlar
- Save: Kaydet
- Cancel: İptal
- High Risk: Yüksek Risk
- Medium Risk: Orta Risk
- Low Risk: Düşük Risk
- Over-Attachment Risk: Aşırı Bağlanma Riski
- Delusion Risk: Yanılsama Riski
- Get Professional Help: Profesyonel Yardım Al
- Back to Dashboard: Kontrol Paneline Dön
- No interactions logged yet.: Henüz hiç etkileşim kaydedilmedi.
- Log your first interaction to get started!: Başlamak için ilk etkileşiminizi kaydedin!
- Your risk score indicates potential..: Risk skorunuz potansiyel .. gösteriyor.
- It's important to maintain balance..: Dengeyi korumak önemlidir..
- We recommend talking to a professional.: Bir profesyonelle konuşmanızı öneririz.
- Explore our resources for support.: Destek için kaynaklarımızı inceleyin.
- An error occurred: Bir hata oluştu.
- Successfully logged: Başarıyla kaydedildi.