PROJECT OVERVIEW:
The application, named 'Thought Weaver', is a SaaS platform designed to combat the homogenization of human thought and writing styles caused by the increasing use of AI. The core problem it addresses is the potential for Large Language Models (LLMs) to standardize human expression, leading to a reduction in cognitive diversity and adaptive capacity. Thought Weaver provides users with tools to analyze their writing and thinking patterns, identify AI-induced stylistic convergence, and develop personalized strategies to enhance their unique voice and creativity. Its value proposition lies in empowering individuals to maintain and cultivate their distinct intellectual and expressive identity in an AI-influenced world.
TECH STACK:
- Frontend: Next.js (App Router), React, Tailwind CSS, shadcn/ui (for pre-built components), Zustand (for state management)
- Backend: Next.js API Routes (or a separate Node.js/Express.js backend if complexity demands)
- Database: PostgreSQL with Drizzle ORM for type-safe database interactions.
- Authentication: NextAuth.js (or Clerk for a simpler integrated solution) for secure user authentication (OAuth with Google/GitHub and email/password).
- Deployment: Vercel
- Other Libraries: React Hook Form (for form handling), Zod (for schema validation), Axios (for API requests if needed outside Next.js fetch).
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. `users` table:
- `id` (uuid, primary key)
- `name` (text)
- `email` (text, unique)
- `emailVerified` (timestamp)
- `image` (text, optional)
- `createdAt` (timestamp)
- `updatedAt` (timestamp)
2. `documents` table:
- `id` (uuid, primary key)
- `userId` (uuid, foreign key to users.id, indexed)
- `title` (text)
- `content` (text)
- `createdAt` (timestamp)
- `updatedAt` (timestamp)
3. `analysisResults` table:
- `id` (uuid, primary key)
- `userId` (uuid, foreign key to users.id, indexed)
- `documentId` (uuid, foreign key to documents.id, indexed)
- `homogenizationScore` (float)
- `analysisDetails` (jsonb, stores detailed metrics like vocabulary diversity, sentence structure variation, sentiment analysis, etc.)
- `analyzedAt` (timestamp)
4. `writingExercises` table:
- `id` (uuid, primary key)
- `title` (text)
- `description` (text)
- `type` (enum: 'style_variation', 'vocabulary_expansion', 'sentence_structure')
- `difficulty` (enum: 'easy', 'medium', 'hard')
5. `userExercises` table:
- `id` (uuid, primary key)
- `userId` (uuid, foreign key to users.id, indexed)
- `exerciseId` (uuid, foreign key to writingExercises.id)
- `userResponse` (text, optional)
- `completedAt` (timestamp, optional)
- `score` (float, optional)
CORE FEATURES & USER FLOW:
1. User Authentication:
- Flow: User lands on the homepage. Clicks 'Sign Up' or 'Login'. Presented with OAuth options (Google, GitHub) and email/password. Upon successful login, redirected to their dashboard. Unauthenticated users can access public content but not personal features.
- Edge Case: Password reset flow, email verification, handling failed login attempts.
2. Document Upload & Creation:
- Flow: From the dashboard, user clicks 'New Document' or 'Upload File'. Can choose to paste text directly into an editor or upload .txt, .docx files. Document is saved associated with the user.
- Edge Cases: Handling large file uploads, unsupported file types, saving drafts.
3. Writing & Thinking Profile Analysis:
- Flow: User selects a saved document or enters text in a dedicated analysis input. Clicks 'Analyze'. The system processes the text (using NLP techniques on the backend, potentially involving external AI APIs for initial similarity checks but focusing on in-house metrics for homogenization). Results including a 'homogenizationScore' and detailed metrics are displayed on a dedicated 'Analysis Results' page.
- Backend Logic: The analysis will involve metrics such as:
- Lexical Diversity (Type-Token Ratio, MTLD)
- Sentence Complexity (average sentence length, parse tree depth)
- Syntactic Variety (use of different sentence structures)
- Vocabulary Richness & Uniqueness (comparison against common LLM outputs and a baseline corpus)
- Sentiment & Tone Consistency
- Edge Cases: Analysis of very short texts, handling text with special characters/formatting, API rate limits if external APIs are used.
4. Homogenization Score Visualization:
- Flow: On the 'Analysis Results' page, the `homogenizationScore` is displayed prominently, perhaps with a gauge or a simple numerical value and descriptive text (e.g., 'Low Risk', 'Moderate Risk', 'High Risk'). Detailed metrics are shown in expandable sections or charts.
- Edge Cases: Displaying scores for documents with insufficient data for a reliable metric.
5. Personalized Writing Exercises:
- Flow: Users can browse available writing exercises. Clicking an exercise presents the task (e.g., 'Rewrite this paragraph using more varied sentence structures'). User submits their response. The system provides feedback or a score based on the exercise's goals.
- Backend Logic: Exercises might be pre-defined templates or dynamically generated. Scoring could be rule-based or involve simpler AI checks.
- Edge Cases: Users not completing exercises, invalid responses.
API & DATA FETCHING:
- API Routes (Next.js App Router - `app/api/...` or `app/(protected)/dashboard/api/...`):
- `POST /api/auth/signup`, `POST /api/auth/login`, `POST /api/auth/logout` (handled by NextAuth.js or Clerk)
- `POST /api/documents`: Upload/create a new document. Request body: `{ title: string, content: string }`. Response: `{ id: string, ...documentData }`
- `GET /api/documents`: Get all user documents. Response: `Array<{ id: string, title: string, updatedAt: string }>`. Used for document list.
- `GET /api/documents/[id]`: Get a single document. Response: `{ id: string, title: string, content: string, ... }`.
- `PUT /api/documents/[id]`: Update a document. Request body: `{ title?: string, content?: string }`. Response: `{ success: boolean }`.
- `DELETE /api/documents/[id]`: Delete a document. Response: `{ success: boolean }`.
- `POST /api/analyze`: Analyze document content. Request body: `{ documentId?: string, content: string }`. Response: `{ id: string, homogenizationScore: number, analysisDetails: object, analyzedAt: string }`. Triggers backend analysis.
- `GET /api/analysis/:id`: Get analysis results for a specific document.
- `GET /api/exercises`: Get available writing exercises. Response: `Array<Exercise>`.
- `POST /api/exercises/submit`: Submit a user's response to an exercise. Request body: `{ exerciseId: string, response: string }`. Response: `{ score: number, feedback?: string }`.
- Data Fetching: Utilize `fetch` within Server Components for direct data access where possible. Use client-side fetching (e.g., using Zustand state and effects, or libraries like SWR/React Query) in Client Components for interactive features like the document editor or analysis results display.
- Data Flow: Server Components fetch initial data. Client Components fetch data dynamically or receive it as props. State management (Zustand) handles shared UI state and data fetched client-side.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.tsx`: Root layout (HTML, Body, Tailwind setup, providers).
- `app/page.tsx`: Landing Page (marketing content, call to action, feature highlights).
- `app/(auth)/login/page.tsx`: Login Page.
- `app/(auth)/signup/page.tsx`: Sign Up Page.
- `app/(protected)/layout.tsx`: Protected route layout (includes Navbar, Sidebar).
- `app/(protected)/dashboard/page.tsx`: User Dashboard (overview, recent documents, quick actions).
- Components: `DashboardStats`, `RecentDocumentsList`, `QuickActionButtons`.
- `app/(protected)/documents/page.tsx`: Document Management Page (List of all user documents).
- Components: `DocumentTable` (using shadcn/ui DataTable), `DocumentListItem`.
- `app/(protected)/documents/new/page.tsx`: New Document Page (rich text editor).
- Components: `RichTextEditor` (using a library like TipTap or Quill integrated with React Hook Form), `DocumentForm`.
- `app/(protected)/documents/[id]/page.tsx`: Document Editor/Viewer Page.
- Components: `DocumentEditor`, `DocumentActionsMenu`.
- `app/(protected)/analyze/[id]/page.tsx`: Analysis Results Page for a specific document.
- Components: `AnalysisScoreCard`, `DetailedMetricsChart`, `HomogenizationRiskIndicator`.
- `app/(protected)/exercises/page.tsx`: Writing Exercises Hub.
- Components: `ExerciseList`, `ExerciseCard`.
- `app/(protected)/exercises/[id]/page.tsx`: Specific Writing Exercise Page.
- Components: `ExercisePrompt`, `UserResponseEditor`, `SubmitExerciseButton`.
- `app/(protected)/settings/page.tsx`: User Settings Page.
- `app/api/...`: API Routes defined within `app` directory.
State Management: Zustand will manage global state like user authentication status, and possibly fetched lists of documents/exercises. Local component state will handle form inputs, UI element states (e.g., modal open/closed), and temporary data.
UI/UX DESIGN & VISUAL IDENTITY:
- Design Style: Minimalist Clean with subtle modern gradients.
- Color Palette:
- Primary: Deep Indigo (`#303F9F`)
- Secondary: Teal (`#009688`)
- Accent/Gradient: Soft Purple (`#7E57C2`), Sky Blue (`#4FC3F7`)
- Neutrals: Dark Gray (`#212529`), Light Gray (`#F8F9FA`), White (`#FFFFFF`)
- Typography:
- Headings: Inter (SemiBold, Bold)
- Body Text: Inter (Regular)
- Layout: Clean, spacious layouts with clear visual hierarchy. Use of cards for distinct sections. Sidebar for navigation in protected routes. Focus on readability and ease of use.
- Responsive Rules: Mobile-first approach. Use Tailwind CSS's responsive modifiers (`sm:`, `md:`, `lg:`) extensively. Ensure optimal viewing on all screen sizes. Sidebar collapses into a hamburger menu on smaller screens.
ANIMATIONS:
- Page Transitions: Subtle fade-in/fade-out using Next.js's `useRouter` and a transition library (e.g., Framer Motion).
- Element Transitions: Smooth transitions for hover effects on buttons and cards (Tailwind CSS `transition` and `hover:` utilities).
- Loading States: Skeleton loaders for data fetching, subtle spinner animations for API calls.
- Micro-interactions: Subtle animations on form validation feedback, button clicks.
EDGE CASES:
- Authentication: Handle expired tokens, unauthorized access redirects, guest access limitations.
- Validation: Implement robust client-side (Zod with React Hook Form) and server-side validation for all user inputs (forms, API requests).
- Empty States: Design informative and visually appealing empty states for document lists, analysis results, and exercise sections (e.g., 'You haven't created any documents yet. Start by uploading one!').
- Error Handling: Graceful error handling for API failures, display user-friendly error messages, implement retry mechanisms where appropriate.
- Rate Limiting: If using external AI APIs for analysis, implement rate limiting and backoff strategies.
- Text Analysis: Handle non-standard text inputs, potential encoding issues, and ensure analysis is meaningful even for shorter texts (perhaps with adjusted thresholds).
SAMPLE/MOCK DATA:
1. User Profile:
`{ id: 'uuid-user-1', name: 'Alice Wonderland', email: 'alice@example.com', image: 'url/to/image.jpg' }`
2. Document List Item:
`{ id: 'uuid-doc-1', title: 'My First Novel Draft', updatedAt: '2023-10-27T10:00:00Z' }`
`{ id: 'uuid-doc-2', title: 'Research Paper Outline', updatedAt: '2023-10-26T15:30:00Z' }`
3. Analysis Result (for a moderately original text):
`{ id: 'uuid-analysis-1', userId: 'uuid-user-1', documentId: 'uuid-doc-1', homogenizationScore: 0.35, analyzedAt: '2023-10-27T11:00:00Z', analysisDetails: { lexicalDiversity: 0.75, sentenceComplexity: 3.2, vocabularyUniqueness: 0.6 } }`
4. Analysis Result (for a highly AI-influenced text):
`{ id: 'uuid-analysis-2', userId: 'uuid-user-1', documentId: 'uuid-doc-2', homogenizationScore: 0.88, analyzedAt: '2023-10-27T11:05:00Z', analysisDetails: { lexicalDiversity: 0.45, sentenceComplexity: 2.5, vocabularyUniqueness: 0.3 } }`
5. Writing Exercise:
`{ id: 'uuid-ex-1', title: 'Vary Sentence Beginnings', description: 'Rewrite the following sentences, ensuring each starts with a different structure.', type: 'style_variation', difficulty: 'easy' }`
6. User Exercise Submission (incomplete):
`{ id: 'uuid-user-ex-1', userId: 'uuid-user-1', exerciseId: 'uuid-ex-1', userResponse: '' }`
7. User Exercise Submission (completed):
`{ id: 'uuid-user-ex-2', userId: 'uuid-user-1', exerciseId: 'uuid-ex-1', userResponse: 'Challenging the norm, Alice began her journey. Suddenly, the rabbit appeared. Because it was late, she had to hurry.', completedAt: '2023-10-27T12:00:00Z', score: 0.8 }`
8. Empty Document List State:
`'No documents found. Click 'New Document' to start creating!'`
TURKISH TRANSLATIONS (for UI elements):
- Sign Up: Kaydol
- Login: Giriş Yap
- Dashboard: Kontrol Paneli
- My Documents: Belgelerim
- New Document: Yeni Belge
- Upload File: Dosya Yükle
- Analyze: Analiz Et
- Analysis Results: Analiz Sonuçları
- Homogenization Score: Tekdüzelik Puanı
- Low Risk: Düşük Risk
- Moderate Risk: Orta Risk
- High Risk: Yüksek Risk
- Writing Exercises: Yazım Egzersizleri
- Start Exercise: Egzersize Başla
- Submit: Gönder
- Settings: Ayarlar
- Save: Kaydet
- Cancel: İptal
- Error: Hata
- Loading: Yükleniyor...
- No data available: Veri bulunamadı.
- Document Title: Belge Başlığı
- Last Updated: Son Güncelleme
- Create Document: Belge Oluştur
- Analyze This Text: Bu Metni Analiz Et
- View Details: Detayları Gör
- Type/Variety: Tür/Çeşitlilik
- Sentence Structure: Cümle Yapısı
- Vocabulary: Kelime Hazinesi