You are an expert AI application developer and architect tasked with creating a single-page SaaS application using React and Tailwind CSS. The application, named 'Codex Cost Optimizer', aims to help developers and businesses track, analyze, and optimize their OpenAI Codex API usage costs, which are now primarily based on token consumption.
**PROJECT OVERVIEW:**
The core problem this application addresses is the complexity and potential opacity of OpenAI's Codex API pricing, which has shifted from per-message to token-based usage (input, cached input, output tokens). Users struggle to accurately predict and control their costs, leading to budget overruns. Codex Cost Optimizer provides a transparent dashboard to monitor API calls, visualize token consumption, calculate associated costs based on different OpenAI plans, and offer actionable insights for cost reduction. The primary value proposition is empowering users with financial control and predictability over their AI API expenditures.
**TECH STACK:**
- **Frontend Framework:** React (using Vite for fast development setup)
- **Styling:** Tailwind CSS for rapid UI development and utility-first styling.
- **State Management:** Zustand for efficient and simple global state management.
- **Routing:** React Router DOM for handling navigation within the single-page application.
- **Charting Library:** Recharts for visualizing usage data and cost trends.
- **API Client:** Axios for making HTTP requests to the OpenAI API (or a mock backend).
- **Form Handling:** React Hook Form for robust form management.
- **Date/Time Handling:** date-fns for date manipulation and formatting.
**CORE FEATURES:**
1. **API Key Management:**
* **User Flow:** User navigates to 'Settings' > 'API Keys'. Clicks 'Add New Key'. Enters a descriptive name for the key and the actual OpenAI API key. Clicks 'Save'. The key is stored securely (ideally encrypted server-side, but for MVP, using Local Storage with a warning about security is acceptable). User can view, edit, or delete existing keys.
* **Details:** Secure input fields. Visual feedback on successful save. Clear warnings about storing API keys client-side.
2. **Usage Dashboard:**
* **User Flow:** Upon logging in or accessing the dashboard, the user sees an overview of their recent API usage. A date range selector (e.g., 'Last 7 Days', 'This Month', 'Custom') is available. The dashboard displays key metrics like total API calls, total input tokens, total output tokens, and total credits consumed within the selected period. A primary chart visualizes token usage (input vs. output) over time.
* **Details:** Real-time or near-real-time data updates. Clear data visualization with Recharts. Metrics are prominently displayed using cards or similar UI elements.
3. **Cost Analysis & Prediction:**
* **User Flow:** Integrated within the dashboard or on a dedicated 'Costs' page. Users can select their OpenAI plan (e.g., 'Free Trial', 'Plus', 'Pro', 'Business', 'Enterprise'). The application calculates the estimated cost based on the tracked token usage and the selected plan's rate card. A projected monthly cost is displayed. Users can toggle between different rate cards (e.g., legacy vs. new token-based pricing if applicable).
* **Details:** Requires a configurable data structure for OpenAI's rate cards (token per credit/cost). Calculations must be precise based on input, cached input, and output tokens. Clear display of cost breakdown.
4. **Optimization Suggestions:**
* **User Flow:** A dedicated section or integrated tips on the dashboard. The system analyzes usage patterns (e.g., high output token ratio, frequent small requests). It provides simple, actionable advice like 'Consider batching requests to reduce overhead' or 'Your output token usage is high; review prompt efficiency'. If applicable, it might suggest switching to a different plan tier based on current and projected usage.
* **Details:** Rule-based system for suggestions. Focus on common optimization strategies for LLM APIs.
5. **Plan Comparison Tool:**
* **User Flow:** A separate page where users can input hypothetical usage metrics (e.g., 1M input tokens, 500K output tokens per month). The tool then calculates the estimated cost for each available OpenAI plan (Free, Plus, Pro, Business, Enterprise, considering different tiers if necessary) side-by-side.
* **Details:** Uses the same rate card data as the Cost Analysis feature. Presents a clear comparison table.
**UI/UX DESIGN:**
- **Layout:** Single-page application structure. A clean sidebar navigation for 'Dashboard', 'Costs', 'Plans', 'Settings'. Main content area displays the relevant information. Responsive design is crucial, ensuring usability on various screen sizes (desktop, tablet, mobile).
- **Color Palette:** Primarily a dark theme (e.g., dark blues, grays, black background) to be easy on the eyes for developers, with bright accent colors (e.g., vibrant blue, green, or orange) for interactive elements, charts, and important data points. Use Tailwind's `dark:` variant for theme switching if desired.
- **Typography:** Clean, modern sans-serif fonts (e.g., Inter, Poppins) for readability. Clear hierarchy using font sizes and weights.
- **Responsive Rules:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Charts and tables adapt to screen width. Use Tailwind's responsive prefixes (sm:, md:, lg:, xl:).
**COMPONENT BREAKDOWN:**
- `App.jsx`: Main application component, sets up routing.
- `Layout.jsx`: Main layout component with Sidebar and Header.
- `Sidebar.jsx`: Navigation component.
- `DashboardPage.jsx`: Contains overview metrics, usage charts, and recent activity.
- `UsageChart.jsx`: Recharts component for token usage visualization.
- `MetricCard.jsx`: Displays key metrics (Total Calls, Tokens, Cost).
- `CostsPage.jsx`: Detailed cost breakdown, prediction, and plan selection.
- `PlanSelector.jsx`: Component to choose the current OpenAI plan.
- `CostBreakdown.jsx`: Shows cost per token type (input, output, cached).
- `ProjectionChart.jsx`: Visualizes projected monthly costs.
- `PlansPage.jsx`: Plan comparison tool.
- `PlanComparisonTable.jsx`: Table comparing costs across different plans.
- `SettingsPage.jsx`: API key management.
- `ApiKeyList.jsx`: Displays saved API keys.
- `ApiKeyForm.jsx`: Form to add/edit API keys.
- `common/`: Directory for shared components like `Button.jsx`, `Input.jsx`, `Card.jsx`, `LoadingSpinner.jsx`, `Alert.jsx`.
**DATA MODEL:**
- **State (`Zustand` stores):**
- `apiKeysStore`: `{ keys: [{ id: string, name: string, key: string }] }`
- `usageStore`: `{ usageData: [{ timestamp: Date, inputTokens: number, outputTokens: number, cachedTokens: number, calls: number }], selectedDateRange: string }`
- `costStore`: `{ currentPlan: string, rateCard: object, calculatedCosts: { totalCost: number, costPerType: { input: number, output: number, cached: number } }, projectedMonthlyCost: number }`
- `plansStore`: `{ availablePlans: [...] }`
- **`rateCard` Object Structure Example:**
```json
{
"planName": "ChatGPT Business New",
"pricing": {
"inputTokensPerMillion": 0.50, // USD per 1M input tokens
"cachedInputTokensPerMillion": 0.50, // USD per 1M cached input tokens
"outputTokensPerMillion": 1.50 // USD per 1M output tokens
},
"effectiveDate": "2026-04-02"
}
```
**ANIMATIONS & INTERACTIONS:**
- **Hover Effects:** Subtle background color changes or slight scaling on buttons and interactive elements.
- **Transitions:** Smooth transitions for route changes (using `CSSTransition` or similar if needed, though often CSS `transition` properties suffice for elements). Fade-in effects for charts and data loading.
- **Loading States:** Display `LoadingSpinner.jsx` components while fetching data from the (mock) API. Use skeleton loaders for UI elements where appropriate.
- **Micro-interactions:** Button click feedback, form validation feedback (e.g., error messages appearing smoothly).
**EDGE CASES:**
- **No API Keys:** Display a clear message prompting the user to add an API key.
- **No Usage Data:** Show an empty state message on the dashboard (e.g., "No data available for the selected period. Start making API calls!").
- **API Errors:** Gracefully handle errors from the (mock) OpenAI API calls (e.g., invalid API key, rate limits exceeded) and display user-friendly error messages using `Alert.jsx`.
- **Invalid Input:** Use `React Hook Form` for validation on forms (API keys, plan comparison inputs). Ensure numeric inputs only accept numbers.
- **Accessibility (a11y):** Use semantic HTML elements. Ensure sufficient color contrast. Add `aria-labels` where necessary. Ensure keyboard navigability.
**SAMPLE DATA (Mock Usage Data & Plans):**
* **Mock Usage Records (Array):**
```json
[
{ "timestamp": "2023-10-26T10:00:00Z", "inputTokens": 1200, "outputTokens": 850, "cachedTokens": 0, "calls": 1 },
{ "timestamp": "2023-10-26T10:05:00Z", "inputTokens": 500, "outputTokens": 300, "cachedTokens": 100, "calls": 1 },
{ "timestamp": "2023-10-26T11:15:00Z", "inputTokens": 2500, "outputTokens": 1800, "cachedTokens": 0, "calls": 1 },
{ "timestamp": "2023-10-27T09:00:00Z", "inputTokens": 1500, "outputTokens": 1100, "cachedTokens": 200, "calls": 2 },
// ... more records for different days/times
]
```
* **Mock Rate Card Data (Array of Objects):**
```json
[
{
"planName": "Free Trial",
"pricing": {"inputTokensPerMillion": 0, "cachedInputTokensPerMillion": 0, "outputTokensPerMillion": 0},
"notes": "Limited usage, not intended for production."
},
{
"planName": "Plus (Legacy)",
"pricing": {"inputTokensPerMillion": 0.75, "cachedInputTokensPerMillion": 0.75, "outputTokensPerMillion": 1.50},
"notes": "Legacy pricing, may be migrated."
},
{
"planName": "Pro (Legacy)",
"pricing": {"inputTokensPerMillion": 0.60, "cachedInputTokensPerMillion": 0.60, "outputTokensPerMillion": 1.20},
"notes": "Legacy pricing, may be migrated."
},
{
"planName": "Business (New Token-Based)",
"pricing": {"inputTokensPerMillion": 0.50, "cachedInputTokensPerMillion": 0.50, "outputTokensPerMillion": 1.50},
"effectiveDate": "2026-04-02"
},
{
"planName": "Enterprise (New Token-Based)",
"pricing": {"inputTokensPerMillion": 0.40, "cachedInputTokensPerMillion": 0.40, "outputTokensPerMillion": 1.30},
"notes": "Custom rates may apply, contact sales."
}
]
```
**DEPLOYMENT NOTES:**
- **Build Command:** `npm run build` (or `yarn build`).
- **Environment Variables:** Use `.env` files for sensitive information if deploying with a backend. For a pure client-side MVP storing keys in Local Storage, no critical environment variables are needed beyond potentially API endpoints if mocking isn't sufficient.
- **Performance Optimizations:** Code splitting (handled by Vite/React). Image optimization (if any used). Lazy loading components. Memoization (`React.memo`, `useMemo`, `useCallback`) where performance bottlenecks are identified.
- **Hosting:** Can be deployed statically to platforms like Vercel, Netlify, or GitHub Pages.
- **Security:** Emphasize that storing API keys in Local Storage is **not** recommended for production. A proper backend with secure key management and potentially proxying API requests is necessary for a production-ready application.