You are an expert full-stack developer and solution architect tasked with building a cutting-edge, single-page application (SPA) for secure data processing using Fully Homomorphic Encryption (FHE). The application will be a Software as a Service (SaaS) product. The goal is to allow users to perform computations on their encrypted data without ever decrypting it, addressing the critical need for privacy in data analysis, especially for sensitive information.
**1. PROJECT OVERVIEW**
**Application Name:** Gizli Veri İşlem Merkezi (Secure Data Processing Hub)
**Problem Solved:** Traditional cloud-based data processing requires decrypting sensitive data, exposing it to potential breaches and privacy violations. Existing FHE solutions are computationally expensive and complex to implement.
**Value Proposition:** Our platform provides a user-friendly, secure, and efficient way to process encrypted data. Leveraging specialized FHE acceleration (conceptually, as the hardware is not directly integrated in this SPA, but the software aims to be compatible with future hardware or optimized libraries), users can gain insights from their data without compromising privacy. This is crucial for sectors like healthcare, finance, AI development, and research.
**2. TECH STACK**
* **Frontend Framework:** React.js (v18+)
* **State Management:** Zustand (lightweight and performant for global state)
* **Styling:** Tailwind CSS (for rapid UI development and responsive design)
* **Routing:** React Router DOM (for navigation within the SPA)
* **UI Components:** shadcn/ui (for accessible, customizable, and modern UI components)
* **Data Fetching/API:** Axios (for HTTP requests to a hypothetical backend)
* **Form Handling:** React Hook Form (for efficient form validation and management)
* **Icons:** Lucide React
* **Build Tool:** Vite (for fast development server and optimized builds)
* **Deployment:** Netlify/Vercel compatible structure
**3. CORE FEATURES**
* **User Authentication & Management:**
* **Flow:** Users can sign up using email/password or OAuth (e.g., Google). Existing users can log in. A password reset flow will be implemented. User profiles will store basic information and account settings.
* **Details:** Secure password hashing (backend concern, simulated in frontend state for MVP), JWT token management for session persistence (stored in localStorage).
* **Secure Data Upload:**
* **Flow:** Logged-in users can navigate to an 'Upload' section. They can select files (e.g., CSV, JSON) from their local system. Before upload, the data will be conceptually encrypted using a user-specific key (simulated client-side encryption for MVP demonstration). The encrypted file is then uploaded to a (simulated) secure cloud storage.
* **Details:** File type validation (CSV, JSON initially), file size limits, progress indicators during upload, clear visual feedback on encryption status.
* **FHE Analysis Selection:**
* **Flow:** After uploading encrypted data, users can select from a predefined list of FHE-compatible analysis tasks (e.g., 'Compute Encrypted Mean', 'Count Encrypted Records', 'Basic Anomaly Detection'). Each analysis requires specific input parameters, which the user provides within an encrypted context.
* **Details:** A clear UI listing available analyses with brief descriptions. Input forms tailored to each analysis type, ensuring data is provided in an encrypted state.
* **Encrypted Computation & Results:**
* **Flow:** Once an analysis is selected and parameters are provided, the user initiates the computation. The SPA sends a request to the (simulated) backend API, which conceptually triggers the FHE computation. Upon completion, the encrypted results are returned and can be downloaded by the user.
* **Details:** Loading spinners and progress notifications during computation. Clear 'Download Results' button. Results are presented as encrypted files.
* **Project/Data Management:**
* **Flow:** Users can create distinct projects to organize their uploaded datasets and analyses. They can view a dashboard of their projects, datasets, and recent analyses.
* **Details:** Simple list views for projects and datasets, with options to rename or delete (with confirmation).
**4. UI/UX DESIGN**
* **Layout:** Single-page application with a persistent sidebar navigation (collapsible on smaller screens) and a main content area. Clean, modern, and intuitive interface.
* **Color Palette:** Primary: Dark blue (#1e3a8a), Secondary: Teal (#14b8a6), Accent: Orange (#f97316), Neutrals: Grays (#f3f4f6, #6b7280, #1f2937).
* **Typography:** Sans-serif fonts like Inter or Poppins for headings and body text, ensuring readability.
* **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on mobile. Content sections reflow and adapt to screen size. Tailwind CSS's responsive prefixes (sm:, md:, lg:) will be extensively used.
* **Key Components:** Dashboard, File Upload Form, Analysis Selection List, Parameter Input Forms, Data Table (for displaying project/file lists), Loading Modals, Download Buttons.
**5. DATA MODEL (Frontend State - Zustand Store)**
```javascript
// Example state structure
interface UserState {
isAuthenticated: boolean;
user: { id: string; email: string; name?: string } | null;
token: string | null;
}
interface ProjectState {
projects: Array<{ id: string; name: string; createdAt: string }>;
currentProject: string | null; // Current selected project ID
}
interface DatasetState {
datasets: Array<{ id: string; projectId: string; name: string; encryptedUrl: string; originalSize: number; encryptedSize: number; uploadedAt: string; status: 'uploaded' | 'processing' | 'failed' }>;
}
interface AnalysisState {
availableAnalyses: Array<{ id: string; name: string; description: string; requiredParams: Array<{ name: string; type: 'string' | 'number' | 'boolean'; label: string }> }>;
selectedAnalysis: string | null;
analysisParameters: Record<string, any>;
computationStatus: 'idle' | 'running' | 'completed' | 'failed';
resultsUrl: string | null;
}
// Combined store
interface AppState extends UserState, ProjectState, DatasetState, AnalysisState {}
// Mock Data Formats:
// Project: { id: 'proj_123', name: 'Financial Analysis Q3', createdAt: '2023-10-27T10:00:00Z' }
// Dataset: { id: 'data_abc', projectId: 'proj_123', name: 'encrypted_transactions.csv.enc', encryptedUrl: 'https://s3.amazonaws.com/...', originalSize: 1048576, encryptedSize: 1258291, uploadedAt: '2023-10-27T10:05:00Z', status: 'uploaded' }
// Analysis: { id: 'mean_calc', name: 'Compute Mean', description: 'Calculates the average of encrypted numerical data.', requiredParams: [{ name: 'dataColumn', type: 'string', label: 'Data Column' }] }
```
* **Local Storage:** JWT token for session persistence.
* **API Calls:** All data interactions (auth, upload, analysis) will be simulated via API calls to a placeholder backend (e.g., using MockServiceWorker or simple Axios mocks).
**6. COMPONENT BREAKDOWN**
* **`App.tsx`:** Main application component, sets up routing and global layout.
* **`Layout.tsx`:** Main layout component with sidebar navigation and main content area.
* **`Sidebar.tsx`:** Navigation menu component (Dashboard, Projects, Upload, Settings).
* **`pages/`:** Directory for page components.
* **`DashboardPage.tsx`:** Overview of projects, recent activity, quick actions.
* **`LoginPage.tsx`:** User login form.
* **`SignupPage.tsx`:** User registration form.
* **`ProjectsPage.tsx`:** Lists user's projects, allows creation/deletion.
* **`UploadPage.tsx`:** File upload component, displays upload progress.
* **`AnalysisPage.tsx`:** Select analysis, input parameters, initiate computation.
* **`ResultsPage.tsx`:** Displays computation status and provides download link for results.
* **`components/`:** Directory for reusable UI components.
* **`Auth/`:** LoginForm.tsx, SignupForm.tsx
* **`Common/`:** Button.tsx, InputField.tsx, LoadingSpinner.tsx, Modal.tsx, FileUpload.tsx, DataTable.tsx, Notification.tsx
* **`Project/`:** ProjectCard.tsx, ProjectList.tsx, CreateProjectForm.tsx
* **`Dataset/`:** DatasetListItem.tsx
* **`Analysis/`:** AnalysisSelector.tsx, ParameterForm.tsx
* **Component Props Example (`FileUpload.tsx`):**
* `onFileSelect: (file: File) => void`
* `onUpload: (file: File) => Promise<void>`
* `uploadProgress: number`
* `isUploading: boolean`
* `acceptedFileTypes: string[]`
**7. ANIMATIONS & INTERACTIONS**
* **Page Transitions:** Subtle fade-in/fade-out transitions between pages using Framer Motion or CSS transitions.
* **Button Hover Effects:** Slight scale-up or background color change on hover.
* **Loading States:** Use `LoadingSpinner.tsx` component with overlayed background or inline spinners for asynchronous operations (uploading, computing). Skeleton loaders for data tables where applicable.
* **Micro-interactions:** Visual feedback on form submission (e.g., checkmark on success), drag-and-drop visual cues for file uploads.
* **Sidebar Collapse/Expand:** Smooth transition animation.
**8. EDGE CASES**
* **Authentication:** Handle expired tokens, failed login attempts gracefully. Implement JWT refresh logic.
* **File Upload:** Handle large files (chunking simulation), network interruptions, invalid file types, exceeding file size limits. Clear error messages.
* **Analysis Computation:** Handle timeouts, server errors during computation. Provide clear 'Failed' status and error details.
* **Empty States:** Display informative messages and clear calls to action when lists are empty (e.g., 'No projects yet. Create your first project!').
* **Data Validation:** Client-side validation for form inputs (parameter forms) using React Hook Form. Server-side validation is assumed to be handled by the backend.
* **Accessibility (a11y):** Use semantic HTML5 elements. Ensure sufficient color contrast. Implement ARIA attributes where necessary. Keyboard navigability for all interactive elements. Use `shadcn/ui` components which are built with accessibility in mind.
**9. SAMPLE DATA**
* **User Profile:**
```json
{ "id": "user_xyz", "email": "user@example.com", "name": "John Doe" }
```
* **Projects:**
```json
[
{ "id": "proj_abc", "name": "Patient Data Analysis", "createdAt": "2023-10-26T09:30:00Z" },
{ "id": "proj_def", "name": "Financial Risk Modeling", "createdAt": "2023-10-27T11:00:00Z" }
]
```
* **Datasets:**
```json
[
{ "id": "data_111", "projectId": "proj_abc", "name": "encrypted_patient_records.csv.enc", "encryptedUrl": "/data/enc_111.enc", "originalSize": 5242880, "encryptedSize": 6300000, "uploadedAt": "2023-10-26T09:35:00Z", "status": "uploaded" },
{ "id": "data_222", "projectId": "proj_def", "name": "encrypted_market_data.json.enc", "encryptedUrl": "/data/enc_222.enc", "originalSize": 10485760, "encryptedSize": 12000000, "uploadedAt": "2023-10-27T11:05:00Z", "status": "uploaded" }
]
```
* **Available Analyses:**
```json
[
{ "id": "mean_fhe", "name": "Encrypted Mean Calculation", "description": "Computes the average value of a specified numerical column in encrypted data.", "requiredParams": [{"name": "columnName", "type": "string", "label": "Numerical Column Name"}] },
{ "id": "count_fhe", "name": "Encrypted Record Count", "description": "Counts the total number of records in the encrypted dataset.", "requiredParams": [] },
{ "id": "stddev_fhe", "name": "Encrypted Standard Deviation", "description": "Calculates the standard deviation for a specified numerical column.", "requiredParams": [{"name": "columnName", "type": "string", "label": "Numerical Column Name"}] }
]
```
* **Computation Request/Response (Conceptual):**
```json
// Request
{ "datasetId": "data_111", "analysisId": "mean_fhe", "parameters": { "columnName": "blood_pressure" } }
// Response
{ "computationId": "comp_789", "status": "completed", "resultsUrl": "/results/enc_res_789.enc" }
```
**10. DEPLOYMENT NOTES**
* **Build Command:** `npm run build` or `yarn build` (using Vite).
* **Environment Variables:** Use `.env` files for API endpoints, authentication keys (if applicable for frontend-only configuration). Vercel/Netlify will manage production environment variables.
* **Performance Optimizations:** Code splitting via Vite. Lazy loading of components and routes. Image optimization (if any). Memoization of expensive calculations or components using `React.memo` and `useMemo`/`useCallback`.
* **Static Assets:** Configure Vite for optimal handling of static assets.
* **Service Worker:** Consider adding a Service Worker for potential offline capabilities or caching strategies using Vite plugin `vite-plugin-pwa`.
* **Backend Simulation:** For MVP, use tools like `MockServiceWorker` (MSW) to intercept API requests and return mock data, simulating backend responses without a real backend.