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'; export default function CodePlayground({ apiKey }) { const [tab, setTab] = useState('python') const key = apiKey || 'YOUR_API_KEY' // Local Mode State const [isLocalMode, setIsLocalMode] = useState(false) const [localProgress, setLocalProgress] = useState('') const [isModelLoaded, setIsModelLoaded] = useState(false) const [isInitializing, setIsInitializing] = useState(false) // Interactive Run State const [testPrompt, setTestPrompt] = useState('Extract main headings from this text...') const [testImage, setTestImage] = useState('') // Optional image URL or base64 const [result, setResult] = useState('') const [isRunning, setIsRunning] = useState(false) const snippets = { python: `import requests response = requests.post( "https://your-gateway.com/api/vision-scrape", headers={"X-API-Key": "${key}"}, json={ "target_url": "https://example.com", "extraction_query": "Extract all product names and prices as JSON" } ) print(response.json())`, node: `const axios = require('axios'); const response = await axios.post( 'https://your-gateway.com/api/vision-scrape', { target_url: 'https://example.com', extraction_query: 'Extract all product names and prices as JSON' }, { headers: { 'X-API-Key': '${key}' } } ); console.log(response.data);`, curl: `curl -X POST https://your-gateway.com/api/vision-scrape \\ -H "Content-Type: application/json" \\ -H "X-API-Key: ${key}" \\ -d '{ "target_url": "https://example.com", "extraction_query": "Extract all product names and prices as JSON" }'`, } const copySnippet = () => { navigator.clipboard.writeText(snippets[tab]) } const handleToggleLocal = async (e) => { const checked = e.target.checked; setIsLocalMode(checked); if (checked && !isModelLoaded) { setIsInitializing(true); try { await initLocalEngine((progress) => { setLocalProgress(progress.text); }); setIsModelLoaded(true); setLocalProgress('Model loaded successfully!'); } catch (err) { if (err.message === "WEBGPU_UNSUPPORTED") { setLocalProgress('WebGPU unsupported by your browser. Falling back to cloud API...'); } else { setLocalProgress('Failed to load local model.'); console.error(err); } setIsLocalMode(false); } finally { setIsInitializing(false); } } } const handleRun = async () => { setIsRunning(true); setResult('Running...'); try { const payload = testImage ? { prompt: testPrompt, image: testImage } : testPrompt; const res = await routeInference(payload, isLocalMode, GATEWAY_URL, key); setResult(JSON.stringify(res, null, 2)); } catch (err) { setResult('Error: ' + err.message); } finally { setIsRunning(false); } } return (