import React, { useState, useEffect, useRef } from 'react';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { initLocalEngine, routeInference } from '../utils/inferenceRouter';
import HCaptcha from '@hcaptcha/react-hcaptcha';
import { supabase, useAuth, GATEWAY_URL, LEMON_CHECKOUT_URL } from '../context';
import ApiKeyCard from './ApiKeyCard';
import UsageCard from './UsageCard';
import BillingCard from './BillingCard';
import CodePlayground from './CodePlayground';
import OpticParseSection from './OpticParseSection';
import PhishVisionSection from './PhishVisionSection';
import QuickTestSection from './QuickTestSection';
import BulkScannerSection from './BulkScannerSection';
import WatchDashboardSection from './WatchDashboardSection';
import QuickStatsBar from './QuickStatsBar';
import FeedbackModal from './FeedbackModal';
import LogsSection from './LogsSection';
import SettingsKeysSection from './SettingsKeysSection';
import IntegrationsSection from './IntegrationsSection';
import ExperimentalFeaturesSection from './ExperimentalFeaturesSection';
const Icons = {
dashboard: ,
key: ,
chart: ,
credit: ,
code: ,
mail: ,
logout:
};
export default function Dashboard() {
const { user, signOut } = useAuth()
const [page, setPage] = useState('dashboard')
const [apiKey, setApiKey] = useState(null)
const [usage, setUsage] = useState({ tier: 'free', monthly_limit: 100, current_usage: 0, usage_reset_at: null })
const [isFeedbackOpen, setIsFeedbackOpen] = useState(false)
// Fetch usage and key on mount
useEffect(() => {
if (user?.id) {
fetch(`${GATEWAY_URL}/gateway/usage/${user.id}`)
.then(r => r.json())
.then(setUsage)
.catch(() => {})
const savedKey = localStorage.getItem(`opticparse_apikey_${user.id}`)
if (savedKey) {
setApiKey(savedKey)
} else {
handleGenerateKey()
}
}
}, [user])
const handleGenerateKey = async () => {
try {
const res = await fetch(`${GATEWAY_URL}/gateway/keys/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: user.id, email: user.email }),
})
if (res.status === 400) {
// Hit the 3 key limit, auto-regenerate instead to clear them
await handleRegenerate(true)
return
}
const data = await res.json()
if (data.api_key) {
setApiKey(data.api_key)
localStorage.setItem(`opticparse_apikey_${user.id}`, data.api_key)
}
} catch (err) {
console.error('Key generation failed:', err)
}
}
const handleRegenerate = async (silent = false) => {
if (!silent && !confirm('Are you sure? Your old key will stop working immediately.')) return;
try {
const response = await fetch(`${GATEWAY_URL}/gateway/keys/regenerate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ user_id: user.id })
});
if (!response.ok) throw new Error('Regenerate failed');
const data = await response.json();
setApiKey(data.api_key);
localStorage.setItem(`opticparse_apikey_${user.id}`, data.api_key);
if (!silent) alert('API key regenerated successfully!');
} catch (err) {
if (!silent) alert('Failed to regenerate key: ' + err.message);
}
}
const navItems = [
{ id: 'dashboard', label: 'Dashboard', icon: Icons.dashboard },
{ id: 'keys', label: 'Settings', icon: Icons.key },
{ id: 'usage', label: 'Usage', icon: Icons.chart },
{ id: 'billing', label: 'Billing', icon: Icons.credit },
{ id: 'integrations', label: 'Integrations', icon: Icons.code },
{ id: 'extensions', label: 'Extensions', icon: Icons.code },
{ id: 'docs', label: 'API Docs', icon: Icons.code },
{ id: 'playground', label: 'Code Playground', icon: Icons.code },
]
const initial = user?.email?.charAt(0)?.toUpperCase() || '?'
return (
{/* Sidebar */}
{/* Main Content */}
{page === 'dashboard' && (
<>
OpticParse & PhishVision Dashboard
Welcome back. Here's your API overview.
>
)}
{page === 'keys' && (
<>
API Keys & Security
Manage your API authentication credentials and environments.
>
)}
{page === 'usage' && (
<>
Usage
Monitor your API consumption across services.
Remaining Calls
{Math.max(0, usage.monthly_limit - usage.current_usage).toLocaleString()}
>
)}
{page === 'billing' && (
<>
Billing
Manage your subscription and payment.
>
)}
{page === 'integrations' && (
<>
Integrations & Webhooks
Connect your APIs to external tools.
>
)}
{page === 'extensions' && (
<>
Experimental Features
Try out new tools in early access.
>
)}
{page === 'playground' && (
<>
Code Playground
Copy-paste ready integration snippets with your API key.
>
)}
{page === 'docs' && (
<>
API Documentation
Quick start guides for OpticParse and PhishVision.
Example 1 — OpticParse (cURL)
{`curl -X POST https://opticparse-python-sg.onrender.com/api/vision-scrape \\
-H "X-API-Key: ${apiKey || 'YOUR_API_KEY'}" \\
-H "Content-Type: application/json" \\
-d '{
"url": "https://example.com",
"query": "Extract main heading",
"response_schema": {"heading": "string"}
}'`}
Example 2 — PhishVision (cURL)
{`curl -X POST https://opticparse-1opticparse-node-sg.onrender.com/api/phish-detect \\
-H "Content-Type: application/json" \\
-d '{"url": "https://suspicious-site.com"}'`}
Example 3 — Python SDK style
{`import requests
response = requests.post(
"https://opticparse-python-sg.onrender.com/api/vision-scrape",
headers={"X-API-Key": "${apiKey || 'YOUR_API_KEY'}"},
json={
"url": "https://example.com",
"query": "Extract data",
"response_schema": {"data": "string"}
}
)
print(response.json())`}
>
)}
setIsFeedbackOpen(false)}
user={user}
/>
)
}