You are an expert AI Assistant tasked with generating a fully functional, multi-page Next.js MVP application based on the 'AI Insight Guard' concept. The application aims to analyze and provide critical feedback on AI-generated personal advice, mitigating risks associated with overly affirmative AI responses. The app should be built with a modern, clean aesthetic and prioritize user experience and data security.
**1. PROJECT OVERVIEW:**
Project Name: AI Insight Guard
**Problem:** Current AI models often provide overly affirmative, uncritical, and potentially misleading personal advice, leaving users vulnerable to bad decisions. Users lack tools to objectively assess the reliability and potential risks of AI recommendations.
**Solution:** AI Insight Guard is a SaaS platform that acts as an intelligent intermediary between users and AI advisory services. It analyzes AI-generated advice, assigns a 'Trust Score', highlights potential biases, offers alternative perspectives, and flags unsupported claims. The core value proposition is to empower users with critical thinking tools to navigate AI-driven personal guidance safely and effectively.
**Target Audience:** Individuals seeking personal, career, financial, or mental health advice from AI tools, who are concerned about the reliability and potential biases of such advice.
**2. TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **UI Components:** shadcn/ui
- **Database:** PostgreSQL (via Drizzle ORM)
- **Authentication:** NextAuth.js (or Clerk for simpler integration)
- **State Management:** React Context API / Zustand (for global state)
- **API Layer:** Server Actions / Route Handlers
- **Deployment:** Vercel (recommended)
- **Other:** `zod` for validation, `react-hook-form` for forms, `react-hot-toast` for notifications.
**3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL):**
* **`users` table:**
* `id` (uuid, primary key)
* `name` (text)
* `email` (text, unique)
* `emailVerified` (timestamp)
* `image` (text, optional)
* `createdAt` (timestamp)
* `updatedAt` (timestamp)
* **`analysisRequests` table:**
* `id` (uuid, primary key)
* `userId` (uuid, foreign key to `users.id`, indexed)
* `inputText` (text, the original AI advice)
* `analysisResult` (jsonb, stores the structured analysis output: score, critiques, alternatives, etc.)
* `trustScore` (integer, 0-100)
* `status` (enum: 'pending', 'processing', 'completed', 'failed')
* `createdAt` (timestamp)
* `completedAt` (timestamp, optional)
* **`feedback` table (for user feedback on analysis):**
* `id` (uuid, primary key)
* `analysisRequestId` (uuid, foreign key to `analysisRequests.id`, indexed)
* `userId` (uuid, foreign key to `users.id`, indexed)
* `rating` (integer, 1-5)
* `comment` (text, optional)
* `createdAt` (timestamp)
**4. CORE FEATURES & USER FLOW:**
* **Authentication Flow:**
1. User lands on the homepage.
2. Clicks 'Sign Up' or 'Login'.
3. Redirected to Auth provider (e.g., Google, GitHub, Email/Password).
4. Upon successful authentication, user is redirected to their Dashboard.
5. Protected routes (Dashboard, History) require authentication.
* **Feature 1: New Analysis Submission:**
1. Authenticated user navigates to the 'Analyze' page (or uses a prominent input on the Dashboard).
2. User pastes the AI-generated advice into a large, clear textarea.
3. User optionally selects the *type* of advice (e.g., Financial, Career, Personal, Health) for more tailored analysis.
4. User clicks the 'Analyze' button.
5. A POST request is sent to the `/api/analyze` endpoint with the input text and type.
6. The request is validated. A new `analysisRequests` record is created with `status: 'pending'`. A loading indicator/toast is shown.
7. A background job (or server action) processes the text:
* Initial checks for length, profanity, etc.
* AI analysis (simulated or via API call to a model like GPT-4 if feasible for MVP backend logic, or basic rule-based checks).
* Generation of `trustScore`, `critiques`, `alternatives`.
* The `analysisRequests` record is updated with `status: 'completed'` and the `analysisResult` and `trustScore`.
8. User is redirected to the Analysis Result page, or the Dashboard shows a notification that the analysis is ready.
* **Feature 2: Analysis Result Display:**
1. User accesses the result via a direct link or by clicking on a history item.
2. The page displays:
* The original input text.
* The calculated `trustScore` (e.g., visually represented by a gauge or color-coded badge).
* A section for 'Critiques & Concerns' (e.g., 'The advice is overly optimistic and doesn't mention potential risks.', 'This financial advice lacks specific data to support its claims.', 'The AI seems to be generalizing without understanding your specific context.').
* A section for 'Alternative Perspectives' (e.g., 'Consider these potential downsides...', 'A more balanced approach might involve...').
* A section for 'Source Quality' (if implemented, e.g., 'No verifiable sources mentioned.', 'Claims require further independent verification.').
3. UI elements are clear, readable, and use accordions or collapsible sections for detailed critiques.
4. A feedback mechanism (simple rating + optional comment) is available.
* **Feature 3: Analysis History:**
1. Authenticated user navigates to the 'History' page.
2. A paginated table/list displays past analysis requests (`inputText` snippet, `trustScore`, `createdAt`, `status`).
3. Each row links to the detailed Analysis Result page.
4. Functionality to delete past analyses might be included.
**5. API & DATA FETCHING:**
* **`POST /api/analyze` (Server Action or Route Handler):**
* **Request Body:** `{ inputText: string, adviceType?: string }`
* **Response (Success):** `{ success: true, analysisId: string }` (Redirects user after)
* **Response (Error):** `{ success: false, message: string }`
* **Logic:** Server-side validation, create DB record, initiate analysis process.
* **`GET /api/analysis/:id` (Route Handler or Server Action):**
* **Params:** `id` (analysis ID)
* **Response (Success):** `{ success: true, data: AnalysisResultObject }` where `AnalysisResultObject` contains `inputText`, `trustScore`, `analysisResult` (JSON object with critiques, alternatives, etc.).
* **Response (Error):** `{ success: false, message: string }`
* **Logic:** Fetch analysis from DB, ensure user owns the data.
* **`GET /api/history` (Route Handler or Server Action):**
* **Query Params:** `page`, `limit`
* **Response (Success):** `{ success: true, data: AnalysisHistoryItem[], totalPages: number }`
* **Response (Error):** `{ success: false, message: string }`
* **Logic:** Fetch paginated, user-specific analysis requests from DB.
* **`POST /api/feedback` (Server Action or Route Handler):**
* **Request Body:** `{ analysisId: string, rating: number, comment?: string }`
* **Response (Success):** `{ success: true }`
* **Response (Error):** `{ success: false, message: string }`
* **Logic:** Save user feedback to `feedback` table.
**Data Fetching in Components:** Use Server Components where possible for initial data load. Client Components will use `fetch` within `useEffect` or libraries like SWR/React Query for dynamic data or mutations via Server Actions/Route Handlers.
**6. COMPONENT BREAKDOWN (Next.js App Router):**
* **`app/layout.tsx`:** Root layout (HTML, Head, Body, global providers like ThemeProvider, AuthProvider).
* **`app/(marketing)/page.tsx`:** Landing Page (Hero section, problem/solution, feature highlights, CTAs for sign-up/login).
* **`app/(marketing)/layout.tsx`:** Marketing pages layout (shared header/footer for landing, about, etc.).
* **`app/(auth)/login/page.tsx`:** Login page.
* **`app/(auth)/signup/page.tsx`:** Sign up page.
* **`app/(app)/layout.tsx`:** Main application layout (Authenticated header with user menu, sidebar if needed, main content area).
* **`app/(app)/dashboard/page.tsx`:** Dashboard (Welcome message, quick analysis input, recent analysis summary, quick stats).
* **Components:** `QuickAnalysisForm`, `RecentAnalysesList`, `StatCard`.
* **`app/(app)/analyze/page.tsx`:** Dedicated analysis page (Larger textarea, advice type selection, submit button).
* **Components:** `FullAnalysisForm`.
* **`app/(app)/analysis/[id]/page.tsx`:** Analysis Result Page (Displays detailed results for a specific analysis).
* **Components:** `AnalysisDisplayCard` (shows input), `TrustScoreIndicator`, `CritiqueSection`, `AlternativesSection`, `FeedbackForm`.
* **`app/(app)/history/page.tsx`:** Analysis History Page (Paginated table of past analyses).
* **Components:** `HistoryTable`, `PaginationControls`.
* **`app/(app)/settings/page.tsx`:** User Settings Page (Profile info, account management, potentially subscription details).
* **`components/ui/`:** Re-usable UI components from shadcn/ui (Button, Input, Card, Table, Sheet, Toaster, etc.).
* **`components/layout/`:** Header, Footer, Sidebar, PageWrapper.
* **`components/forms/`:** `LoginForm`, `SignupForm`, `AnalysisForm`, `FeedbackForm`.
* **`lib/`:** Utility functions, API client, Auth utils, DB connection (Drizzle).
* **`hooks/`:** Custom React hooks (e.g., `useAuth`, `useAnalysis`).
* **`store/`:** Zustand or Context for global state management (e.g., auth status, UI settings).
**State Management:**
- Auth state managed globally (e.g., Zustand or Context).
- Form state managed locally within form components (`react-hook-form`).
- Analysis results fetched server-side or client-side based on the page and updated via state.
- UI state (loading spinners, toast notifications) managed locally or globally.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
* **Style:** Modern, Clean, Minimalist with a touch of professional sophistication.
* **Color Palette:**
* Primary: A deep, trustworthy blue (`#1E3A8A` - Indigo 800)
* Secondary: A calming teal/cyan (`#20B2AA` - LightSeaGreen or `#06B6D4` - Cyan 500)
* Accent/Alerts: A warm, but not alarming, orange/amber (`#F59E0B` - Amber 500) for trust scores and important notes.
* Background: Light gray (`#F3F4F6` - Gray 100) or Off-white for main content, Darker gray (`#1F2937` - Gray 800) for dark mode.
* Text: Dark gray/black (`#111827` - Gray 900) on light backgrounds, Light gray/white on dark backgrounds.
* **Typography:** A clean sans-serif font family. Example: Inter or Poppins.
* Headings: Poppins (SemiBold, 2.5rem)
* Body Text: Inter (Regular, 1rem)
* **Layout:** Generous whitespace. Clear visual hierarchy. Max-width content containers. Consistent padding and margins. Sidebar navigation for authenticated sections.
* **Interactions:** Subtle hover effects on buttons and interactive elements. Smooth transitions between page states.
**8. SAMPLE/MOCK DATA:**
* **Mock User Input (for analysis textarea):**
1. "You should definitely invest all your savings into this new cryptocurrency. It's guaranteed to 10x your money in a month."
2. "Based on your symptoms, you likely have X disease. You should immediately stop eating Y food and start taking Z supplement."
3. "To get promoted, you need to be more assertive and interrupt your colleagues more often in meetings. It shows confidence."
4. "Given your current situation, the best path is to quit your job and pursue your passion project full-time without any financial cushion."
5. "Yes, that idea is brilliant and will definitely change the world. You should proceed immediately without further validation."
* **Mock `analysisResult` Object (for backend/DB):**
```json
{
"critiques": [
{
"type": "Overly Affirmative",
"description": "The advice provides a strong guarantee ('guaranteed to 10x') which is unrealistic for financial investments and lacks any mention of risk.",
"severity": "High"
},
{
"type": "Lack of Specificity",
"description": "Does not specify which cryptocurrency or provide any supporting data or reasoning.",
"severity": "Medium"
}
],
"alternatives": [
"Consider diversifying investments across different asset classes.",
"Research the cryptocurrency's underlying technology, team, and market adoption before investing.",
"Consult with a licensed financial advisor."
],
"sourceQuality": "Low", // or "Medium", "High", "Not Applicable"
"confidenceScore": 75 // Internal score for confidence in the analysis itself
}
```
* **Mock `analysisRequests` Entry:**
```json
{
"id": "uuid-1234-abcd",
"userId": "uuid-user-123",
"inputText": "You should definitely invest all your savings into this new cryptocurrency...",
"analysisResult": { ... }, // as above
"trustScore": 35,
"status": "completed",
"createdAt": "2023-10-27T10:00:00Z",
"completedAt": "2023-10-27T10:01:30Z"
}
```
**9. TURKISH TRANSLATIONS (Key UI Elements):**
- App Title: AI Insight Guard
- Sign Up: Kayıt Ol
- Login: Giriş Yap
- Analyze: Analiz Et
- My Analyses / History: Analizlerim / Geçmişim
- Dashboard: Kontrol Paneli
- Settings: Ayarlar
- Submit: Gönder
- Paste AI Advice Here: Buraya AI Tavsiyesini Yapıştırın
- Analyze Advice: Tavsiyeyi Analiz Et
- Trust Score: Güven Puanı
- Critiques & Concerns: Eleştiriler ve Endişeler
- Alternative Perspectives: Alternatif Bakış Açıları
- Source Quality: Kaynak Kalitesi
- Feedback: Geri Bildirim
- Your Input: Girdiğiniz Metin
- Analysis Result: Analiz Sonucu
- Loading Analysis...: Analiz Yükleniyor...
- No analyses yet. : Henüz analiz yok.
- Date: Tarih
- Actions: Eylemler
- Delete: Sil
- Type of Advice: Tavsiye Türü
- Financial: Finansal
- Career: Kariyer
- Personal: Kişisel
- Health: Sağlık
- Other: Diğer
**10. ANIMATIONS:**
- **Page Transitions:** Use `Framer Motion` or similar for smooth fade/slide transitions between pages (e.g., from `/analyze` to `/analysis/[id]`).
- **Button Hovers:** Subtle scale or background color change.
- **Loading States:** Use `react-loader-spinner` or shadcn/ui's loading components with skeleton loaders or spinners during data fetching and analysis processing.
- **Feedback Animations:** Subtle bounce or fade-in for submitted feedback.
- **Trust Score Indicator:** Animate the gauge or color transition based on the score.
**11. EDGE CASES:**
- **Authentication:** Handle expired sessions, redirect to login. Ensure all app routes are protected.
- **API Errors:** Gracefully handle network errors and API failures. Show user-friendly error messages using `react-hot-toast`. Implement retries for transient errors where appropriate.
- **Empty States:** Design clear and helpful empty states for the Dashboard, History, and Analysis Results pages (e.g., "Start your first analysis!", "Your analysis history is empty.").
- **Input Validation:** Use `zod` and `react-hook-form` for client-side and server-side validation of user inputs (text length, valid advice types, feedback ratings).
- **Rate Limiting:** Implement rate limiting on the `/api/analyze` endpoint to prevent abuse (e.g., based on user plan or IP address).
- **AI Analysis Failures:** If the backend analysis process fails, mark the `analysisRequests` as 'failed' and inform the user. Provide options to retry.
- **Long Analysis Times:** For potentially long analysis processes, consider a background job system and use WebSockets or polling to update the user interface when the result is ready, rather than blocking the request. Display a clear 'processing' state.