You are tasked with building a fully functional, multi-page Next.js MVP application for 'Peptide Compass'. This application aims to be an integrated platform for individuals new to peptide research, simplifying information gathering, resource discovery, and community interaction. The goal is to help users understand peptide fundamentals, access current research, and connect with experts.
**1. PROJECT OVERVIEW:**
* **App Name:** Peptide Compass
* **Problem Solved:** The complexity and vastness of peptide science make it difficult for beginners to find reliable starting points, understand fundamental concepts, and connect with the research community. Existing resources are often fragmented and overwhelming.
* **Value Proposition:** Peptide Compass provides a centralized, user-friendly platform for discovering, learning about, and discussing peptides. It acts as a 'compass' guiding newcomers through the scientific landscape, offering curated resources, a searchable database, and a supportive community.
**2. TECH STACK:**
* **Framework:** Next.js (App Router)
* **UI Library:** shadcn/ui (built on Radix UI and Tailwind CSS)
* **Styling:** Tailwind CSS
* **ORM:** Drizzle ORM (PostgreSQL compatible, e.g., using Neon or Supabase)
* **Authentication:** NextAuth.js (e.g., with GitHub and Email providers)
* **Database:** PostgreSQL
* **State Management:** React Context API or Zustand for global state, component-level state for local UI logic.
* **Form Handling:** React Hook Form with Zod for validation.
* **HTTP Client:** `fetch` API (built into Next.js)
* **Deployment:** Vercel (recommended)
**3. DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
```typescript
// schema.ts
import { pgTable, text, timestamp, integer, pgEnum, uuid, varchar, boolean, jsonb } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// --- Enums ---
export const userRole = pgEnum('user_role', ['admin', 'user']);
// --- Core Tables ---
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
name: text('name'),
email: text('email').notNull().unique(),
emailVerified: timestamp('email_verified', { mode: 'date' }),
image: text('image'),
role: userRole('role').default('user'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const peptides = pgTable('peptides', {
id: uuid('id').primaryKey().defaultRandom(),
name: varchar('name', { length: 256 }).notNull().unique(), // e.g., "Angiotensin II"
sequence: text('sequence').notNull(), // e.g., "Asp-Arg-Val-Tyr-Ile-His-Pro-Phe"
molecularFormula: varchar('molecular_formula', { length: 256 }),
molecularWeight: integer('molecular_weight'), // in Da
function: text('function'), // Brief description of function
researchArea: varchar('research_area', { length: 256 }), // e.g., "Cardiovascular", "Neurology"
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const resources = pgTable('resources', {
id: uuid('id').primaryKey().defaultRandom(),
title: varchar('title', { length: 256 }).notNull(),
url: text('url').notNull(),
description: text('description'),
type: varchar('type', { length: 100 }), // e.g., "Research Paper", "Database", "Article", "Video"
tags: jsonb('tags'), // Array of strings, e.g., ["cardiac", "hypertension"]
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const forumPosts = pgTable('forum_posts', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
title: varchar('title', { length: 256 }).notNull(),
content: text('content').notNull(),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const forumComments = pgTable('forum_comments', {
id: uuid('id').primaryKey().defaultRandom(),
postId: uuid('post_id').notNull().references(() => forumPosts.id, { onDelete: 'cascade' }),
userId: uuid('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
content: text('content').notNull(),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
// --- Relations ---
export const usersRelations = relations(users, ({ many }) => ({
posts: many(forumPosts),
comments: many(forumComments),
}));
export const peptidesRelations = relations(peptides, ({ many }) => ({
// Could add relations to related resources or discussions in the future
}));
export const resourcesRelations = relations(resources, ({}) => ({
// No direct relations needed for MVP, could link to peptides or discussions later
}));
export const forumPostsRelations = relations(forumPosts, ({ one, many }) => ({
user: one(users, {
fields: [forumPosts.userId],
references: [users.id],
}),
comments: many(forumComments),
}));
export const forumCommentsRelations = relations(forumComments, ({ one }) => ({
post: one(forumPosts, {
fields: [forumComments.postId],
references: [forumPosts.id],
}),
user: one(users, {
fields: [forumComments.userId],
references: [users.id],
}),
}));
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Peptide = typeof peptides.$inferSelect;
export type NewPeptide = typeof peptides.$inferInsert;
export type Resource = typeof resources.$inferSelect;
export type NewResource = typeof resources.$inferInsert;
export type ForumPost = typeof forumPosts.$inferSelect;
export type NewForumPost = typeof forumPosts.$inferInsert;
export type ForumComment = typeof forumComments.$inferSelect;
export type NewForumComment = typeof forumComments.$inferInsert;
```
**4. CORE FEATURES & USER FLOW:**
* **A. User Authentication:**
* **Flow:** User lands on the homepage. Clicks 'Sign In/Sign Up'. Presented with options (GitHub, Email/Password). Upon successful login, redirected to the dashboard. If email/password, requires verification.
* **Pages:** `/auth/signin`, `/auth/signup` (if email/password is complex, could integrate signup into signin)
* **Components:** Sign-in form, OAuth buttons.
* **Edge Cases:** Invalid credentials, email already exists, password complexity, email verification required.
* **B. Peptide Database Browsing & Searching:**
* **Flow:** Authenticated user navigates to the 'Peptides' section. Sees a paginated list of peptides. Can use a search bar (by name, sequence, function) and filters (e.g., research area). Clicking a peptide opens a detailed view.
* **Pages:** `/peptides` (list/search), `/peptides/[id]` (detail)
* **API Endpoints:**
* `GET /api/peptides?search=<query>&area=<filter>&page=<num>&limit=<num>`: Fetches paginated peptide data with search/filter options.
* `GET /api/peptides/[id]`: Fetches details for a specific peptide.
* **Components:** `PeptideList`, `PeptideListItem`, `SearchBar`, `FilterDropdowns`, `PeptideDetailCard`.
* **State:** Search query, active filters, current page, peptide data, loading state, error state.
* **Edge Cases:** No search results, invalid peptide ID, API errors.
* **C. Resource Discovery:**
* **Flow:** User navigates to the 'Resources' section. Sees a curated list of resources (articles, databases, papers). Can search and filter by type or tags. Clicking a resource navigates to the external URL or shows a brief description.
* **Pages:** `/resources`
* **API Endpoints:**
* `GET /api/resources?search=<query>&type=<filter>`: Fetches paginated resources.
* **Components:** `ResourceList`, `ResourceListItem`, `SearchBar`, `ResourceTypeFilter`.
* **State:** Search query, selected resource type, resource data, loading/error states.
* **Edge Cases:** No resources match criteria, broken external links (handle gracefully).
* **D. Community Forum:**
* **Flow:** User navigates to the 'Forum' section. Sees a list of recent posts. Can create a new post (requiring authentication). Clicking a post shows the content and comments. Users can add comments to existing posts.
* **Pages:** `/forum`, `/forum/posts/[id]` (view post & comments), `/forum/new` (create post)
* **API Endpoints:**
* `GET /api/forum/posts?page=<num>&limit=<num>`: Get posts.
* `GET /api/forum/posts/[postId]`: Get a single post with its comments.
* `POST /api/forum/posts`: Create a new post (requires auth).
* `POST /api/forum/posts/[postId]/comments`: Add a comment (requires auth).
* **Components:** `ForumPostList`, `ForumPostListItem`, `NewPostForm`, `CommentList`, `CommentItem`, `NewCommentForm`.
* **State:** Post data, comment data, form inputs (title, content), loading/error states.
* **Edge Cases:** Post/comment creation failure, unauthorized access, empty post/comment content, deleted posts.
* **E. User Dashboard (Authenticated Area):**
* **Flow:** Upon login, users see a personalized dashboard. It could include recent forum activity, saved peptides/resources (future feature), and quick links.
* **Pages:** `/dashboard`
* **Components:** `DashboardWidget` (for various sections like 'Recent Activity', 'Quick Links'), `UserProfileSummary`.
* **State:** User data, personalized content flags.
* **Edge Cases:** User not logged in (redirect to sign-in), no recent activity.
**5. API & DATA FETCHING:**
* **Approach:** Utilize Next.js API Routes for backend logic and data fetching. Employ `fetch` within Server Components where possible for direct data access, and Client Components will call API routes or use server actions.
* **Data Structure:** Consistent JSON responses. Use Zod for request/response validation where applicable.
* **Example (Get Peptides):**
* **Request:** `GET /api/peptides?search=Angiotensin&area=Cardiovascular&page=1&limit=10`
* **Response (Success - 200 OK):**
```json
{
"data": [
{
"id": "uuid-string-1",
"name": "Angiotensin II",
"sequence": "Asp-Arg-Val-Tyr-Ile-His-Pro-Phe",
"molecularFormula": "C43H52N12O12",
"molecularWeight": 899,
"function": "Potent vasoconstrictor, regulates blood pressure.",
"researchArea": "Cardiovascular",
"createdAt": "2023-10-27T10:00:00Z",
"updatedAt": "2023-10-27T10:00:00Z"
}
// ... more peptides
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"hasNextPage": true,
"hasPrevPage": false,
"totalCount": 50
}
}
```
* **Response (Error - 500 Internal Server Error):**
```json
{
"error": "Database connection failed."
}
```
* **Authentication:** API routes will check `req.headers.authorization` or rely on NextAuth.js session data within Server Components.
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
* **`app/`**
* **`(marketing)/`** (Public routes)
* `page.tsx`: Landing Page (App title, concept, value prop, CTA to sign up/explore)
* `layout.tsx`: Marketing Layout (Navbar, Footer)
* `layout.tsx`: (Shared layout components like Navbar, Footer)
* **`(app)/`** (Authenticated routes)
* `dashboard/page.tsx`: User Dashboard (Widgets for recent activity, etc.)
* `peptides/page.tsx`: Peptide List/Search Page
* `peptides/[id]/page.tsx`: Peptide Detail Page
* `resources/page.tsx`: Resources List/Search Page
* `forum/page.tsx`: Forum - List Posts Page
* `forum/posts/[id]/page.tsx`: Forum - View Post & Comments Page
* `forum/new/page.tsx`: Forum - Create New Post Page
* `layout.tsx`: App Layout (Authenticated Navbar, Sidebar?)
* **`(auth)/`**
* `signin/page.tsx`: Sign In Page
* `signup/page.tsx` (Optional, could be part of signin)
* `layout.tsx`: Auth Layout (Minimalist)
* `layout.tsx`: Root Layout (html, body, Providers: Theme, AuthSession)
* `loading.tsx`: Global Loading UI
* `error.tsx`: Global Error UI
* **`components/`**
* **`ui/`** (shadcn/ui components, plus custom ones):
* `Button`
* `Input`
* `Card`
* `Form` (From React Hook Form integrations)
* `Table`
* `Pagination`
* `Dialog` (for modals)
* `Skeleton` (for loading states)
* `Alert` (for errors/notifications)
* `Avatar`
* `DropdownMenu`
* `Badge`
* `Separator`
* `Tabs`
* `Tooltip`
* **`layout/`**:
* `Navbar.tsx` (Marketing & App Nav)
* `Footer.tsx`
* `Sidebar.tsx` (If needed for authenticated area)
* `MarketingHero.tsx`
* **`features/`** (Feature-specific components):
* **`auth/`**:
* `SignInForm.tsx`
* `OAuthButton.tsx`
* **`peptides/`**:
* `PeptideList.tsx`
* `PeptideListItem.tsx`
* `PeptideDetailView.tsx`
* `PeptideSearchFilter.tsx`
* **`resources/`**:
* `ResourceList.tsx`
* `ResourceListItem.tsx`
* `ResourceSearchFilter.tsx`
* **`forum/`**:
* `ForumPostList.tsx`
* `ForumPostListItem.tsx`
* `ForumPostDetail.tsx`
* `CommentList.tsx`
* `CommentItem.tsx`
* `NewPostForm.tsx`
* `NewCommentForm.tsx`
* **`dashboard/`**:
* `DashboardWidget.tsx`
* `RecentActivityFeed.tsx`
* **`common/`**:
* `LoadingSpinner.tsx`
* `ErrorMessage.tsx`
* `PaginationControls.tsx`
* **`lib/`**: Utility functions, API clients, constants.
* **`hooks/`**: Custom React hooks.
* **`styles/`**: Global CSS (`globals.css`).
* **`providers/`**: Context providers (e.g., `SessionProvider`).
**7. UI/UX DESIGN & VISUAL IDENTITY:**
* **Design Style:** Minimalist Clean with a touch of scientific professionalism. Focus on readability, clear information hierarchy, and intuitive navigation.
* **Color Palette:**
* Primary: `#0A7AFF` (Vibrant blue for accents, CTAs)
* Secondary: `#343A40` (Dark grey for text, backgrounds)
* Accent/Muted: `#6C757D` (Medium grey for secondary text, borders)
* Background: `#F8F9FA` (Light off-white for main content areas)
* White: `#FFFFFF`
* Success: `#28A745`
* Warning/Error: `#DC3545`
* **Typography:**
* Headings: Inter (e.g., Inter Bold, 700)
* Body Text: Inter (e.g., Inter Regular, 400)
* Use appropriate font sizes for hierarchy (e.g., H1: 2.5rem, H2: 2rem, Body: 1rem).
* **Layout:**
* Use a consistent grid system (e.g., 12-column responsive grid).
* Generous whitespace.
* Clear separation between sections using subtle borders or background color changes.
* Max-width for content containers on large screens.
* **Responsiveness:** Mobile-first approach. Ensure usability across devices (phones, tablets, desktops). Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
**8. SAMPLE/MOCK DATA:**
* **Peptides:**
1. `{ "id": "pep-001", "name": "Insulin", "sequence": "Mal-Leu-Tyr-Gln-Trp-Met-Asn-Thr-...", "molecularFormula": "C257H384N65O77S6", "molecularWeight": 5808, "function": "Regulates glucose metabolism", "researchArea": "Endocrinology" }`
2. `{ "id": "pep-002", "name": "Oxytocin", "sequence": "Cys-Tyr-Ile-Gln-Asn-Cys-Pro-Leu-Gly-NH2", "molecularFormula": "C43H66N12O12S2", "molecularWeight": 1007, "function": "Social bonding, uterine contractions", "researchArea": "Neuroscience" }`
3. `{ "id": "pep-003", "name": "Angiotensin II", "sequence": "Asp-Arg-Val-Tyr-Ile-His-Pro-Phe", "molecularFormula": "C43H52N12O12", "molecularWeight": 899, "function": "Regulates blood pressure", "researchArea": "Cardiovascular" }`
4. `{ "id": "pep-004", "name": "Glucagon", "sequence": "His-Ser-Gln-Gly-Thr-Phe-Thr-Ser-Asp-Tyr-Ser-Lys-Tyr-Leu-Asp-Ser-Arg-Arg-Ala-Gln-Asp-Phe-Val-Gln-Trp-Leu-Met-Asn-Thr", "molecularFormula": "C153H221N43O45S", "molecularWeight": 3483, "function": "Raises blood glucose levels", "researchArea": "Endocrinology" }`
* **Resources:**
1. `{ "id": "res-001", "title": "PubMed", "url": "https://pubmed.ncbi.nlm.nih.gov/", "description": "Biomedical literature database.", "type": "Database", "tags": ["literature", "biomedical", "search"] }`
2. `{ "id": "res-002", "title": "Peptides - Wikipedia", "url": "https://en.wikipedia.org/wiki/Peptide", "description": "General overview and introduction to peptides.", "type": "Article", "tags": ["introduction", "basics", "overview"] }`
3. `{ "id": "res-003", "title": "DBPepper: database of bioactive peptides", "url": "https://structure.bioc.cam.ac.uk/dbpepper/", "description": "A curated database of bioactive peptides.", "type": "Database", "tags": ["bioactive", "database", "curated"] }`
* **Forum Posts:**
1. `{ "id": "post-001", "userId": "user-abc", "title": "Starting with peptide synthesis - Any recommendations?", "content": "Hi everyone, I'm new to peptide research and need to start synthesizing peptides for my project...", "createdAt": "2023-10-26T08:30:00Z", "updatedAt": "2023-10-26T08:30:00Z" }`
2. `{ "id": "post-002", "userId": "user-xyz", "title": "Difference between peptide hormones and neurotransmitters?", "content": "I'm struggling to grasp the key differences in function and signaling pathways...", "createdAt": "2023-10-25T15:00:00Z", "updatedAt": "2023-10-25T15:00:00Z" }`
* **Forum Comments:**
1. `{ "id": "cmt-001", "postId": "post-001", "userId": "user-def", "content": "Check out the Merrifield synthesis method, it's a classic!", "createdAt": "2023-10-26T09:00:00Z", "updatedAt": "2023-10-26T09:00:00Z" }`
2. `{ "id": "cmt-002", "postId": "post-001", "userId": "user-abc", "content": "Thanks! Any specific protocols you'd recommend for Fmoc chemistry?", "createdAt": "2023-10-26T09:15:00Z", "updatedAt": "2023-10-26T09:15:00Z" }`
**9. TURKISH TRANSLATIONS:**
* **App Title:** Peptit Pusulası
* **Navbar:** Keşfet (Explore), Peptitler (Peptides), Kaynaklar (Resources), Forum, Giriş Yap (Sign In)
* **Buttons:** Ara (Search), Gönder (Submit), Yeni Yazı Oluştur (Create New Post), Yorum Yap (Comment), Giriş Yap (Sign In), Kaydol (Sign Up)
* **Placeholders:** Peptit adı, dizisi veya fonksiyonu ile arayın... (Search by peptide name, sequence, or function...)
* **Headings:** Peptit Veri Tabanı, Popüler Kaynaklar, Topluluk Forumu, En Son Tartışmalar
* **Labels:** Başlık (Title), İçerik (Content), Adınız (Name), E-posta (Email), Parola (Password)
* **Messages:** Oturum açıldı. (Logged in.), Yorumunuz gönderildi. (Your comment has been posted.), Bir hata oluştu. (An error occurred.)
**10. ANIMATIONS:**
* **Page Transitions:** Subtle fade-in/out using Next.js's built-in features or libraries like `Framer Motion` if needed.
* **Hover Effects:** Slight scale-up or color change on interactive elements (buttons, links, cards).
* **Loading States:** Use skeleton loaders (`Skeleton` component from shadcn/ui) for data fetching. Spinners for immediate actions (e.g., form submission).
* **Transitions:** Smooth transitions for elements appearing/disappearing (e.g., filter menus). Tailwind's `transition` utility class.
**11. EDGE CASES:**
* **Empty States:** Display informative messages and potential CTAs when lists are empty (e.g., 'No peptides found matching your criteria. Try adjusting your search.', 'Start the conversation by creating the first post!').
* **Authentication:** Protect relevant routes and API endpoints. Redirect unauthenticated users to the sign-in page. Display appropriate messages for unauthorized actions.
* **Error Handling:** Global error boundaries (`error.tsx`). Specific error messages within components for API failures or validation errors. Use `Alert` components from shadcn/ui.
* **Validation:** Implement robust validation using Zod and React Hook Form for all user inputs (forms, search queries). Provide clear, inline error messages.
* **Data Integrity:** Ensure uniqueness constraints in the database (e.g., peptide names). Handle potential race conditions in concurrent operations (though less likely in MVP).
* **Rate Limiting:** Consider basic rate limiting on API endpoints to prevent abuse, especially for auth endpoints.