You are an expert AI architect and full-stack developer tasked with creating a single-page, highly responsive React application using Next.js and Tailwind CSS. The application, named 'Token Kısaltıcı: Yapay Zeka Sohbet Optimizatörü', aims to significantly reduce token usage in AI chatbot interactions while maintaining technical accuracy, inspired by the 'Caveman' concept. This tool will be invaluable for developers, researchers, and content creators looking to cut costs and improve response times when interacting with Large Language Models (LLMs).
**1. PROJECT OVERVIEW:**
The core purpose of this application is to provide a user-friendly interface and an API endpoint that takes natural language text (intended for an LLM) and rephrases it into a more concise, 'caveman-like' yet technically accurate format. This dramatically reduces the token count required by the LLM, leading to significant cost savings and faster processing times. The value proposition is clear: 'Use fewer tokens, pay less, get faster AI responses without sacrificing accuracy.' The application will serve both as a standalone web tool and an integrable API service.
**2. TECH STACK:**
- **Framework:** Next.js (for potential SSR/ISR benefits and routing, although primarily a SPA focus for MVP)
- **UI Library:** Tailwind CSS (for rapid, utility-first styling)
- **State Management:** Zustand (lightweight and efficient for this scale)
- **Forms:** React Hook Form (for robust form handling and validation)
- **API Client:** Axios (or native fetch)
- **Icons:** React Icons
- **Animations:** Framer Motion (for smooth UI transitions and micro-interactions)
**3. CORE FEATURES:**
* **Text Input & Optimization:**
* **User Flow:** The user lands on the main page. They see a large, clear textarea for inputting their prompt or message. Below this, there are controls to select the optimization level (e.g., 'Lite', 'Medium', 'Full Caveman'). A prominent 'Optimize' button triggers the process.
* **Backend Logic (Simulated for Frontend):** Upon clicking 'Optimize', the input text and selected level are sent to a (simulated) backend service. The frontend displays a loading state. The response, containing both the original text and the optimized 'caveman' version, is then displayed.
* **Optimization Level Selection:**
* **User Flow:** Radio buttons or a segmented control allow users to choose between 'Lite' (slight reduction, very natural), 'Medium' (balanced reduction), and 'Full Caveman' (maximum reduction, potentially less natural but highly concise).
* **Logic:** This selection would ideally map to different prompting strategies or parameter adjustments on the backend. For the MVP frontend, it primarily affects the display and potentially mock data generation.
* **Comparison View:**
* **User Flow:** After optimization, the original text and the optimized text are displayed side-by-side or in an expandable section. Key metrics like token count reduction (e.g., 'Saved 75% tokens', 'Reduced from 69 to 19 tokens') and the absolute difference are clearly shown.
* **UI:** Use distinct visual styles (e.g., different background colors, icons like 🗣️ and 🪨) to differentiate original vs. optimized text.
* **API Integration Snippet:**
* **User Flow:** A dedicated section or a toggle reveals example code snippets (e.g., JavaScript, Python using `fetch` or `axios`) showing how to call the application's API endpoint with their text and desired level.
* **MVP Focus:** Displaying a clear, copyable example is sufficient.
**4. UI/UX DESIGN:**
* **Layout:** A clean, single-column layout for the main optimization interface on desktop, stacking vertically on mobile. A simple navigation bar at the top for 'Optimizer', 'API Docs', and potentially 'About'.
* **Color Palette:** Primary colors: Dark charcoal/deep blue for backgrounds (#1a202c), a vibrant accent color like teal or orange (#06b6d4 or #f97316) for buttons and highlights. Secondary colors: Light gray for input borders, white/off-white for text. Use distinct colors for 'Normal' (e.g., blueish) and 'Caveman' (e.g., earthy orange/brown) text blocks.
* **Typography:** A modern, readable sans-serif font like Inter or Poppins. Use varying weights and sizes for hierarchy (e.g., large headings, standard body text, smaller labels).
* **Responsive Design:** Mobile-first approach. Ensure usability on small screens. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`) extensively. Textareas should resize appropriately. Buttons should be easily tappable.
* **Interactions:** Subtle hover effects on buttons and links. Smooth transitions for expanding/collapsing sections (like API docs).
**5. DATA MODEL (State Management - Zustand):**
```javascript
// Example Zustand store
interface AppState {
originalText: string;
optimizedText: string;
optimizationLevel: 'lite' | 'medium' | 'full';
isLoading: boolean;
comparisonMetrics: {
originalTokens: number;
optimizedTokens: number;
tokensSaved: number;
percentageSaved: number;
} | null;
error: string | null;
setOriginalText: (text: string) => void;
setOptimizationLevel: (level: 'lite' | 'medium' | 'full') => void;
optimizeText: () => Promise<void>; // This would call the API/mock service
// ... other setters and reset functions
}
const useAppStore = create<AppState>(set => ({
originalText: '',
optimizedText: '',
optimizationLevel: 'medium',
isLoading: false,
comparisonMetrics: null,
error: null,
setOriginalText: (text) => set({ originalText: text, optimizedText: '', comparisonMetrics: null, error: null }),
setOptimizationLevel: (level) => set({ optimizationLevel: level }),
optimizeText: async () => {
set({ isLoading: true, error: null, optimizedText: '', comparisonMetrics: null });
try {
// --- SIMULATED API CALL ---
const mockResponse = await simulateApiCall(get().originalText, get().optimizationLevel);
set({
optimizedText: mockResponse.optimizedText,
comparisonMetrics: {
originalTokens: mockResponse.originalTokens,
optimizedTokens: mockResponse.optimizedTokens,
tokensSaved: mockResponse.originalTokens - mockResponse.optimizedTokens,
percentageSaved: ((mockResponse.originalTokens - mockResponse.optimizedTokens) / mockResponse.originalTokens) * 100,
},
isLoading: false,
});
// --- END SIMULATION ---
} catch (err) {
set({ error: 'Optimization failed. Please try again.', isLoading: false });
console.error(err);
}
},
}));
// Mock API Simulation Function
const simulateApiCall = async (inputText: string, level: string): Promise<any> => {
// Dummy token counts and simple logic for simulation
const baseTokens = inputText.split('\s+').length;
let multiplier = 1;
if (level === 'lite') multiplier = 0.8;
else if (level === 'medium') multiplier = 0.5;
else if (level === 'full') multiplier = 0.25;
const simulatedOptimizedTokens = Math.max(10, Math.round(baseTokens * multiplier)); // Ensure minimum tokens
const simulatedOptimizedText = generateCavemanText(inputText, level); // Placeholder for actual text generation logic
return new Promise(resolve => {
setTimeout(() => {
resolve({
originalText: inputText,
optimizedText: simulatedOptimizedText,
originalTokens: baseTokens,
optimizedTokens: simulatedOptimizedTokens,
});
}, 700); // Simulate network latency
});
};
// Placeholder for caveman text generation
const generateCavemanText = (text: string, level: string): string => {
if (level === 'full') {
// Simple aggressive shortening logic
return text.replace(/\b\w{4,}\b/g, word => word.substring(0, 2)).replace(/\s+/g, ' ').trim();
}
// More sophisticated logic based on level would go here
return "Shorten like caveman. " + text.split('. ').join('. ')"+".";
}
export default useAppStore;
```
**6. COMPONENT BREAKDOWN:**
* **`PageLayout`:** Main container, handles overall page structure, padding, and responsiveness using Tailwind.
* **`Navbar`:** Top navigation bar with logo/app title and links.
* **`OptimizerView`:** Main component containing input, controls, and output display.
* **`TextInputArea`:** Handles the main `textarea` for user input. Receives `value` and `onChange` props.
* **`OptimizationControls`:** Contains the `LevelSelector` and the `OptimizeButton`.
* **`LevelSelector`:** Radio group or segmented control for selecting 'Lite', 'Medium', 'Full'. Receives `selectedValue` and `onChange` props.
* **`OptimizeButton`:** Triggers the `optimizeText` action. Displays 'Optimizing...' when `isLoading` is true. Uses Framer Motion for hover effects.
* **`ComparisonDisplay`:** Shows original text, optimized text, and token metrics. Conditionally rendered.
* **`TextBlock`:** Reusable component to display text content with a label (e.g., 'Normal', 'Caveman') and distinct styling. Takes `title`, `text`, and `variant` props.
* **`MetricsCard`:** Displays token savings. Takes `originalTokens`, `optimizedTokens`, `percentageSaved` props.
* **`ApiDocs`:** Component (perhaps a separate page or modal) displaying API usage instructions and examples.
* **`CodeSnippet`:** Displays syntax-highlighted code examples. Takes `language` and `code` props.
**7. ANIMATIONS & INTERACTIONS:**
* **Button Hover:** Subtle scale-up or background color change on button hover using Tailwind's `hover:` variants and Framer Motion.
* **Loading State:** When 'Optimize' is clicked, the button text changes to 'Optimizing...' and a small spinner animation appears. The input/output areas might show a subtle pulsing or placeholder animation.
* **Section Expansion:** Smooth expansion/collapse animation for the API documentation section using Framer Motion's `AnimatePresence` and `motion.div`.
* **Text Fade-in:** Optimized text could fade in upon successful generation.
**8. EDGE CASES:**
* **Empty Input:** If the input textarea is empty when 'Optimize' is clicked, display a validation message (e.g., 'Please enter text to optimize.'). Disable the button if empty.
* **API Errors:** Gracefully handle API errors. Display a user-friendly message (e.g., 'Sorry, optimization failed. Please try again later.') in the `error` state, clearing previous results.
* **No Token Savings:** If the optimization results in no token saving (or even an increase due to placeholder logic), display a message indicating this, perhaps disabling the metrics card or showing zero savings.
* **Accessibility (a11y):** Ensure all interactive elements have proper ARIA attributes. Use semantic HTML. Ensure sufficient color contrast. Keyboard navigation should be fully supported.
* **Long Text:** The UI should handle very long input/output texts gracefully, potentially using scrolling within text areas or truncating display with a 'show more' option.
**9. SAMPLE DATA (Mock Data for `simulateApiCall`):**
* **Input 1:** "The reason your React component is re-rendering is likely because you're creating a new object reference on each render cycle. When you pass an inline object as a prop, React's shallow comparison sees it as a different object every time, which triggers a re-render. I'd recommend using useMemo to memoize the object."
* **Level: 'full'**
* **Output:** "New object ref each render. Inline object prop = new ref = re-render. Use useMemo."
* **Tokens:** Original: ~69, Optimized: ~19
* **Input 2:** "Sure! I'd be happy to help you with that. The issue you're experiencing is most likely caused by your authentication middleware not properly validating the token expiry. Let me take a look and suggest a fix."
* **Level: 'full'**
* **Output:** "Auth middleware bug. Token expiry check < not <=. Fix: Check expiry."
* **Tokens:** Original: ~45, Optimized: ~15
* **Input 3:** "Could you please provide a detailed explanation of the process for setting up a new Node.js project, including dependency installation and basic server configuration?"
* **Level: 'medium'**
* **Output:** "Explain Node.js setup: install deps, basic server config."
* **Tokens:** Original: ~25, Optimized: ~10
* **Input 4:** "I need to write a Python function that takes a list of integers and returns the sum of all even numbers in the list. Please ensure it handles empty lists gracefully."
* **Level: 'lite'**
* **Output:** "Write Python function: sum even numbers in list. Handle empty list."
* **Tokens:** Original: ~30, Optimized: ~22
* **Input 5:** "What are the primary differences between the Agile and Waterfall methodologies in software development project management?"
* **Level: 'full'**
* **Output:** "Agile vs Waterfall software project management?"
* **Tokens:** Original: ~20, Optimized: ~6
**10. DEPLOYMENT NOTES:**
* **Build:** Use `next build` for production deployment.
* **Environment Variables:** Define `NEXT_PUBLIC_API_BASE_URL` for the backend API endpoint if separating frontend/backend. For MVP, the simulation runs client-side.
* **Performance:** Optimize images (if any). Code-split components that are not critical for the initial load (e.g., `ApiDocs` if implemented as a separate route/modal).
* **Hosting:** Can be deployed on Vercel, Netlify, or other static hosting providers.
* **CORS:** If a separate backend API is used, ensure CORS is configured correctly to allow requests from the frontend domain.