## AI Master Prompt: IdeaTruth - Next.js MVP Application
**1. PROJECT OVERVIEW:**
IdeaTruth is a SaaS platform designed to combat misinformation and elevate intellectual discourse by analyzing arguments based on evidence, logical consistency, and the absence of deceptive tactics. The core problem it solves is the proliferation of ideas and narratives that gain acceptance not through merit, but through manipulation, emotional appeals, or logical fallacies, particularly prevalent in complex fields like economics and politics. The platform empowers users to submit articles, essays, or arguments (via URL or direct text input) and receive an AI-generated analysis highlighting the strength of evidence, logical structure, and potential fallacies. Users can then rate, comment on, and share these analyses, fostering a community dedicated to critical thinking. The value proposition is to provide a tool for objective evaluation of ideas, promoting intellectual honesty and informed public discourse.
**2. TECH STACK:**
- **Frontend Framework:** React (Next.js App Router)
- **Styling:** Tailwind CSS (with shadcn/ui for pre-built components)
- **State Management:** React Context API / Zustand (for global state)
- **ORM:** Drizzle ORM (PostgreSQL/SQLite compatible)
- **Database:** PostgreSQL (recommended for production) or SQLite (for local dev/simpler deployments)
- **Authentication:** NextAuth.js (for email/password, Google, GitHub OAuth)
- **API Layer:** Next.js API Routes (or Server Actions for simpler CRUD)
- **AI/NLP:** Integration with a suitable NLP library/API for text analysis (e.g., spaCy, NLTK via a backend service, or a cloud-based NLP API like Google Cloud Natural Language or OpenAI for advanced features. For MVP, a simpler rule-based or basic ML model might suffice for fallacy detection).
- **Other Packages:** `react-hook-form` (for forms), `zod` (for schema validation), `date-fns` (for date manipulation), `axios` (for API calls if needed).
**3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL syntax):**
```sql
-- Users Table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
email_verified TIMESTAMP WITH TIME ZONE,
image TEXT, -- URL to profile picture
hashed_password TEXT, -- For email/password auth
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Accounts Table (for OAuth)
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
provider_account_id VARCHAR(255) NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
token_type VARCHAR(255),
scope VARCHAR(255),
id_token TEXT,
UNIQUE(provider, provider_account_id)
);
-- Sessions Table (for NextAuth.js)
CREATE TABLE sessions (
id SERIAL PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
session_token VARCHAR(255) UNIQUE NOT NULL,
expires TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Verification Tokens Table (for NextAuth.js email verification)
CREATE TABLE verification_tokens (
identifier TEXT NOT NULL,
token TEXT NOT NULL,
expires TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY (identifier, token)
);
-- Submissions Table (User-submitted content)
CREATE TABLE submissions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL, -- Allow anonymous submissions or keep context if user deletes account
url TEXT UNIQUE, -- Optional: URL if submitted via link
title VARCHAR(255) NOT NULL,
content TEXT, -- Direct text input
source_type VARCHAR(50) NOT NULL, -- 'url' or 'text'
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Analyses Table (AI-generated analysis of submissions)
CREATE TABLE analyses (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
submission_id UUID NOT NULL REFERENCES submissions(id) ON DELETE CASCADE,
analyzer_id UUID REFERENCES users(id) ON DELETE SET NULL, -- User who initiated/refined the analysis, if applicable
summary TEXT,
evidence_strength INT, -- e.g., 1-5 scale
logical_consistency INT, -- e.g., 1-5 scale
fallacy_score INT, -- e.g., 0-100, higher means more fallacies detected
detected_fallacies JSONB, -- e.g., {"type": "Ad Hominem", "severity": "medium", "snippet": "..."}
ai_model_version VARCHAR(50),
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Comments Table (User comments on analyses)
CREATE TABLE comments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
analysis_id UUID NOT NULL REFERENCES analyses(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
parent_id UUID REFERENCES comments(id) ON DELETE CASCADE, -- For threaded comments
body TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
-- Ratings Table (User ratings for analyses)
CREATE TABLE ratings (
id SERIAL PRIMARY KEY,
analysis_id UUID NOT NULL REFERENCES analyses(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
rating INT NOT NULL CHECK (rating >= 1 AND rating <= 5), -- e.g., 1-5 stars
UNIQUE(analysis_id, user_id)
);
-- Follows Table (User following other users)
CREATE TABLE follows (
follower_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
following_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
PRIMARY KEY (follower_id, following_id)
);
-- Indexes for performance
CREATE INDEX idx_submissions_user_id ON submissions(user_id);
CREATE INDEX idx_analyses_submission_id ON analyses(submission_id);
CREATE INDEX idx_comments_analysis_id ON comments(analysis_id);
CREATE INDEX idx_comments_user_id ON comments(user_id);
CREATE INDEX idx_ratings_analysis_id ON ratings(analysis_id);
CREATE INDEX idx_ratings_user_id ON ratings(user_id);
CREATE INDEX idx_follows_follower_id ON follows(follower_id);
CREATE INDEX idx_follows_following_id ON follows(following_id);
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* **Flow:** User clicks 'Sign Up' or 'Login'. Can use Email/Password or OAuth (Google/GitHub). Email/Password flow: Enter email/password, submit. If new, create user; if existing, log in. If email/password, send verification email. OAuth flow: Click provider button, redirected to provider, authorize, redirected back, logged in/account created. Session management via NextAuth.js.
* **Edge Cases:** Invalid credentials, email already exists, OAuth errors, email not verified.
* **Submission Creation:**
* **Flow:** Authenticated user navigates to 'Submit' page. Chooses 'URL' or 'Text Input'. If URL, paste URL, optionally add title/description. If Text, enter title and paste/write content directly. Submit. The system stores the submission and triggers the analysis process (either synchronously for short texts or asynchronously via a background job for URLs/long texts).
* **Edge Cases:** Invalid URL, URL fetch failure (timeout, 404), empty text, exceeding content length limits, duplicate URL submission.
* **AI Analysis:**
* **Flow:** Triggered after submission. Backend service fetches URL content or processes direct text. NLP model analyzes text for: Main arguments, supporting evidence (identification and assessment), logical fallacies (detection and categorization), language tone, and potential bias. Results are structured (e.g., JSON) and stored in the `analyses` table, linked to the `submission`. For URL submissions, a loading indicator is shown to the user.
* **Edge Cases:** NLP model errors, unsupported content types on URL, inability to parse content, inadequate analysis depth (requiring model tuning).
* **Analysis Viewing & Interaction:**
* **Flow:** User views a specific analysis via a unique URL (e.g., `/analysis/{id}`). The page displays the submission title, original content/URL, the AI analysis (summary, evidence score, fallacy score, detailed fallacy list), and user comments/ratings. Users can: Rate the analysis (1-5 stars), leave a comment (threaded), view comments, and see other users' ratings. A 'Follow User' button is available on analysis author/commenter profiles.
* **Edge Cases:** Analysis not found (404), no comments yet, displaying complex fallacy data clearly.
* **User Dashboard/Profile:**
* **Flow:** Authenticated user navigates to '/dashboard'. Shows a list of their submitted analyses, received comments, and followed users' activity. Profile page shows user info, list of their analyses, and follower/following counts.
* **Edge Cases:** No submissions, no activity, privacy settings (future feature).
* **Feed/Discovery:**
* **Flow:** Publicly accessible page (e.g., '/') displaying a feed of recent or highly-rated analyses. Filters available: Sort by 'Most Recent', 'Highest Rated', 'Most Discussed'. Each item links to the full analysis view.
* **Edge Cases:** Empty feed, pagination implementation.
**5. API & DATA FETCHING (Next.js App Router):**
* **Data Fetching:** Primarily use Server Components for direct DB queries (via Drizzle ORM) to fetch data for static parts of pages (e.g., analysis details, user profiles). Use Client Components with Server Actions or API Routes for dynamic data, mutations (creating submissions, comments, ratings, follows), and authenticated actions.
* **API Routes / Server Actions Examples:**
* `POST /api/submissions` or `POST /actions/submit`:
* **Request Body:** `{ url: string, title: string }` or `{ text: string, title: string }`
* **Response Body:** `{ success: true, submissionId: string }` or `{ success: false, error: string }`
* **Action:** Creates a new submission, potentially triggers async analysis.
* `POST /api/analyses/{id}/rate` or `POST /actions/rateAnalysis`:
* **Request Body:** `{ analysisId: string, rating: number }`
* **Response Body:** `{ success: true, averageRating: number }` or `{ success: false, error: string }`
* **Action:** Adds/updates a user's rating for an analysis.
* `POST /api/analyses/{id}/comments` or `POST /actions/addComment`:
* **Request Body:** `{ analysisId: string, body: string, parentId?: string }`
* **Response Body:** `{ success: true, comment: CommentObject }` or `{ success: false, error: string }`
* **Action:** Creates a new comment.
* `POST /actions/followUser`:
* **Request Body:** `{ userIdToFollow: string }`
* **Response Body:** `{ success: true, isFollowing: boolean }`
* **Action:** Creates or deletes a follow relationship.
* **Data Flow:** Server Components fetch data directly. Client Components fetch data via Server Actions (mutations) or dedicated API routes (queries, often called from `useEffect` or event handlers). UI updates optimistically where appropriate, followed by data refetching on success.
**6. UI/UX DESIGN & VISUAL IDENTITY:**
* **Design Style:** Minimalist Clean with subtle Modern Gradient accents.
* **Color Palette:**
* Primary (Dark Background): `#1A1A1A` (Near Black)
* Secondary (Text/Elements): `#E0E0E0` (Light Gray)
* Accent 1 (Gradient/Highlights): `#4A90E2` (Vibrant Blue)
* Accent 2 (Subtle Gradient): `#50E3C2` (Teal/Mint)
* Warning/Error: `#D0021B` (Red)
* Success: `#7ED321` (Green)
* **Typography:**
* Headings: `'Inter', sans-serif` (Bold)
* Body Text: `'Inter', sans-serif` (Regular)
* **Layout:** Clean, spacious layout using a 12-column grid system. Emphasis on readability. Sidebar for navigation in authenticated views. Clear separation between submission, analysis, and comments sections.
* **UI Components:** Utilize `shadcn/ui` components (Card, Button, Input, Select, Dialog, Tooltip, Avatar, etc.) for a consistent look and feel.
* **Responsive Rules:** Mobile-first approach. Layouts adapt fluidly. Navigation collapses into a burger menu on smaller screens. Content sections reflow for optimal readability on all devices.
* **Visual Elements:** Subtle use of gradients in buttons or headers. Clean icons. Minimal animations to avoid distraction.
**7. COMPONENT BREAKDOWN (Next.js App Router Structure):**
* **`app/`**
* **`layout.tsx`:** Root layout (html, body, global providers, Tailwind CSS setup, font loading).
* **`page.tsx`:** Public landing page / Feed of recent analyses.
* **`dashboard/`**
* **`layout.tsx`:** Dashboard specific layout (e.g., sidebar + content).
* **`page.tsx`:** User's dashboard (My Submissions, Activity feed).
* **`submit/`**
* **`page.tsx`:** Form for submitting new URLs or text content.
* **`analysis/[id]/`**
* **`page.tsx`:** Displays a specific analysis, including AI breakdown, user ratings, and comments section.
* **`profile/[userId]/`**
* **`page.tsx`:** Public profile page for a user.
* **`auth/`**
* **`signin/page.tsx`:** Sign in form.
* **`signup/page.tsx`:** Sign up form.
* **`reset-password/page.tsx`:** Password reset form.
* **`api/`**
* **`auth/[...nextauth]/route.ts`:** NextAuth.js route handler.
* **`[resource]/route.ts`:** Example API routes for CRUD operations if not using Server Actions exclusively.
* **`components/`**
* **`ui/`:** Re-exports from `shadcn/ui` or custom base components (Button, Input, Card, etc.).
* **`layout/`:** Navbar, Footer, Sidebar, PageWrapper.
* **`auth/`:** SignInForm, SignUpForm, OAuthButtons.
* **`submission/`:** SubmissionForm (URL/Text tabs), SubmissionCard.
* **`analysis/`:** AnalysisView (displays AI results), FallacyBadge, RatingStars, CommentSection, CommentItem, AddCommentForm.
* **`common/`:** LoadingSpinner, ErrorMessage, AvatarDisplay, UserLink, Pagination.
* **`lib/`:** Database connection (Drizzle), API clients, utility functions, AI/NLP interaction module.
* **`hooks/`:** Custom React hooks (e.g., `useAuth`, `useFetchAnalysis`).
* **`styles/`:** Global CSS (`globals.css`).
**8. SAMPLE/MOCK DATA:**
* **User:**
* `{ id: 'uuid-1', name: 'Alice Johnson', email: 'alice@example.com', image: 'url/to/alice.jpg' }`
* **Submission:**
* `{ id: 'uuid-sub-1', userId: 'uuid-1', url: 'https://example.com/economic-theory', title: 'Critique of Neoclassical Economics', source_type: 'url', created_at: '2023-10-27T10:00:00Z' }`
* `{ id: 'uuid-sub-2', userId: null, content: 'This new policy proposal seems flawed...', title: 'Policy Analysis Draft', source_type: 'text', created_at: '2023-10-27T11:30:00Z' }`
* **Analysis:**
* `{ id: 'uuid-ana-1', submissionId: 'uuid-sub-1', summary: 'The article presents a strong argument against neoclassical assumptions, supported by historical data. However, it relies heavily on anecdotal evidence in section 3.', evidence_strength: 4, logical_consistency: 4, fallacy_score: 15, detected_fallacies: '[{"type": "Anecdotal Evidence", "severity": "low", "snippet": "...like my neighbor's experience shows..."}]', created_at: '2023-10-27T10:05:00Z' }`
* **Comment:**
* `{ id: 'uuid-com-1', analysisId: 'uuid-ana-1', userId: 'uuid-2', body: 'Interesting points, but the author ignores key macroeconomic indicators.', created_at: '2023-10-27T12:00:00Z' }`
* `{ id: 'uuid-com-2', analysisId: 'uuid-ana-1', userId: 'uuid-1', parentId: 'uuid-com-1', body: 'Which indicators specifically? I'd like to see the data.', created_at: '2023-10-27T12:05:00Z' }`
* **Rating:**
* `{ id: 1, analysisId: 'uuid-ana-1', userId: 'uuid-1', rating: 4 }`
* `{ id: 2, analysisId: 'uuid-ana-1', userId: 'uuid-2', rating: 3 }`
**9. TURKISH TRANSLATIONS (Key UI Text Examples):**
* **App Title:** FikirDoğrusu
* **Sign Up:** Kayıt Ol
* **Login:** Giriş Yap
* **Submit Article:** Makale Gönder
* **URL:** URL
* **Text:** Metin
* **Title:** Başlık
* **Content:** İçerik
* **Analysis Results:** Analiz Sonuçları
* **Summary:** Özet
* **Evidence Strength:** Kanıt Gücü
* **Logical Consistency:** Mantıksal Tutarlılık
* **Detected Fallacies:** Tespit Edilen Mantık Hataları
* **Rate Analysis:** Analizi Değerlendir
* **Add Comment:** Yorum Ekle
* **Your Submissions:** Gönderilerin
* **Follow:** Takip Et
* **Submit:** Gönder
* **Loading...:** Yükleniyor...
* **Error:** Hata
* **No data available:** Veri Bulunamadı
**10. ANIMATIONS:**
* **Page Transitions:** Subtle fade-in/out for page loads using Next.js `useRouter` and a transition library like `Framer Motion` (optional for MVP, but recommended for polish).
* **Component Transitions:** Fade-in for new comments or analysis results. Smooth expansion/collapse for threaded comments.
* **Button Hovers:** Slight scale-up or color change on hover.
* **Loading States:** Use spinners or pulsing animations within buttons/cards to indicate background processing (e.g., fetching data, AI analysis). Placeholder UI (shimmer effects) for content loading.
**11. EDGE CASES & VALIDATION:**
* **Authentication:** Handle expired sessions, unauthorized access (redirect to login), display appropriate messages.
* **Form Validation:** Use `zod` and `react-hook-form` for client-side and server-side validation of all user inputs (URLs, text length, rating values, comment content).
* **API Errors:** Gracefully handle network errors, server errors (5xx), and client errors (4xx) with user-friendly messages.
* **Empty States:** Design clear and informative empty states for dashboards, comment sections, and feeds when no data is present.
* **URL Fetching:** Implement robust error handling for timeouts, 404s, content parsing issues. Consider rate limiting and user agent spoofing if necessary.
* **AI Analysis Failures:** Log errors, inform the user that analysis could not be completed, and potentially offer a retry or manual submission option.
* **Database Constraints:** Ensure unique constraints (e.g., user email, submission URL) are handled correctly during creation.