# PROJECT OVERVIEW
**App Name:** Guardian Gate
**Core Problem:** Social media platforms like Meta (Facebook, Instagram) are struggling to adequately protect children from sexual predators and harmful content, leading to significant legal liabilities and, more importantly, severe harm to minors. Users, particularly parents and advocacy groups, lack effective tools to monitor and mitigate these risks proactively.
**Value Proposition:** Guardian Gate is a cutting-edge SaaS platform designed to empower parents, guardians, and child advocacy organizations by providing advanced AI-driven tools to detect, report, and mitigate online risks to children on social media. We aim to create a safer digital environment by proactively identifying potential threats, enabling swift intervention, and holding platforms accountable.
**Target Users:** Concerned parents, legal guardians, child protection agencies, schools, NGOs focused on child safety, and potentially social media platform safety teams looking for enhanced monitoring tools.
**Key Differentiator:** Unlike reactive reporting tools, Guardian Gate uses predictive AI analysis of platform data (where legally and ethically permissible, focusing on public data and anonymized trends) and user behavior patterns to flag potential risks *before* harm occurs. It also provides a comprehensive dashboard for monitoring and managing digital safety.
# TECH STACK
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (with providers like Google, Email/Password)
- **UI Library:** shadcn/ui
- **State Management:** React Context API / Zustand (for global state)
- **AI/ML Integration:** (Placeholder for future integration - e.g., Python backend with Flask/FastAPI for model serving, or direct API calls to services like OpenAI/Hugging Face for specific NLP tasks like sentiment analysis or threat detection if applicable and ethical)
- **Charting:** Recharts or similar for dashboard visualizations
- **Form Handling:** React Hook Form + Zod for validation
- **Deployment:** Vercel (recommended)
# DATABASE SCHEMA (PostgreSQL with Drizzle ORM)
1. **`users` Table:**
* `id` (UUID, Primary Key, Default: uuid_generate_v4())
* `name` (VARCHAR(255), Not Null)
* `email` (VARCHAR(255), Unique, Not Null)
* `emailVerified` (TIMESTAMP WITH TIME ZONE)
* `hashedPassword` (VARCHAR(255))
* `image` (TEXT) // URL for profile picture
* `role` (VARCHAR(50), Default: 'USER') // e.g., 'USER', 'PARENT', 'ADMIN', 'AGENCY'
* `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
* `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
2. **`accounts` Table (for NextAuth.js):**
* `id` (BIGSERIAL, Primary Key)
* `userId` (UUID, Foreign Key to `users.id` on delete cascade)
* `type` (TEXT)
* `provider` (TEXT)
* `providerAccountId` (TEXT)
* `refresh_token` (TEXT)
* `access_token` (TEXT)
* `expires_at` (BIGINT)
* `token_type` (TEXT)
* `scope` (TEXT)
* `id_token` (TEXT)
* `session_state` (TEXT)
3. **`sessions` Table (for NextAuth.js):**
* `id` (BIGSERIAL, Primary Key)
* `sessionToken` (TEXT, Unique, Not Null)
* `userId` (UUID, Foreign Key to `users.id` on delete cascade)
* `expires` (TIMESTAMP WITH TIME ZONE, Not Null)
4. **`verificationTokens` Table (for NextAuth.js):**
* `identifier` (TEXT)
* `token` (TEXT, Unique, Not Null)
* `expires` (TIMESTAMP WITH TIME ZONE, Not Null)
5. **`organizations` Table:** (For agency/institutional users)
* `id` (UUID, Primary Key, Default: uuid_generate_v4())
* `name` (VARCHAR(255), Not Null)
* `userId` (UUID, Foreign Key to `users.id` on delete cascade, Unique) // Link to the primary user account for the org
* `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
* `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
6. **`monitored_profiles` Table:** (Profiles users want to track, respecting privacy laws)
* `id` (UUID, Primary Key, Default: uuid_generate_v4())
* `userId` (UUID, Foreign Key to `users.id` on delete cascade)
* `organizationId` (UUID, Foreign Key to `organizations.id` on delete cascade, Nullable)
* `profileIdentifier` (VARCHAR(255), Not Null) // e.g., username, platform ID (requires careful handling and user consent)
* `platform` (VARCHAR(100), Not Null) // e.g., 'Facebook', 'Instagram', 'TikTok'
* `status` (VARCHAR(50), Default: 'ACTIVE') // e.g., 'ACTIVE', 'PAUSED', 'ARCHIVED'
* `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
* `updatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
7. **`risk_alerts` Table:**
* `id` (UUID, Primary Key, Default: uuid_generate_v4())
* `monitoredProfileId` (UUID, Foreign Key to `monitored_profiles.id` on delete cascade)
* `alertType` (VARCHAR(100), Not Null) // e.g., 'Predator Pattern', 'Harmful Content', 'Age Inconsistency', 'High Risk Interaction'
* `severity` (VARCHAR(50), Not Null) // e.g., 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'
* `description` (TEXT, Not Null)
* `platformEvidence` (TEXT, Nullable) // Link to or description of evidence on the platform
* `detectedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
* `status` (VARCHAR(50), Default: 'NEW') // e.g., 'NEW', 'ACKNOWLEDGED', 'RESOLVED', 'ESCALATED'
* `assignedToUserId` (UUID, Foreign Key to `users.id` on delete set null, Nullable) // For agencies assigning tasks
* `notes` (TEXT, Nullable)
* `createdAt` (TIMESTAMP WITH TIME ZONE, Default: now())
8. **`platform_reports` Table:** (Aggregated reports for platform-level analysis)
* `id` (UUID, Primary Key, Default: uuid_generate_v4())
* `organizationId` (UUID, Foreign Key to `organizations.id` on delete cascade, Nullable)
* `reportType` (VARCHAR(100), Not Null) // e.g., 'Overall Risk Trends', 'Platform Vulnerability Score', 'Emerging Threats'
* `platform` (VARCHAR(100), Not Null)
* `startDate` (DATE, Not Null)
* `endDate` (DATE, Not Null)
* `data` (JSONB, Not Null) // Stores aggregated metrics, trends, insights
* `generatedAt` (TIMESTAMP WITH TIME ZONE, Default: now())
*Note: All foreign keys should have appropriate `ON DELETE` actions defined (e.g., `CASCADE`, `SET NULL`, `RESTRICT`). Ensure proper indexing on foreign keys and frequently queried columns.*
# CORE FEATURES & USER FLOW
**1. User Authentication & Authorization:**
* **Flow:** Users sign up via email/password or OAuth (Google). Upon signup, they select their role ('Parent', 'Guardian', 'Agency Representative').
* **Auth:** NextAuth.js handles session management.
* **Authorization:** Role-based access control (RBAC) is implemented. Parents see their profiles and alerts. Agency reps can manage multiple profiles and alerts, assign tasks, and view organization-level reports.
* **Admin:** Super admin role for system management.
**2. Profile Onboarding & Monitoring Setup:**
* **Flow:** Authenticated user navigates to 'Add Profile' or 'Dashboard'.
* **Action:** User enters the target `platform` (e.g., Instagram) and `profileIdentifier` (username). User *must* confirm they have legal right/consent to monitor this profile (crucial for ethical and legal compliance).
* **System:** The platform attempts to associate this profile with available (public or ethically sourced) data or flags it for AI analysis. For MVP, focus on user-inputted data and potentially public profile info (username, follower count, post count - *no private data*).
* **State:** `monitored_profiles` table is updated.
**3. AI-Driven Risk Detection (Backend Process):**
* **Trigger:** Periodically (e.g., daily or triggered by new data scrapes/API updates - *simulated for MVP*).
* **Process:** A background job (or scheduled function) iterates through `monitored_profiles`.
* **Analysis:** For each profile, it simulates analysis based on available data points (e.g., language patterns in public comments, interaction frequency, network analysis if feasible/ethical, age-inappropriate content indicators). For MVP, this might involve checking for keywords, sentiment analysis on public text, or flagging unusual activity metrics.
* **Output:** If risk factors exceed predefined thresholds, a new entry is created in the `risk_alerts` table.
* **Example Logic (Simplified):**
* *Predator Pattern:* Detects communication with known underage-looking profiles, unusually high interaction rates with new/anonymous accounts, specific keyword clusters associated with grooming.
* *Harmful Content:* Flags public posts/comments containing hate speech, violence, or explicit content (using NLP models).
* *Age Inconsistency:* Flags profiles claiming significantly different ages or exhibiting behavior inconsistent with stated age.
**4. Dashboard & Alert Management:**
* **Flow:** User logs in and sees their personalized dashboard.
* **Components:** Displays a summary of monitored profiles, active alerts (sorted by severity/date), recent activity, and platform risk scores.
* **Alert View:** User clicks on an alert to see details (`description`, `platformEvidence`, `detectedAt`, `status`).
* **Actions:** User can 'Acknowledge', 'Resolve', or 'Escalate' (for agencies) the alert. For agencies, alerts can be assigned to specific users.
* **State:** `risk_alerts` table `status` and `assignedToUserId` are updated.
**5. Reporting (MVP Focus on Alerts):**
* **Flow:** Users can view historical alerts and filter them (by date, profile, status).
* **Future Scope (Post-MVP):** Generate aggregated `platform_reports` based on alert trends and anonymized data.
# API & DATA FETCHING
* **Architecture:** Next.js App Router - API routes within `app/api/` or Server Actions.
* **Data Fetching:** Primarily server-side fetching (using `async/await` in Server Components) or API routes for dynamic data. Client-side fetching for interactive elements using SWR or React Query if needed.
* **Key API Routes/Server Actions (Examples):
* `POST /api/auth/*`: Handled by NextAuth.js
* `POST /api/profiles`: (Server Action) Add a new `monitored_profile`. Requires user authentication. Validates input (platform, identifier). Inserts into `monitored_profiles` table.
* `GET /api/profiles`: (Server Component or API Route) Fetch profiles for the logged-in user/organization.
* `GET /api/alerts`: (Server Component or API Route) Fetch alerts for the logged-in user/organization, with filtering/sorting parameters (e.g., `?status=NEW&sortBy=detectedAt`).
* `PATCH /api/alerts/:id`: (Server Action) Update alert status (e.g., acknowledge, resolve). Requires authentication and authorization (user owns the alert or is an admin/agency rep).
* `GET /api/dashboard/summary`: (Server Component or API Route) Fetch aggregated data for the dashboard (e.g., count of new alerts, profiles being monitored).
* **Data Flow:** Client requests data -> API Route/Server Component handles request -> Interacts with Database via Drizzle ORM -> Returns JSON response or renders UI.
* **Security:** All API endpoints and Server Actions must enforce authentication and authorization checks.
# COMPONENT BREAKDOWN (Next.js App Router Structure)
```
app/
├── api/
│ └── auth/[...nextauth]/route.ts // NextAuth.js handler
├── (marketing)/
│ ├── layout.tsx
│ ├── page.tsx // Landing Page
│ └── about/page.tsx
│ └── pricing/page.tsx
├── (app)/
│ ├── layout.tsx // Main app layout with sidebar/header
│ ├── dashboard/
│ │ └── page.tsx // Main dashboard component
│ ├── profiles/
│ │ ├── page.tsx // List of monitored profiles
│ │ └── add/page.tsx // Form to add a new profile
│ │ └── [profileId]/page.tsx // View/edit a specific profile (future)
│ ├── alerts/
│ │ ├── page.tsx // List of all alerts with filters
│ │ └── [alertId]/page.tsx // Detailed alert view
│ ├── settings/
│ │ ├── page.tsx // User settings
│ │ └── security/page.tsx // Security settings
│ └── layout.tsx // Nested layout for authenticated users
├── components/
│ ├── ui/
│ │ ├── button.tsx
│ │ ├── card.tsx
│ │ ├── input.tsx
│ │ ├── table.tsx
│ │ ├── alert.tsx // Custom alert display
│ │ ├── badge.tsx
│ │ ├── dialog.tsx // For confirmations etc.
│ │ └── ... // All shadcn/ui components
│ ├── Auth/
│ │ ├── SignInButton.tsx
│ │ ├── SignOutButton.tsx
│ │ └── UserNav.tsx // User dropdown
│ ├── Layout/
│ │ ├── Header.tsx
│ │ ├── Sidebar.tsx
│ │ └── Footer.tsx
│ ├── Dashboard/
│ │ ├── DashboardSummary.tsx // Key metrics cards
│ │ ├── AlertOverviewChart.tsx // Chart of alert types/severity
│ │ └── RecentAlerts.tsx // List of latest alerts
│ ├── Profiles/
│ │ ├── ProfileForm.tsx
│ │ └── ProfileListItem.tsx
│ ├── Alerts/
│ │ ├── AlertDetailView.tsx
│ │ ├── AlertFilter.tsx
│ │ └── AlertTable.tsx
│ └── common/
│ ├── LoadingSpinner.tsx
│ └── ErrorMessage.tsx
├── lib/
│ ├── auth.ts // NextAuth.js config
│ ├── db.ts // Drizzle ORM client setup
│ ├── utils.ts // Helper functions
│ ├── validators.ts // Zod schemas
│ └── ai-simulation.ts // Mock AI logic for MVP
├── providers/
│ └── ThemeProvider.tsx // For theme management
├── hooks/
│ └── useAuth.ts // Custom auth hook (optional)
├── app/layout.tsx // Root layout
└── page.tsx // Default landing page if not using (marketing)
```
* **State Management:** Primarily server components manage their own data. `Zustand` or `Context API` can be used for cross-component state like user authentication status or theme settings.
* **Routing:** App Router conventions for nested routes, loading states, error handling.
# UI/UX DESIGN & VISUAL IDENTITY
* **Design Style:** Modern, Clean, Trustworthy, Slightly Tech-Forward.
* **Color Palette:**
* Primary: `#4A90E2` (Trustworthy Blue)
* Secondary: `#50E3C2` (Vibrant Green/Teal for positive actions/success)
* Accent/Warning: `#F5A623` (Orange/Amber for alerts)
* Danger: `#D0021B` (Red for critical alerts/errors)
* Neutrals: `#FFFFFF` (White), `#F8F9FA` (Light Gray Background), `#CED4DA` (Border), `#495057` (Dark Text), `#212529` (Very Dark Text/Headers)
* **Typography:** A clean sans-serif font family like Inter or Poppins.
* Headings: Poppins (SemiBold, Bold)
* Body Text: Inter (Regular, Medium)
* **Layout:** Use a consistent sidebar navigation for logged-in users. Main content area will use a responsive grid system. Cards are used extensively for summaries and data display.
* **Key UI Elements:**
* **Dashboard:** High-level overview using cards (monitored profiles count, new alerts, etc.) and charts (alert trends over time).
* **Forms:** Clean, well-spaced input fields with clear labels and validation feedback.
* **Tables:** `shadcn/ui` table component for alerts and profiles, with sorting and filtering capabilities.
* **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows and scales appropriately. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
* **Animations:** Subtle animations for loading states (`Suspense` boundary with spinners), hover effects on buttons and links, and smooth transitions between states/pages managed by Next.js and Tailwind CSS.
# SAMPLE/MOCK DATA
**1. Mock User (Admin/Agency):**
* `id`: `uuid()`
* `name`: "Global Child Safety Agency"
* `email`: "agency@guardiangate.com"
* `role`: "AGENCY"
**2. Mock User (Parent):**
* `id`: `uuid()`
* `name`: "Alex Johnson"
* `email`: "alex.j@email.com"
* `role`: "PARENT"
**3. Mock Monitored Profile:**
* `id`: `uuid()`
* `userId`: (ID of Alex Johnson)
* `platform`: "Instagram"
* `profileIdentifier`: "kid_explorer123"
* `status`: "ACTIVE"
**4. Mock Risk Alert (High Severity):**
* `id`: `uuid()`
* `monitoredProfileId`: (ID of the profile above)
* `alertType`: "Predator Pattern"
* `severity`: "HIGH"
* `description`: "Profile 'kid_explorer123' is interacting with multiple newly created, anonymous accounts exhibiting grooming language patterns. High frequency of private messages detected."
* `platformEvidence`: "[Link to Instagram message thread analysis - simulated]"
* `detectedAt`: `now()`
* `status`: "NEW"
**5. Mock Risk Alert (Medium Severity):**
* `id`: `uuid()`
* `monitoredProfileId`: (ID of another profile)
* `alertType`: "Harmful Content Exposure"
* `severity`: "MEDIUM"
* `description`: "Public posts from monitored profile contain borderline violent imagery and aggressive language. Potential exposure to harmful content."
* `platformEvidence`: "[Link to public post analysis - simulated]"
* `detectedAt`: `now() - interval '1 day'`
* `status`: "NEW"
**6. Mock Organization Report (Summary):**
* `id`: `uuid()`
* `organizationId`: (ID of the agency)
* `reportType`: "Overall Risk Trends"
* `platform`: "Instagram"
* `startDate`: "2023-10-01"
* `endDate`: "2023-10-31"
* `data`: `{ "alertCounts": { "predator": 15, "harmfulContent": 30, "other": 10 }, "trend": "increasing", "riskiestAgeGroup": "13-15" }`
* `generatedAt`: `now()`
# ANIMATIONS
- **Page Transitions:** Use Next.js's built-in `Suspense` for route transitions, providing skeleton loaders or spinners. Tailwind CSS can be used to animate the appearance of elements entering the viewport.
- **Button Hovers:** Subtle background color change or slight scale-up effect using Tailwind's `hover:` variants.
- **Loading States:** `LoadingSpinner` component displayed within `Suspense` boundaries or conditional rendering for data fetching operations.
- **Data Entry:** Smooth transitions for form validation feedback (e.g., error messages appearing smoothly).
- **Chart Interactions:** Recharts provides built-in tooltips and hover effects for charts.
# EDGE CASES & VALIDATION
- **Authentication:** Handle `unauthenticated` state gracefully. Redirect to login page. Ensure session expiry and refresh work correctly.
- **Authorization:** Prevent users from accessing data or actions they are not permitted to (e.g., a parent trying to view another user's alerts). Return 403 Forbidden or appropriate error messages.
- **Empty States:** Design thoughtful empty states for dashboards, profile lists, and alert lists (e.g., "You haven't added any profiles to monitor yet. Click here to get started.").
- **Data Validation:** Use Zod schemas with React Hook Form for all form inputs (profile identifier format, email, passwords, etc.). Implement server-side validation for API routes and Server Actions.
- **AI Simulation Errors:** Gracefully handle potential errors in the (mock) AI analysis. Log errors and potentially display a "Data unavailable" message instead of a specific alert.
- **Platform API Changes (Future):** Design with the future possibility of platform APIs changing. Use clear interfaces and potentially abstract data fetching logic.
- **Rate Limiting:** Implement rate limiting on API endpoints to prevent abuse.
- **Error Handling:** Global error handling using Next.js Error page and specific `error.tsx` boundaries. Provide user-friendly error messages.
- **Ethical Considerations & Consent:** Crucial. Ensure clear disclaimers about data usage. MVP should *strictly* avoid accessing private data. The "monitoring consent" step during profile onboarding is paramount.
# TURKISH TRANSLATIONS (Examples for UI Elements)
- **App Title:** Guardian Gate
- **Sign In:** Giriş Yap
- **Sign Up:** Kayıt Ol
- **Dashboard:** Kontrol Paneli
- **My Profiles:** Profillerim
- **Add Profile:** Profil Ekle
- **Alerts:** Uyarılar
- **Settings:** Ayarlar
- **Logout:** Çıkış Yap
- **Active Alerts:** Aktif Uyarılar
- **New Alert:** Yeni Uyarı
- **Severity:** Önem Derecesi
- **Detected:** Tespit Edildi
- **Status:** Durum
- **Acknowledge:** Onayla
- **Resolve:** Çözüldü
- **Escalate:** Yükselt
- **Profile Identifier:** Profil Tanımlayıcı (Kullanıcı Adı)
- **Platform:** Platform
- **Save:** Kaydet
- **Cancel:** İptal
- **Are you sure?** Emin misiniz?
- **This action cannot be undone.** Bu işlem geri alınamaz.
- **No alerts found.** Hiç uyarı bulunamadı.
- **Add your first profile to start monitoring.** İzlemeye başlamak için ilk profilinizi ekleyin.
- **Loading...** Yükleniyor...
- **Error:** Hata
- **An unexpected error occurred.** Beklenmeyen bir hata oluştu.
- **Go back home:** Ana sayfaya dön
- **Edit Profile:** Profili Düzenle
- **Delete Profile:** Profili Sil
- **Organization Name:** Kurum Adı
- **Assign to:** Ata
- **Notes:** Notlar