-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathApiUsage.tsx
More file actions
829 lines (761 loc) · 26.1 KB
/
Copy pathApiUsage.tsx
File metadata and controls
829 lines (761 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
import { useState, useEffect, useCallback } from 'react';
import EmptyState from './components/EmptyState';
import Skeleton, { SkeletonRow } from './components/Skeleton';
import { formatPrice } from './utils/format';
import type { JsonSchema } from './components/RequestBodyEditor';
import CallHistoryRow from './components/CallHistoryRow';
import Breadcrumb from './components/Breadcrumb';
import ParamsBuilder from './components/ParamsBuilder';
type ApiEndpoint = {
id: string;
name: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
path: string;
description: string;
/**
* Optional JSON Schema (Draft-07 subset) describing the expected request
* body for this endpoint. When present, RequestBodyEditor validates the
* user's JSON input against it in real time.
*/
requestBodySchema?: JsonSchema;
};
type CallRecord = {
id: string;
timestamp: Date;
endpoint: string;
status: 'success' | 'error';
responseTime: number;
cost: number;
request?: any;
response?: any;
};
type UsageStats = {
callsToday: number;
callsWeek: number;
totalSpent: number;
avgResponseTime: number;
successRate: number;
};
type DateRange = {
preset: '24h' | '7d' | '30d' | 'custom';
from?: Date;
to?: Date;
};
const MOCK_ENDPOINTS: ApiEndpoint[] = [
{
id: '1',
name: 'Get User Profile',
method: 'GET',
path: '/api/v1/user/profile',
description: 'Retrieve user profile information',
// GET endpoints typically have no request body; schema intentionally omitted.
},
{
id: '2',
name: 'Create Transaction',
method: 'POST',
path: '/api/v1/transactions',
description: 'Create a new transaction',
requestBodySchema: {
type: 'object',
required: ['amount', 'currency'],
properties: {
amount: {
type: 'number',
minimum: 0.01,
description: 'Transaction amount (positive, non-zero)',
},
currency: {
type: 'string',
enum: ['USD', 'EUR', 'GBP', 'USDC'],
description: 'ISO 4217 currency code or USDC',
},
recipient: {
type: 'string',
minLength: 1,
maxLength: 100,
description: 'Optional recipient identifier',
},
note: {
type: 'string',
maxLength: 255,
description: 'Optional transaction note',
},
},
},
},
{
id: '3',
name: 'Update Balance',
method: 'PUT',
path: '/api/v1/user/balance',
description: 'Update user balance',
requestBodySchema: {
type: 'object',
required: ['balance'],
properties: {
balance: {
type: 'number',
minimum: 0,
description: 'New balance value (must be non-negative)',
},
reason: {
type: 'string',
maxLength: 200,
description: 'Reason for the balance update',
},
},
},
},
];
const MOCK_CALL_HISTORY: CallRecord[] = [
{
id: '1',
timestamp: new Date(Date.now() - 1000 * 60 * 5),
endpoint: '/api/v1/user/profile',
status: 'success',
responseTime: 120,
cost: 0.001
},
{
id: '2',
timestamp: new Date(Date.now() - 1000 * 60 * 15),
endpoint: '/api/v1/transactions',
status: 'success',
responseTime: 250,
cost: 0.003
},
{
id: '3',
timestamp: new Date(Date.now() - 1000 * 60 * 30),
endpoint: '/api/v1/user/balance',
status: 'error',
responseTime: 5000,
cost: 0.001
}
];
const CODE_EXAMPLES = {
javascript: `// JavaScript/Node.js example
const apiKey = 'your-api-key-here';
const response = await fetch('https://api.callora.com/v1/user/profile', {
method: 'GET',
headers: {
'Authorization': \`Bearer \${apiKey}\`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log(data);`,
python: `# Python example
import requests
api_key = 'your-api-key-here'
response = requests.get(
'https://api.callora.com/v1/user/profile',
headers={
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
)
data = response.json()
print(data)`,
curl: `# cURL example
curl -X GET "https://api.callora.com/v1/user/profile" \\
-H "Authorization: Bearer your-api-key-here" \\
-H "Content-Type: application/json"`
};
function formatTime(ms: number) {
if (ms < 1000) return `${ms}ms`;
return `${(ms / 1000).toFixed(1)}s`;
}
function formatTimestamp(date: Date) {
return new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
export default function ApiUsage() {
const { trackFetch } = useFetchTracker();
const [apiKey, setApiKey] = useState('ck_live_4e85ff1ed6a4ff73893a0bf73f2bb');
const [isApiKeyVisible, setIsApiKeyVisible] = useState(false);
const [copied, setCopied] = useState(false);
const [selectedEndpoint, setSelectedEndpoint] = useState(MOCK_ENDPOINTS[0]);
const [requestParams, setRequestParams] = useState('{}');
const [isLoading, setIsLoading] = useState(false);
const [apiResponse, setApiResponse] = useState<any>(null);
const [responseTime, setResponseTime] = useState<number | null>(null);
const [callCost, setCallCost] = useState<number | null>(null);
const [statusFilter, setStatusFilter] = useState<'all' | 'success' | 'error'>('all');
const [filterResetMessage, setFilterResetMessage] = useState('');
const [callHistory, setCallHistory] = useState<CallRecord[]>(MOCK_CALL_HISTORY);
const [isTableLoading, setIsTableLoading] = useState(true);
useEffect(() => {
const timer = setTimeout(() => {
setIsTableLoading(false);
}, LOADING_DELAY_MS);
return () => clearTimeout(timer);
}, []);
const [selectedRange, setSelectedRange] = useState<DateRange>({ preset: '24h' });
const [selectedLanguage, setSelectedLanguage] = useState<'javascript' | 'python' | 'curl'>('javascript');
const [expandedCall, setExpandedCall] = useState<string | null>(null);
const [snapshotted, setSnapshotted] = useState(false);
// Restore endpoint params from snapshot URL on mount
useEffect(() => {
const snapshot = parseSnapshotUrl(window.location.search);
if (snapshot?.endpointId) {
const endpoint = MOCK_ENDPOINTS.find(ep => ep.id === snapshot.endpointId);
if (endpoint) {
setSelectedEndpoint(endpoint);
if (snapshot.params) {
setRequestParams(JSON.stringify(snapshot.params, null, 2));
}
}
}
}, []);
const handleShareSnapshot = async () => {
let parsedParams: Record<string, unknown> | null = null;
try {
parsedParams = JSON.parse(requestParams);
} catch {
// Invalid JSON, use null
}
const success = await copySnapshotUrl(window.location.pathname, {
endpointId: selectedEndpoint.id,
params: parsedParams,
});
if (success) {
setSnapshotted(true);
setTimeout(() => setSnapshotted(false), 2000);
}
};
// Filter call history based on selected date range
const filterCallsByRange = (calls: CallRecord[]): CallRecord[] => {
const now = new Date();
let from: Date | undefined;
let to: Date | undefined;
switch (selectedRange.preset) {
case '24h':
from = new Date(now.getTime() - 24 * 60 * 60 * 1000);
to = now;
break;
case '7d':
from = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
to = now;
break;
case '30d':
from = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
to = now;
break;
case 'custom':
from = selectedRange.from;
to = selectedRange.to;
break;
}
return calls.filter(call => {
const ts = call.timestamp;
if (from && ts < from) return false;
if (to && ts > to) return false;
return true;
});
};
const filteredCallHistory = filterCallsByRange(statusFilter === 'all' ? callHistory : callHistory.filter(call => call.status === statusFilter));
// Initialize selected range from URL query on mount
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const preset = params.get('range') as DateRange['preset'] | null;
const from = params.get('from');
const to = params.get('to');
if (preset && ['24h', '7d', '30d', 'custom'].includes(preset)) {
setSelectedRange({
preset,
...(preset === 'custom' && from && to ? { from: new Date(from), to: new Date(to) } : {}),
});
}
}, []);
// Sync selected range to URL query whenever it changes
useEffect(() => {
const params = new URLSearchParams();
if (selectedRange.preset !== '24h') {
params.set('range', selectedRange.preset);
if (selectedRange.preset === 'custom' && selectedRange.from && selectedRange.to) {
params.set('from', selectedRange.from.toISOString());
params.set('to', selectedRange.to.toISOString());
}
}
const newUrl = `${window.location.pathname}?${params.toString()}`;
window.history.replaceState(null, '', newUrl);
}, [selectedRange]);
const { usagePercent, isDismissed, dismiss } = useQuota(MOCK_USAGE_PERCENT);
const [usageStats, setUsageStats] = useState<UsageStats>({
callsToday: 47,
callsWeek: 312,
totalSpent: 2.847,
avgResponseTime: 180,
successRate: 94.2
});
// Whether any call-history filter differs from its default value.
const filtersAreActive = statusFilter !== 'all' || selectedRange.preset !== '24h';
// Reset all call-history filters to their defaults and announce the change
// to assistive technology via the aria-live region below.
const handleResetFilters = () => {
setStatusFilter('all');
setSelectedRange({ preset: '24h' });
setFilterResetMessage('Filters reset. Showing all calls from the last 24 hours.');
};
const handleCopyApiKey = async () => {
try {
await navigator.clipboard.writeText(apiKey);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy API key');
}
};
const handleRegenerateApiKey = () => {
const newKey = 'ck_live_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
setApiKey(newKey);
};
const handleMakeTestCall = async () => {
// Guard: do not submit when the request body has a JSON syntax error.
// (Schema constraint violations are warnings — we allow submission but
// still show the error to inform the user.)
const trimmed = requestParams.trim();
if (trimmed !== '' && trimmed !== '{}') {
try {
JSON.parse(requestParams);
} catch {
return; // Textarea will already show the syntax error inline.
}
}
setIsLoading(true);
setApiResponse(null);
setResponseTime(null);
setCallCost(null);
const startTime = Date.now();
await trackFetch(new Promise<void>((resolve) => {
setTimeout(() => {
const endTime = Date.now();
const time = endTime - startTime;
const cost = Math.random() * 0.005 + 0.001;
setResponseTime(time);
setCallCost(cost);
const mockResponse = {
success: true,
data: {
id: 'user_123',
name: 'John Doe',
email: 'john@example.com',
balance: 1250.50,
created_at: new Date().toISOString()
},
timestamp: new Date().toISOString()
};
setApiResponse(mockResponse);
const newCall: CallRecord = {
id: Date.now().toString(),
timestamp: new Date(),
endpoint: selectedEndpoint.path,
status: 'success',
responseTime: time,
cost: cost,
request: requestParams,
response: mockResponse
};
setCallHistory(prev => [newCall, ...prev]);
const historyEntry: HistoryEntry = {
id: newCall.id,
timestamp: newCall.timestamp.toISOString(),
endpointId: selectedEndpoint.id,
endpointName: selectedEndpoint.name,
endpointPath: selectedEndpoint.path,
method: selectedEndpoint.method,
requestParams: requestParams,
response: mockResponse,
status: "success",
responseTime: time,
cost: cost,
};
saveEntry(historyEntry);
setHistoryEntries(loadHistory());
setUsageStats(prev => ({
...prev,
callsToday: prev.callsToday + 1,
callsWeek: prev.callsWeek + 1,
totalSpent: prev.totalSpent + cost,
avgResponseTime: (prev.avgResponseTime * prev.callsToday + time) / (prev.callsToday + 1)
}));
setIsLoading(false);
resolve();
}, 1000 + Math.random() * 2000);
}));
};
const handleHistorySelect = useCallback((entry: HistoryEntry) => {
setSelectedEndpoint(
MOCK_ENDPOINTS.find((ep) => ep.id === entry.endpointId) ?? MOCK_ENDPOINTS[0],
);
setRequestParams(entry.requestParams);
setApiResponse(entry.response);
setResponseTime(entry.responseTime);
setCallCost(entry.cost);
toggleHistory();
}, [toggleHistory]);
const handleClearHistory = useCallback(() => {
clearHistory();
setHistoryEntries([]);
}, []);
const handleCopyCode = async (code: string) => {
try {
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy code');
}
};
const handleExportHistory = (format: 'csv' | 'json') => {
const data = callHistory.map(call => ({
timestamp: call.timestamp.toISOString(),
endpoint: call.endpoint,
status: call.status,
responseTime: call.responseTime,
cost: call.cost
}));
if (format === 'json') {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'call-history.json';
a.click();
} else {
const csv = [
'Timestamp,Endpoint,Status,Response Time,Cost',
...data.map(call =>
`${call.timestamp},${call.endpoint},${call.status},${call.responseTime},${call.cost}`
)
].join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'call-history.csv';
a.click();
}
};
return (
<div className="api-usage-page">
<Breadcrumb
items={[
{ label: 'Marketplace', href: '/marketplace' },
{
label: 'User Profile API usage',
href: '/api-usage',
isCurrent: true,
},
]}
/>
{!isDismissed && (
<PlanNudge usagePercent={usagePercent} onDismiss={dismiss} />
)}
{/* Header Section */}
<div className="api-header">
<div className="api-header-info">
<div className="api-logo">
<div className="logo-placeholder">API</div>
</div>
<div>
<h1>User Profile API</h1>
<p className="api-description">Manage user profiles and authentication</p>
</div>
</div>
<div className="api-header-actions">
<button className="secondary-button" onClick={() => window.history.back()}>
← Back to API Details
</button>
<button
className="secondary-button"
onClick={toggleHistory}
aria-label={isHistoryOpen ? "Close request history" : "Open request history"}
aria-expanded={isHistoryOpen}
>
<Icons.History size={16} style={{ marginRight: 6 }} />
History
</button>
<div className="status-indicator active">
<span className="status-dot"></span>
API is Active
</div>
</div>
</div>
{/* API Key Section */}
<div className="surface api-key-section">
<h2>API Key</h2>
<div className="api-key-card">
<div className="api-key-display">
<div className="key-input-group">
<input
type={isApiKeyVisible ? 'text' : 'password'}
value={apiKey}
readOnly
className="api-key-input"
/>
<button
className="ghost-button"
onClick={() => setIsApiKeyVisible(!isApiKeyVisible)}
>
{isApiKeyVisible ? 'Hide' : 'Show'}
</button>
</div>
<div className="key-actions">
<button className="secondary-button" onClick={handleCopyApiKey}>
{copied ? 'Copied!' : 'Copy'}
</button>
<button className="danger-button" onClick={handleRegenerateApiKey}>
Regenerate
</button>
</div>
</div>
<p className="usage-instruction">
Include this key in your requests as a Bearer token in the Authorization header.
</p>
</div>
</div>
{/* Test API Call Section */}
<div className="surface test-call-section">
<h2>Test API Call</h2>
<div className="test-call-form">
<div className="form-row">
<label>Endpoint</label>
<select
value={selectedEndpoint.id}
onChange={(e) => {
const endpoint = MOCK_ENDPOINTS.find(ep => ep.id === e.target.value);
if (endpoint) {
setSelectedEndpoint(endpoint);
// Reset the request body when switching endpoints so stale
// JSON from a previous endpoint doesn't fail the new schema.
setRequestParams('{}');
}
}}
className="endpoint-select"
>
{MOCK_ENDPOINTS.map(endpoint => (
<option key={endpoint.id} value={endpoint.id}>
{endpoint.method} {endpoint.path} - {endpoint.name}
</option>
))}
</select>
</div>
<div className="form-row">
<ParamsBuilder
value={requestParams}
onChange={setRequestParams}
disabled={isLoading}
label="Parameters"
/>
</div>
<button
className={`primary-button ${isLoading ? 'button-loading' : ''}`}
onClick={handleMakeTestCall}
disabled={isLoading}
>
{isLoading && <span className="button-spinner" aria-hidden="true" />}
{isLoading ? 'Making Call...' : 'Make Test Call'}
</button>
<button
className="secondary-button share-snapshot-button"
onClick={handleShareSnapshot}
disabled={isLoading}
aria-label="Share snapshot URL"
>
<LinkIcon size={16} />
{snapshotted ? 'Copied!' : 'Share Snapshot'}
</button>
</div>
{(apiResponse || isLoading) && (
<div
className="response-display"
aria-live="polite"
aria-busy={isLoading}
>
<h3>Response</h3>
{isLoading ? (
<div className="response-content">
<div className="response-meta">
<Skeleton width="120px" height="18px" borderRadius="4px" />
<Skeleton width="100px" height="18px" borderRadius="4px" />
</div>
<div className="response-json-skeleton">
<Skeleton width="60%" height="16px" borderRadius="4px" />
<Skeleton width="80%" height="16px" borderRadius="4px" />
<Skeleton width="45%" height="16px" borderRadius="4px" />
<Skeleton width="70%" height="16px" borderRadius="4px" />
<Skeleton width="30%" height="16px" borderRadius="4px" />
</div>
</div>
) : (
<div className="response-content">
<div className="response-meta">
<span className="response-time">Response time: {formatTime(responseTime || 0)}</span>
<span className="response-cost">Cost: {formatPrice(callCost || 0)} USDC</span>
</div>
<pre className="response-json">
{JSON.stringify(apiResponse, null, 2)}
</pre>
</div>
)}
</div>
)}
</div>
{/* Usage Statistics */}
<div className="surface usage-stats-section">
<h2>Usage Statistics</h2>
<div className="stats-grid">
<div className="stat-card">
<span className="stat-label">Calls Today</span>
<strong className="stat-value">{usageStats.callsToday}</strong>
</div>
<div className="stat-card">
<span className="stat-label">Calls This Week</span>
<strong className="stat-value">{usageStats.callsWeek}</strong>
</div>
<div className="stat-card">
<span className="stat-label">Total Spent</span>
<strong className="stat-value">{formatPrice(usageStats.totalSpent)} USDC</strong>
</div>
<div className="stat-card">
<span className="stat-label">Avg Response Time</span>
<strong className="stat-value">{formatTime(usageStats.avgResponseTime)}</strong>
</div>
<div className="stat-card">
<span className="stat-label">Success Rate</span>
<strong className="stat-value">{usageStats.successRate}%</strong>
</div>
</div>
<div className="mini-chart">
<h3>Calls Over Time</h3>
<CallsHeatmap />
<div className="chart-placeholder" style={{ marginTop: '24px' }}>
{/* Simple bar chart visualization */}
<div className="chart-bars">
{[65, 59, 80, 81, 56, 55, 47].map((height, i) => (
<div key={i} className="chart-bar" style={{ height: `${height}%` }}></div>
))}
</div>
<div className="chart-labels">
<span>Mon</span>
<span>Tue</span>
<span>Wed</span>
<span>Thu</span>
<span>Fri</span>
<span>Sat</span>
<span>Sun</span>
</div>
</div>
</div>
</div>
{/* Call History */}
<div className="surface call-history-section">
<div className="section-header">
<h2>Call History</h2>
<div className="history-actions">
<Tabs
tabs={[
{ id: 'all', label: 'All Status' },
{ id: 'success', label: 'Success' },
{ id: 'error', label: 'Error' },
]}
activeTab={statusFilter}
onChange={(id) => {
setStatusFilter(id as 'all' | 'success' | 'error');
setFilterResetMessage('');
}}
/>
<button
type="button"
className="secondary-button"
onClick={handleResetFilters}
disabled={!filtersAreActive}
>
Reset Filters
</button>
<button className="secondary-button" onClick={() => handleExportHistory('csv')}>
Export CSV
</button>
<button className="secondary-button" onClick={() => handleExportHistory('json')}>
Export JSON
</button>
</div>
</div>
{/* Screen-reader announcement for filter reset (WCAG 2.1 AA) */}
<p className="sr-only" role="status" aria-live="polite">
{filterResetMessage}
</p>
<div className="call-history-table" aria-busy={isLoading}>
<div className="table-header">
<span>Timestamp</span>
<span>Endpoint</span>
<span>Status</span>
<span>Response Time</span>
<span>Cost</span>
<span>Actions</span>
</div>
{isTableLoading ? (
<SkeletonRow rows={5} />
) : filteredCallHistory.length === 0 ? (
<EmptyState message="No call records match the selected filter." />
) : (
filteredCallHistory.map(call => (
<CallHistoryRow
key={call.id}
call={call}
expanded={expandedCall === call.id}
onToggleExpand={id => setExpandedCall(expandedCall === id ? null : id)}
/>
))
)}
</div>
</div>
{/* Integration Guide */}
<div className="surface integration-guide-section">
<h2>Integration Guide</h2>
<div className="language-tabs">
{(['javascript', 'python', 'curl'] as const).map(lang => (
<button
key={lang}
className={`tab-button ${selectedLanguage === lang ? 'active' : ''}`}
onClick={() => setSelectedLanguage(lang)}
>
{lang.charAt(0).toUpperCase() + lang.slice(1)}
</button>
))}
</div>
<div className="code-example">
<div className="code-header">
<h3>{selectedLanguage.charAt(0).toUpperCase() + selectedLanguage.slice(1)} Example</h3>
<button
className="secondary-button"
onClick={() => handleCopyCode(CODE_EXAMPLES[selectedLanguage])}
>
{copied ? 'Copied!' : 'Copy Code'}
</button>
</div>
<pre className="code-block">
<code>{CODE_EXAMPLES[selectedLanguage]}</code>
</pre>
</div>
<div className="documentation-link">
<a href="#" className="primary-button">View Full Documentation →</a>
</div>
</div>
<RequestHistoryPanel
entries={historyEntries}
isOpen={isHistoryOpen}
onClose={toggleHistory}
onSelect={handleHistorySelect}
onClear={handleClearHistory}
/>
</div>
);
}