-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
523 lines (476 loc) · 16.3 KB
/
App.tsx
File metadata and controls
523 lines (476 loc) · 16.3 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
import React, { useState, useEffect } from 'react';
import InputForm from './components/InputForm';
import Dashboard from './components/Dashboard';
import QuestionDetail from './components/QuestionDetail';
import LandingPage from './components/LandingPage';
import Login from './components/Auth/Login';
import Signup from './components/Auth/Signup';
import ForgotPassword from './components/Auth/ForgotPassword';
import GetSolution from './components/GetSolution';
import AdminPanel from './components/AdminPanel';
import UsageDisplay from './components/UsageDisplay';
import Pricing from './components/Pricing';
import { PolicyPage } from './components/Policies';
import { API_BASE_URL } from './config/api';
import {
SubmissionData,
SavedQuestion,
ViewState,
UserSettings,
} from './types';
import { analyzeSubmission } from './services/aiService';
import {
LayoutDashboard,
PlusCircle,
AlertCircle,
LogOut,
Sparkles,
DollarSign,
ArrowLeft,
} from 'lucide-react';
import AppLogo from './components/Logo-With-Name cropped.png';
const App: React.FC = () => {
// --- State ---
const [token, setToken] = useState<string | null>(
localStorage.getItem('token')
);
const [user, setUser] = useState<any>(null);
const [authView, setAuthView] = useState<
'login' | 'signup' | 'forgot-password'
>('login');
const [showLanding, setShowLanding] = useState<boolean>(!token);
const [showAdmin, setShowAdmin] = useState<boolean>(false);
const [policyView, setPolicyView] = useState<string | null>(null);
// Check for policy routes on mount
useEffect(() => {
const path = window.location.pathname;
const routes: Record<string, string> = {
'/privacy': 'privacy',
'/privacy-policy': 'privacy',
'/terms': 'terms',
'/terms-and-conditions': 'terms',
'/refunds': 'refunds',
'/cancellation-refund-policy': 'refunds',
'/shipping': 'shipping',
'/shipping-policy': 'shipping',
'/contact': 'contact',
'/contact-us': 'contact',
};
// Check exact match or without trailing slash
const view = routes[path] || routes[path.replace(/\/$/, '')];
if (view) {
setPolicyView(view);
setShowLanding(false);
}
}, []);
// Check for admin route on mount and hash change
useEffect(() => {
const checkAdminRoute = () => {
setShowAdmin(window.location.hash === '#admin');
};
checkAdminRoute();
window.addEventListener('hashchange', checkAdminRoute);
return () => window.removeEventListener('hashchange', checkAdminRoute);
}, []);
// Handle OAuth callback (GitHub redirect with token in URL)
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const urlToken = params.get('token');
const urlUser = params.get('user');
if (urlToken && urlUser) {
try {
const parsedUser = JSON.parse(decodeURIComponent(urlUser));
localStorage.setItem('token', urlToken);
setToken(urlToken);
setUser(parsedUser);
setShowLanding(false);
// Clean up URL
window.history.replaceState(
{},
document.title,
window.location.pathname
);
} catch (err) {
console.error('[OAuth] Failed to parse user data:', err);
}
}
}, []);
const [questions, setQuestions] = useState<SavedQuestion[]>([]);
const [userSettings, setUserSettings] = useState<UserSettings>(() => {
const saved = localStorage.getItem('leetcode-revision-settings');
const defaults = {
showEdgeCases: true,
showSyntaxNotes: true,
showTestCases: true,
};
return saved ? { ...defaults, ...JSON.parse(saved) } : defaults;
});
const [view, setView] = useState<ViewState>('dashboard');
const [selectedQuestionId, setSelectedQuestionId] = useState<string | null>(
null
);
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [error, setError] = useState<string | null>(null);
// --- Effects ---
useEffect(() => {
if (token) {
fetchQuestions();
setShowLanding(false);
} else {
setShowLanding(true);
}
}, [token]);
useEffect(() => {
localStorage.setItem(
'leetcode-revision-settings',
JSON.stringify(userSettings)
);
}, [userSettings]);
// Listen for navigation to pricing from UsageDisplay
useEffect(() => {
const handlePricingNav = () => setView('pricing');
window.addEventListener('navigate-to-pricing', handlePricingNav);
return () =>
window.removeEventListener('navigate-to-pricing', handlePricingNav);
}, []);
const fetchQuestions = async () => {
try {
const res = await fetch(`${API_BASE_URL}/api/questions`, {
headers: { 'x-auth-token': token! },
});
const data = await res.json();
if (res.ok) {
// Map _id to id
const mappedQuestions = data.map((q: any) => ({ ...q, id: q._id }));
setQuestions(mappedQuestions);
}
} catch (err) {
console.error('Failed to fetch questions', err);
}
};
// --- Handlers ---
const handleLogin = (newToken: string, newUser: any) => {
localStorage.setItem('token', newToken);
setToken(newToken);
setUser(newUser);
};
const handleLogout = () => {
localStorage.removeItem('token');
setToken(null);
setUser(null);
setQuestions([]);
setShowLanding(true);
};
const handleAddNew = async (data: SubmissionData) => {
setIsAnalyzing(true);
setError(null);
try {
const analysis = await analyzeSubmission(data);
const newQuestionData = {
...data,
...analysis,
title: analysis.title || 'Untitled Problem',
language: analysis.language || 'Unknown Language',
};
// Save to DB
const res = await fetch(`${API_BASE_URL}/api/questions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-auth-token': token!,
},
body: JSON.stringify(newQuestionData),
});
const savedQuestion = await res.json();
if (!res.ok) throw new Error(savedQuestion.message || 'Failed to save');
setQuestions((prev) => [
{ ...savedQuestion, id: savedQuestion._id },
...prev,
]);
setSelectedQuestionId(savedQuestion._id);
setView('detail');
} catch (err: any) {
setError(err.message || 'Failed to analyze submission');
} finally {
setIsAnalyzing(false);
}
};
const handleGetStarted = () => {
setShowLanding(false);
// If not logged in, show login
if (!token) {
setAuthView('login');
}
};
const handleDelete = async (id: string) => {
try {
await fetch(`${API_BASE_URL}/api/questions/${id}`, {
method: 'DELETE',
headers: { 'x-auth-token': token! },
});
setQuestions((prev) => prev.filter((q) => q.id !== id));
if (selectedQuestionId === id) {
setSelectedQuestionId(null);
setView('dashboard');
}
} catch (err) {
console.error('Failed to delete', err);
}
};
const handleUpdateQuestion = (updatedQuestion: SavedQuestion) => {
setQuestions((prev) =>
prev.map((q) => (q.id === updatedQuestion.id ? updatedQuestion : q))
);
};
const renderContent = () => {
if (showAdmin) {
return (
<AdminPanel
onBack={() => {
window.location.hash = '';
setShowAdmin(false);
}}
/>
);
}
if (policyView) {
return (
<PolicyPage
type={policyView}
onHome={() => {
setPolicyView(null);
window.location.href = '/';
}}
/>
);
}
if (showLanding && !token) {
return <LandingPage onGetStarted={handleGetStarted} />;
}
if (!token) {
if (authView === 'login') {
return (
<Login
onLogin={handleLogin}
onSwitchToSignup={() => setAuthView('signup')}
onForgotPassword={() => setAuthView('forgot-password')}
/>
);
} else if (authView === 'signup') {
return (
<Signup
onSignup={handleLogin}
onSwitchToLogin={() => setAuthView('login')}
/>
);
} else if (authView === 'forgot-password') {
return (
<ForgotPassword
onBack={() => setAuthView('login')}
onLogin={() => setAuthView('login')}
/>
);
}
}
if (view === 'add') {
return (
<div className="max-w-3xl mx-auto animate-in fade-in slide-in-from-bottom-2">
<div className="mb-6">
<h2 className="text-2xl font-bold text-white flex items-center gap-2">
<PlusCircle className="w-6 h-6 text-yellow-500" />
Add New Solution
</h2>
<p className="text-gray-400 text-sm mt-1">
Paste your code. We will auto-detect the problem and extract
patterns.
</p>
</div>
{error && (
<div className="mb-6 p-4 bg-red-900/20 border border-red-800/50 rounded-lg text-red-200 flex items-center gap-2">
<AlertCircle className="w-5 h-5" />
{error}
</div>
)}
<InputForm onSubmit={handleAddNew} isLoading={isAnalyzing} />
</div>
);
}
if (view === 'detail' && selectedQuestionId) {
const question = questions.find((q) => q.id === selectedQuestionId);
if (!question) return <div>Question not found</div>;
return (
<QuestionDetail
question={question}
userSettings={userSettings}
onUpdateSettings={setUserSettings}
onBack={() => setView('dashboard')}
onDelete={handleDelete}
onUpdateQuestion={handleUpdateQuestion}
isPro={user?.plan === 'pro' || user?.role === 'admin'}
onUpgrade={() => setView('pricing')}
/>
);
}
if (view === 'solution') {
return <GetSolution />;
}
if (view === 'pricing') {
return <Pricing />;
}
return (
<Dashboard
questions={questions}
onSelectQuestion={(q) => {
setSelectedQuestionId(q.id);
setView('detail');
}}
onAddNew={() => setView('add')}
onShowPricing={() => setView('pricing')}
/>
);
};
return (
<div className="flex h-screen bg-[#0c0c0c] text-gray-100 font-sans overflow-hidden">
{showAdmin ? (
<div className="w-full h-full overflow-y-auto">
<AdminPanel
onBack={() => {
window.location.hash = '';
setShowAdmin(false);
}}
/>
</div>
) : policyView ? (
<div className="w-full h-full overflow-y-auto">{renderContent()}</div>
) : (!token && showLanding) || !token ? (
<div className="w-full h-full overflow-y-auto">{renderContent()}</div>
) : view === 'pricing' ? (
<div className="w-full h-full overflow-y-auto bg-[#0c0c0c]">
<div className="max-w-6xl mx-auto px-4 sm:px-8 py-8">
<button
onClick={() => setView('dashboard')}
aria-label="Back to app"
className="mb-8 inline-flex items-center text-gray-400 hover:text-yellow-400 transition-colors"
>
<ArrowLeft className="w-7 h-7" />
</button>
<Pricing />
</div>
</div>
) : (
<>
{/* Sidebar */}
<aside className="w-64 bg-[#0e0e0e] border-r border-gray-800 flex flex-col hidden md:flex shrink-0">
<div className="p-6 border-b border-gray-800 flex items-center gap-3">
<div className="h-10 rounded-lg overflow-hidden">
<img
src={AppLogo}
alt="ReCode"
className="h-full w-auto object-contain"
/>
</div>
</div>
<nav className="flex-1 p-4 space-y-2">
<button
onClick={() => setView('dashboard')}
className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 text-sm font-medium tracking-wide ${
view === 'dashboard' || view === 'detail'
? 'bg-yellow-500/10 text-yellow-400 border-l-2 border-yellow-500'
: 'text-gray-400 hover:bg-gray-800 hover:text-white hover:pl-5'
}`}
>
<LayoutDashboard className="w-5 h-5" />
Dashboard
</button>
<button
onClick={() => setView('add')}
className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 text-sm font-medium tracking-wide ${
view === 'add'
? 'bg-yellow-500/10 text-yellow-400 border-l-2 border-yellow-500'
: 'text-gray-400 hover:bg-gray-800 hover:text-white hover:pl-5'
}`}
>
<PlusCircle className="w-5 h-5" />
Add Solution
</button>
<button
onClick={() => setView('solution')}
className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 text-sm font-medium tracking-wide ${
view === 'solution'
? 'bg-yellow-500/10 text-yellow-400 border-l-2 border-yellow-500'
: 'text-gray-400 hover:bg-gray-800 hover:text-white hover:pl-5'
}`}
>
<Sparkles className="w-5 h-5" />
Get Solution
</button>
</nav>
<div className="p-6 border-t border-gray-800 space-y-4">
<div className="bg-gray-950 p-4 rounded-lg border border-gray-800">
<div className="text-xs text-gray-500 mb-1">
Total Questions
</div>
<div className="text-2xl font-bold text-white">
{questions.length}
</div>
</div>
{/* Usage Display */}
<UsageDisplay />
<button
onClick={handleLogout}
className="w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-sm font-medium text-red-400 hover:bg-red-900/20"
>
<LogOut className="w-5 h-5" />
Sign Out
</button>
</div>
</aside>
{/* Main Content */}
<main className="flex-1 overflow-y-auto relative">
{/* Mobile Header */}
<div className="md:hidden p-4 border-b border-gray-800 flex items-center justify-between sticky top-0 bg-[#0b0f19]/90 backdrop-blur-md z-20">
<div className="h-8 rounded-lg overflow-hidden">
<img
src={AppLogo}
alt="ReCode"
className="h-full w-auto object-contain"
/>
</div>
<div className="flex gap-2">
<button
onClick={() => setView('dashboard')}
className={`p-2 rounded-md ${view === 'dashboard' ? 'bg-yellow-500/20 text-yellow-400' : 'bg-gray-800'}`}
>
<LayoutDashboard className="w-5 h-5" />
</button>
<button
onClick={() => setView('add')}
className={`p-2 rounded-md ${view === 'add' ? 'bg-yellow-500/20 text-yellow-400' : 'bg-gray-800'}`}
>
<PlusCircle className="w-5 h-5" />
</button>
<button
onClick={() => setView('solution')}
className={`p-2 rounded-md ${view === 'solution' ? 'bg-yellow-500/20 text-yellow-400' : 'bg-gray-800'}`}
>
<Sparkles className="w-5 h-5" />
</button>
<button
onClick={handleLogout}
className="p-2 rounded-md bg-gray-800 text-red-400 hover:bg-red-900/30"
>
<LogOut className="w-5 h-5" />
</button>
</div>
</div>
{/* Content Area */}
<div className="max-w-6xl mx-auto px-4 sm:px-8 py-8 md:py-12">
{renderContent()}
</div>
</main>
</>
)}
</div>
);
};
export default App;