You are an AI assistant tasked with creating a single-page, server-rendered React application using Next.js and Tailwind CSS. The application is a SaaS platform called 'Kod Kalitesi ve Bakım Kalkanı' (Code Quality and Maintenance Shield). Its primary goal is to combat the "everything is broken" phenomenon often associated with rapid AI-assisted development, by analyzing code quality, maintainability, and identifying risks introduced by AI coding agents.
## PROJECT OVERVIEW
**Purpose:** To provide development teams with tools to monitor, analyze, and improve the quality and maintainability of their codebase, particularly in the context of using AI coding agents. The platform aims to prevent the "brittle mess" state of software that can arise from unchecked AI-generated code or rapid, low-maintenance development cycles.
**Problem Solved:** Addresses the degradation of software quality, increased technical debt, and maintenance difficulties that can emerge when AI coding agents are used extensively without proper oversight and quality control. It helps teams "slow the fuck down" intelligently by providing data-driven insights.
**Value Proposition:** Enables teams to build and maintain high-quality, robust, and long-lasting software even when leveraging advanced AI coding tools. It shifts focus from rapid, potentially low-quality output to sustainable, maintainable development, reducing long-term costs and risks.
## TECH STACK
* **Framework:** Next.js (for server-side rendering, API routes, and optimized performance)
* **UI Library:** Tailwind CSS (for rapid, utility-first styling)
* **State Management:** Zustand (lightweight and efficient for global state)
* **Data Fetching:** React Query (for efficient server-state management and caching)
* **Charting:** Chart.js or Recharts (for visualizing metrics)
* **Icons:** Heroicons orlucide-react
* **Deployment:** Vercel (recommended for Next.js)
## CORE FEATURES & USER FLOW
1. **Project Onboarding (Git Integration):**
* **User Flow:** User navigates to 'Projects' > 'Add New Project'. They authenticate with their Git provider (GitHub, GitLab, Bitbucket). They select a repository to monitor. The system clones the repository (or fetches relevant metadata) to its analysis environment.
* **Details:** Secure OAuth flow for Git provider. Users can select specific branches to monitor. Initial analysis runs upon setup.
2. **AI Code Analysis & Risk Detection:**
* **User Flow:** After onboarding, the system automatically analyzes the selected repository. It identifies code sections potentially generated or heavily modified by AI agents (heuristic-based, e.g., common AI patterns, lack of comments, unusual complexity). It flags potential issues like "compounding booboos with zero learning, no bottlenecks, and delayed pain," "merchants of learned complexity," and "agentic search has low recall."
* **Details:** Analysis focuses on complexity metrics (e.g., cyclomatic complexity), code duplication, adherence to coding standards (basic linting checks), and historical commit analysis to spot AI-driven changes.
3. **Maintainability Index:**
* **User Flow:** User views a dashboard for a selected project. A prominent 'Maintainability Index' score (e.g., 0-100) is displayed. Hovering over the score reveals contributing factors (e.g., Code Complexity: -15, Test Coverage: +10, Documentation: -5).
* **Details:** This index is a calculated score based on multiple factors. It provides a quick health check of the codebase's long-term viability.
4. **Technical Debt Visualization:**
* **User Flow:** Within the project dashboard, a 'Technical Debt' section shows a trend graph of accumulated technical debt over time. Specific debt items, flagged as potentially AI-introduced, are listed with severity and estimated remediation effort.
* **Details:** Uses charting libraries to display debt accumulation trends. Links identified debt items back to specific code commits or files.
5. **Reporting & Insights:**
* **User Flow:** Users can access a 'Reports' section to generate and download PDF reports summarizing the project's health, identified risks, maintainability index trends, and technical debt.
* **Details:** Reports are customizable (date range, specific metrics). Provides actionable insights and suggestions for improvement.
## UI/UX DESIGN
* **Layout:** Single-page application (SPA) feel within Next.js. A persistent sidebar navigation (Projects, Dashboard, Reports, Settings) and a main content area. Minimalist and data-focused.
* **Color Palette:** Primary: Dark charcoal (#1a1a1a), Secondary: Deep blue (#007bff), Accent: Teal/Green (#20c997), Text: Light gray (#e0e0e0), Error: Red (#dc3545). Use a dark theme to reduce eye strain and focus on code-related data.
* **Typography:** Use a clean, readable sans-serif font like Inter or Roboto for body text and headings. Code snippets should use a monospaced font like Fira Code or Source Code Pro.
* **Responsive Design:** Mobile-first approach using Tailwind CSS's responsive modifiers (sm:, md:, lg:). Sidebar collapses into a hamburger menu on smaller screens. Charts and tables adapt to screen width.
* **Key Components:** Dashboard widgets (cards for scores, charts), tables for lists (projects, risks), forms for settings/onboarding, modals for confirmation/details, loading spinners, empty state illustrations.
## COMPONENT BREAKDOWN
* **`Layout.js`:** Main application layout wrapper. Includes sidebar, header (if any), and main content area. Handles responsive sidebar toggle.
* Props: `children`
* **`Sidebar.js`:** Navigation menu component.
* Props: `currentRoute`
* **`ProjectList.js`:** Displays a list of monitored projects.
* Props: `projects` (array of project objects)
* **`ProjectCard.js`:** Individual project summary card in the list.
* Props: `project` (object with name, status, maintainability score)
* **`Dashboard.js`:** Main dashboard view for a selected project.
* Components: `MaintainabilityChart.js`, `TechDebtTrendChart.js`, `RiskAlerts.js`, `AIAttributionScore.js`
* **`MaintainabilityChart.js`:** Displays the Maintainability Index score and trend.
* Props: `scoreHistory` (array of {date, score})
* **`TechDebtTrendChart.js`:** Displays the technical debt trend.
* Props: `debtHistory` (array of {date, debtAmount})
* **`RiskAlerts.js`:** Lists detected risks and issues.
* Props: `risks` (array of risk objects {description, severity, file, line})
* **`AIAttributionScore.js`:** Shows a score or percentage indicating the likely AI contribution to recent changes.
* Props: `aiContributionPercent`
* **`AddProjectForm.js`:** Form for adding a new project, including Git authentication flow.
* **`Settings.js`:** User and system settings.
* **`LoadingSpinner.js`:** Generic loading indicator.
* **`EmptyState.js`:** Displays when no projects or data are available.
## DATA MODEL (State Management with Zustand & React Query)
* **`useProjectStore` (Zustand):** Manages the list of projects and the currently selected project.
* `projects`: `Array<{id: string, name: string, gitUrl: string, status: 'analyzing' | 'healthy' | 'warning' | 'error', maintainabilityScore: number, lastAnalysis: string}>`
* `selectedProjectId`: `string | null`
* `setProjects`: `function`
* `setSelectedProject`: `function`
* **`useAnalysisStore` (Zustand - potentially for UI state):** Manages UI-specific states like active tabs, filters.
* **React Query:** Handles fetching data from backend API routes (simulated via Next.js API routes for MVP).
* `queryKey: ['project', projectId, 'analysis']` -> Fetches detailed analysis data (metrics, risks, debt) for a project.
* `queryKey: ['projects']` -> Fetches the list of projects.
**Mock Data Format:**
```json
{
"projects": [
{
"id": "proj_123",
"name": "Alpha Project",
"gitUrl": "https://github.com/user/alpha",
"status": "healthy",
"maintainabilityScore": 78,
"lastAnalysis": "2024-07-26T10:00:00Z"
},
{
"id": "proj_456",
"name": "Beta Initiative",
"gitUrl": "https://github.com/user/beta",
"status": "warning",
"maintainabilityScore": 45,
"lastAnalysis": "2024-07-26T09:30:00Z"
}
],
"analysisData": {
"proj_123": {
"id": "proj_123",
"maintainabilityHistory": [
{"date": "2024-07-25", "score": 75},
{"date": "2024-07-26", "score": 78}
],
"techDebtHistory": [
{"date": "2024-07-25", "amount": 120},
{"date": "2024-07-26", "amount": 115}
],
"aiContributionPercent": 15,
"risks": [
{
"id": "risk_001",
"description": "High cyclomatic complexity in auth module, possibly AI-generated.",
"severity": "medium",
"filePath": "src/modules/auth/handler.js",
"lineNumber": 55,
"suggestedAction": "Refactor the function to reduce complexity.",
"introducedByAI": true
}
]
},
"proj_456": {
"id": "proj_456",
"maintainabilityHistory": [
{"date": "2024-07-25", "score": 40},
{"date": "2024-07-26", "score": 45}
],
"techDebtHistory": [
{"date": "2024-07-25", "amount": 350},
{"date": "2024-07-26", "amount": 365}
],
"aiContributionPercent": 65,
"risks": [
{
"id": "risk_002",
"description": "Significant code duplication detected in payment processing.",
"severity": "high",
"filePath": "src/services/payment.js",
"lineNumber": null,
"suggestedAction": "Create reusable utility functions.",
"introducedByAI": true
},
{
"id": "risk_003",
"description": "Lack of unit tests for critical API endpoints.",
"severity": "medium",
"filePath": "src/api/users.js",
"lineNumber": null,
"suggestedAction": "Implement comprehensive unit tests.",
"introducedByAI": false
}
]
}
}
}
```
## ANIMATIONS & INTERACTIONS
* **Page Transitions:** Subtle fade-in/fade-out transitions between pages/sections using Next.js's `transition` or a library like Framer Motion (optional for MVP).
* **Hover Effects:** Subtle background color changes or slight scaling on interactive elements like buttons, project cards, and links.
* **Loading States:** Use `react-query`'s `isLoading` state to display `LoadingSpinner.js` components. Skeleton loaders can be used for dashboard widgets before data fetches.
* **Micro-interactions:** Smooth expansion/collapse of details in risk lists. Subtle animations on chart data points appearing.
* **Form Interactions:** Visual feedback on input validation (e.g., red borders for invalid fields).
## EDGE CASES & VALIDATION
* **No Projects:** Display `EmptyState.js` with a clear call-to-action to add the first project.
* **Analysis in Progress:** Show a distinct status ('Analyzing...') on project cards and dashboard, with spinners. Prevent viewing detailed metrics until complete.
* **API Errors:** Gracefully handle errors during data fetching (e.g., Git authentication failure, analysis server error). Display user-friendly error messages using snackbars or dedicated error components.
* **Empty Analysis Data:** If a project has no risks or data yet, display informative messages (e.g., "No significant risks detected yet.").
* **Input Validation:** Validate project name, Git URL formats on the Add Project form.
* **Accessibility (a11y):** Ensure proper semantic HTML, ARIA attributes where necessary, keyboard navigation, and sufficient color contrast.
## SAMPLE DATA (Beyond Mock Data Format above)
* **Risk Object Example:**
```json
{
"id": "risk_004",
"description": "Code complexity in `processOrder` exceeds threshold (15). High potential for bugs.",
"severity": "high",
"filePath": "src/services/order_processing.js",
"lineNumber": 112,
"suggestedAction": "Break down the `processOrder` function into smaller, single-responsibility functions.",
"introducedByAI": true,
"analysisTimestamp": "2024-07-26T08:15:00Z"
}
```
* **Maintainability Score Breakdown (Example for display):**
```json
{
"score": 45,
"factors": {
"complexity": {"value": 30, "weight": 0.4, "contribution": -12},
"testCoverage": {"value": 40, "weight": 0.3, "contribution": 12},
"documentation": {"value": 20, "weight": 0.2, "contribution": -8},
"codeDuplication": {"value": 50, "weight": 0.1, "contribution": -5}
}
}
```
## DEPLOYMENT NOTES
* **Environment Variables:** Use `.env.local` for local development and Vercel's environment variable settings for production. Key variables: `NEXT_PUBLIC_API_URL`, `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITLAB_CLIENT_ID`, `GITLAB_CLIENT_SECRET`.
* **Build Command:** `npm run build` (or `yarn build`)
* **Output Directory:** `.next`
* **Performance Optimizations:** Leverage Next.js features like automatic code splitting, image optimization (`next/image`), and server-side rendering/static generation where appropriate. Optimize Tailwind CSS by purging unused styles in production builds.
* **API Routes:** Implement Next.js API routes (`pages/api/`) to simulate backend functionality for Git interaction (using libraries like Octokit for GitHub) and analysis processing. For a real SaaS, these would connect to a dedicated backend service and database.
* **Database:** For MVP, mock data can be managed in memory or local storage. For production, a database like PostgreSQL or MongoDB would be required to store project data, analysis results, and user information.