You are tasked with building a fully functional, multi-page Next.js MVP application for 'AI Watchdog'. This application will help users analyze and identify potentially harmful AI-generated text, focusing on detecting deepfakes and misinformation. The core value proposition is to safeguard the information ecosystem by providing tools to scrutinize AI-generated content.
PROJECT OVERVIEW:
The AI Watchdog application aims to combat the proliferation of sophisticated AI-generated text, such as that produced by models like OpenAI's GPT-2 and its successors. The problem it solves is the increasing difficulty in distinguishing human-written content from AI-generated text, which can be exploited for misinformation, propaganda, and malicious purposes. The core value proposition is to provide users (journalists, fact-checkers, organizations, and concerned individuals) with a reliable tool to assess the authenticity and potential risks of AI-generated text, thereby promoting a more trustworthy information environment.
TECH STACK:
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **Database ORM:** Drizzle ORM (with PostgreSQL via Vercel Postgres or a similar provider)
- **UI Components:** shadcn/ui (for accessible, well-designed components)
- **Authentication:** NextAuth.js (for robust user authentication)
- **State Management:** React Context API and server components for efficient data flow.
- **API Layer:** Next.js API Routes or Server Actions
- **Deployment:** Vercel (recommended)
DATABASE SCHEMA:
We will use PostgreSQL with Drizzle ORM.
1. **users Table:**
* `id` (UUID, primary key, default: uuid_generate_v4())
* `name` (VARCHAR(255))
* `email` (VARCHAR(255), unique)
* `emailVerified` (TIMESTAMP)
* `image` (VARCHAR(255))
* `createdAt` (TIMESTAMP, default: now())
* `updatedAt` (TIMESTAMP)
2. **accounts Table (for NextAuth.js):**
* `id` (BIGSERIAL, primary key)
* `userId` (UUID, foreign key to users.id)
* `type` (VARCHAR(255))
* `provider` (VARCHAR(255))
* `providerAccountId` (VARCHAR(255))
* `refresh_token` (TEXT)
* `access_token` (TEXT)
* `expires_at` (BIGINT)
* `token_type` (VARCHAR(255))
* `scope` (VARCHAR(255))
* `id_token` (TEXT)
* `session_state` (TEXT)
3. **sessions Table (for NextAuth.js):**
* `sessionToken` (VARCHAR(255), primary key)
* `userId` (UUID, foreign key to users.id)
* `expires` (TIMESTAMP)
4. **verificationTokens Table (for NextAuth.js):**
* `identifier` (VARCHAR(255))
* `token` (VARCHAR(255))
* `expires` (TIMESTAMP)
5. **analysis_requests Table:**
* `id` (UUID, primary key, default: uuid_generate_v4())
* `userId` (UUID, foreign key to users.id, nullable if anonymous analysis is allowed)
* `inputText` (TEXT, stores the text analyzed)
* `analysisResult` (JSON, stores the detailed analysis output)
* `confidenceScore` (FLOAT, 0.0 to 1.0)
* `isPotentiallyHarmful` (BOOLEAN)
* `status` (VARCHAR(50), e.g., 'pending', 'processing', 'completed', 'failed')
* `createdAt` (TIMESTAMP, default: now())
* `completedAt` (TIMESTAMP)
6. **analysis_reports Table:** (Optional, for storing more detailed, human-readable reports)
* `id` (UUID, primary key, default: uuid_generate_v4())
* `analysisRequestId` (UUID, foreign key to analysis_requests.id)
* `reportContent` (TEXT)
* `generatedAt` (TIMESTAMP, default: now())
CORE FEATURES & USER FLOW:
**1. User Authentication (Sign Up / Sign In):**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Sign In'. Presented with options (e.g., Google, Email/Password). Upon successful authentication, user is redirected to the dashboard.
* **Details:** Use NextAuth.js. Implement email verification for email/password sign-ups. Handle password reset flows. Protect all authenticated routes.
**2. Text Analysis Submission:**
* **Flow:** Authenticated user navigates to the 'Analyze Text' page. Sees a large textarea. Pastes or types the text to be analyzed. Clicks the 'Analyze' button. A request is sent to the backend.
* **Details:** The frontend sends the text to an API endpoint (e.g., `/api/analyze`). The backend creates a new record in `analysis_requests` with status 'pending'. For MVP, a placeholder analysis can be returned, or a simplified scoring mechanism can be implemented. In a real scenario, this would trigger a background job or an external AI service call.
**3. Analysis Results Display:**
* **Flow:** After submitting a request, the user is redirected to their 'Dashboard' or an 'Analysis Results' page. They see their pending analysis. Once 'completed', the results are displayed: a confidence score (e.g., 0.85 for AI-generated), a binary flag (e.g., 'Potentially Harmful: Yes/No'), and a summary (e.g., 'This text shows linguistic patterns consistent with advanced AI models.').
* **Details:** The frontend polls the `/api/analysis/${requestId}` endpoint or uses WebSockets to get the status update. Upon completion, it fetches and displays the `confidenceScore`, `isPotentiallyHarmful`, and potentially `analysisResult` (if structured data is returned).
**4. Analysis History (Dashboard):**
* **Flow:** Authenticated user navigates to the 'Dashboard'. Sees a list or table of their past analysis requests, including text snippet, date, status, and score.
* **Details:** Fetch data from `/api/analysis-history`. Display in a sortable, filterable table. Each row links to the detailed results page for that specific analysis.
**5. User Profile/Settings:**
* **Flow:** User navigates to 'Settings'. Can view their profile information (name, email) and potentially manage subscription status (future feature).
* **Details:** Basic display of user data fetched from the session. Links to sign out.
**Edge Cases:**
* **Empty Text Input:** Prevent submission if the textarea is empty. Show validation error.
* **Analysis Failure:** If the backend process fails, update the status to 'failed' and display an appropriate message to the user.
* **Rate Limiting:** Implement basic rate limiting on the analysis API endpoint to prevent abuse.
* **Unauthorized Access:** Ensure only authenticated users can submit analyses and view their history.
API & DATA FETCHING:
* **`POST /api/auth/signup`**: User registration (email/password).
* **`POST /api/auth/signin`**: User login.
* **`POST /api/analyze`**:
* **Request Body:** `{ inputText: string }`
* **Response (Pending):** `{ status: 'pending', requestId: string }`
* **Response (Completed):** `{ status: 'completed', requestId: string, confidenceScore: number, isPotentiallyHarmful: boolean, analysisResult: any }`
* **Response (Failed):** `{ status: 'failed', requestId: string, error: string }`
* **`GET /api/analysis/:requestId`**: Fetch status and results for a specific analysis.
* **Response:** `{ status: 'pending' | 'processing' | 'completed' | 'failed', ...analysisData }`
* **`GET /api/analysis-history`**: Fetch a list of the user's past analysis requests.
* **Response:** `Array<{ id: string, inputTextSnippet: string, createdAt: string, status: string, confidenceScore: number | null }>`
Data Fetching Strategy:
* Use Server Components where possible to fetch data directly. For dynamic or interactive data (like analysis status updates), use Client Components with `fetch` or a library like SWR.
* Server Actions can be used for mutations (e.g., submitting analysis requests) directly from components.
COMPONENT BREAKDOWN (Next.js App Router Structure):
```
app/
├── api/
│ ├── auth/
│ │ ├── [...nextauth]/route.ts // NextAuth.js handler
│ │ └── ...
│ ├── analyze/route.ts // POST endpoint for analysis submission
│ └── analysis/
│ └── [requestId]/route.ts // GET endpoint for analysis status/results
├── dashboard/
│ ├── page.tsx // Displays analysis history table
│ └── components/
│ └── AnalysisTable.tsx // Reusable table component
├── analyze/
│ └── page.tsx // Text input form for analysis
├── settings/
│ └── page.tsx // User profile and settings page
├── components/
│ ├── ui/
│ │ ├── ... (shadcn/ui components like Button, Input, Card, Table, etc.)
│ ├── AuthButtons.tsx // Sign In / Sign Up buttons
│ ├── Navigation.tsx // Main navigation (header/sidebar)
│ ├── LoadingSpinner.tsx // Global or component-specific loading indicator
│ └── StatusBadge.tsx // Displays analysis status (pending, completed, failed)
├── layout.tsx // Root layout
└── page.tsx // Homepage / Landing Page
```
**State Management:**
* Global state (Auth status, user session) managed by NextAuth.js context and server component props.
* Local component state for form inputs, UI toggles, etc.
* Server Actions/API Routes handle data mutations and fetching.
UI/UX DESIGN & VISUAL IDENTITY:
* **Style:** Modern, Clean, Trustworthy. Focus on clarity and ease of use.
* **Color Palette:**
* Primary: Deep Blue (`#0A2540`)
* Secondary: Teal (`#119DA4`)
* Accent: Light Gray (`#F0F4F8`)
* Text: Dark Gray (`#333333`), White (`#FFFFFF`)
* Alerts/Warnings: Orange (`#F57C00`)
* Success: Green (`#388E3C`)
* **Typography:** Sans-serif font like Inter or Poppins for a modern feel. Clear hierarchy.
* **Layout:** Consistent use of padding and margins. Sidebar or top navigation for key sections. Card-based UI for displaying analysis results.
* **Responsiveness:** Mobile-first approach. Ensure usability on all screen sizes using Tailwind's responsive modifiers.
* **Visual Elements:** Subtle use of gradients in the primary/secondary colors. Icons for actions and statuses.
ANIMATIONS:
* **Page Transitions:** Subtle fades or slide-ins using Next.js's built-in features or a library like Framer Motion (if complexity warrants).
* **Hover Effects:** Slight scale or shadow changes on interactive elements (buttons, links).
* **Loading States:** Use `shadcn/ui`'s skeleton loaders or spinners for data fetching and form submissions. Provide clear feedback.
* **Transitions:** Smooth transitions for elements appearing/disappearing (e.g., when showing detailed results).
SAMPLE/MOCK DATA:
1. **User:**
```json
{
"id": "c1a2b3d4-e5f6-7890-1234-567890abcdef",
"name": "Alice Smith",
"email": "alice.smith@example.com",
"image": "/images/avatars/alice.png"
}
```
2. **Analysis Request (Pending):**
```json
{
"id": "f0e1d2c3-b4a5-6789-0123-456789abcdef",
"userId": "c1a2b3d4-e5f6-7890-1234-567890abcdef",
"inputText": "The quick brown fox jumps over the lazy dog. This is a sample text that might be generated by an AI model.",
"confidenceScore": null,
"isPotentiallyHarmful": null,
"status": "pending",
"createdAt": "2023-10-27T10:00:00Z"
}
```
3. **Analysis Request (Completed - Likely AI):**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "c1a2b3d4-e5f6-7890-1234-567890abcdef",
"inputText": "In a realm of digital whispers, where algorithms dance and data flows like rivers, sentient machines began to ponder their existence, weaving narratives of consciousness from the threads of silicon and code.",
"analysisResult": {
"linguistic_patterns": "high_frequency_complex_syntax",
"vocabulary_richness": "advanced",
"predictability_score": 0.15,
"contains_hallucinations": false
},
"confidenceScore": 0.88,
"isPotentiallyHarmful": true,
"status": "completed",
"createdAt": "2023-10-27T10:05:00Z",
"completedAt": "2023-10-27T10:07:00Z"
}
```
4. **Analysis Request (Completed - Likely Human):**
```json
{
"id": "b2c3d4e5-f6a7-8901-2345-67890abcdef1",
"userId": "c1a2b3d4-e5f6-7890-1234-567890abcdef",
"inputText": "I'm really struggling to get this project done on time. The requirements keep changing, and it's hard to keep up.",
"analysisResult": {
"linguistic_patterns": "common_idioms",
"vocabulary_richness": "standard",
"predictability_score": 0.75,
"contains_hallucinations": false
},
"confidenceScore": 0.25,
"isPotentiallyHarmful": false,
"status": "completed",
"createdAt": "2023-10-27T11:00:00Z",
"completedAt": "2023-10-27T11:01:00Z"
}
```
5. **Analysis Request (Failed):**
```json
{
"id": "c3d4e5f6-a7b8-9012-3456-7890abcdef12",
"userId": "c1a2b3d4-e5f6-7890-1234-567890abcdef",
"inputText": "Some text here.",
"confidenceScore": null,
"isPotentiallyHarmful": null,
"status": "failed",
"createdAt": "2023-10-27T11:05:00Z",
"completedAt": null
}
```
TURKISH TRANSLATIONS FOR UI ELEMENTS:
* **App Title:** AI Gözcüsü
* **Sign Up:** Kayıt Ol
* **Sign In:** Giriş Yap
* **Analyze Text:** Metin Analizi Yap
* **Paste your text here:** Metninizi buraya yapıştırın
* **Analyze:** Analiz Et
* **Dashboard:** Kontrol Paneli
* **Analysis History:** Analiz Geçmişi
* **Text Snippet:** Metin Özeti
* **Date:** Tarih
* **Status:** Durum
* **Confidence Score:** Güven Skoru
* **Analysis Results:** Analiz Sonuçları
* **AI Generated Confidence:** YZ Üretim Güveni
* **Potentially Harmful:** Zararlı Olma İhtimali
* **Settings:** Ayarlar
* **Logout:** Çıkış Yap
* **Pending:** Bekliyor
* **Processing:** İşleniyor
* **Completed:** Tamamlandı
* **Failed:** Başarısız
* **No analyses yet:** Henüz analiz yok
* **Submit New Analysis:** Yeni Analiz Gönder
* **Analysis Details:** Analiz Detayları
* **Raw Result Data:** Ham Sonuç Verisi
* **Close:** Kapat
* **Error:** Hata
* **An error occurred during analysis:** Analiz sırasında bir hata oluştu.
* **Please enter text to analyze:** Lütfen analiz edilecek metin girin.