forked from codechefPesuecc/CodeChef-PESUECC-Chapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArenaWorkspace.tsx
More file actions
1532 lines (1455 loc) · 50.5 KB
/
Copy pathArenaWorkspace.tsx
File metadata and controls
1532 lines (1455 loc) · 50.5 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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import {
useCallback,
useEffect,
useRef,
useState,
type CSSProperties,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import CodeEditor from "./CodeEditor";
import {
LANGUAGES,
STARTER_CODE,
formatClock,
languageLabel,
type LanguageId,
} from "./mockData";
import { BASE_POINTS, BOUNTY_LADDER, ordinal } from "@/lib/points";
import { FLAG_LIMIT, useIntegrityMonitor } from "./useIntegrityMonitor";
import { useUser } from "@/components/auth/useUser";
import LeaderboardTable, { type LeaderRow } from "./LeaderboardTable";
import Turnstile, { turnstileConfigured } from "./Turnstile";
import MechaPanel from "./MechaPanel";
import Link from "next/link";
const FILE_EXT: Record<LanguageId, string> = {
cpp: "cpp",
c: "c",
python: "py",
java: "java",
csharp: "cs",
javascript: "js",
go: "go",
rust: "rs",
zig: "zig",
};
// Draggable split between the problem and the editor (desktop only). Stored as
// the problem pane's width in percent; clamped so neither side collapses.
const SPLIT_KEY = "cp-arena:split-pct";
const SPLIT_MIN = 25;
const SPLIT_MAX = 75;
const SPLIT_STEP = 2; // keyboard nudge per arrow press
const clampSplit = (n: number) => Math.min(SPLIT_MAX, Math.max(SPLIT_MIN, n));
type Verdict = "AC" | "WA" | "TLE" | "MLE" | "RE" | "CE";
type Judgement = {
mode: "run" | "submit";
// RAN = ran on custom input; CE = compile error; TLE/RE = runtime; ERR = infra
status: Verdict | "RAN" | "ERR";
input?: string;
output?: string; // real stdout from Piston (run mode)
stderr?: string; // compiler output (CE) or program stderr (RE)
message?: string; // error / info text
passed?: number; // submit: tests passed before failure
total?: number; // submit: total tests
failedOn?: number; // submit: 1-based failing test index
warning?: string; // soft warning (e.g. persist failure on an AC)
} | null;
interface Submission {
id: number;
language: string;
status: Verdict;
clock: string;
detail: string;
}
export default function ArenaWorkspace({
slug,
problem,
sampleInput,
sampleOutput,
practice = false,
}: {
slug: string;
problem: ReactNode;
sampleInput: string;
sampleOutput: string;
/** Past-problem practice mode: no proctoring, no ranked board or points. */
practice?: boolean;
}) {
const codeKey = (lang: LanguageId) => `cp-arena:code:${slug}:${lang}`;
const loadCode = (lang: LanguageId) => {
if (typeof window === "undefined") return STARTER_CODE[lang];
try {
return localStorage.getItem(codeKey(lang)) ?? STARTER_CODE[lang];
} catch {
return STARTER_CODE[lang];
}
};
const user = useUser();
const [language, setLanguage] = useState<LanguageId>("cpp");
const [code, setCode] = useState<string>(() => loadCode("cpp"));
const [customInput, setCustomInput] = useState(sampleInput);
const [running, setRunning] = useState(false);
const [judgement, setJudgement] = useState<Judgement>(null);
const [history, setHistory] = useState<Submission[]>([]);
const [elapsed, setElapsed] = useState(0);
const [mySolveSeconds, setMySolveSeconds] = useState<number | null>(null);
const [myFlags, setMyFlags] = useState(0);
const [myRank, setMyRank] = useState<number | null>(null);
const [myPoints, setMyPoints] = useState<number | null>(null);
const [myFlaggedSolve, setMyFlaggedSolve] = useState(false);
const [board, setBoard] = useState<LeaderRow[] | null>(null);
const [pageFocused, setPageFocused] = useState(true);
const [busyLabel, setBusyLabel] = useState("Running…");
const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
const [turnstileNonce, setTurnstileNonce] = useState(0);
// Layout: draggable problem/editor split + maximized editor.
const [splitPct, setSplitPct] = useState(50);
const [editorFullscreen, setEditorFullscreen] = useState(false);
const startRef = useRef<number | null>(null);
const frozenRef = useRef(false);
const splitContainerRef = useRef<HTMLDivElement>(null);
// Live "your time" clock. Seeded to now, then corrected to the server-recorded
// first-open time (below) so it survives reloads. Freezes on an accepted solve.
useEffect(() => {
if (startRef.current == null) startRef.current = Date.now();
const id = setInterval(() => {
if (!frozenRef.current && startRef.current != null) {
setElapsed(Math.max(0, Math.floor((Date.now() - startRef.current) / 1000)));
}
}, 1000);
return () => clearInterval(id);
}, []);
// Ranked POTD: record the first-open time (server-authoritative and immutable)
// and seed the clock from it, so "your time" reads the same after a refresh or
// on another device. Practice problems keep the local-only timer above.
useEffect(() => {
if (practice || !user) return;
let cancelled = false;
(async () => {
try {
const res = await fetch("/api/attempt/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ slug }),
});
const data = await res.json();
if (!cancelled && data?.ok && data.ranked && typeof data.startedAt === "number") {
startRef.current = data.startedAt;
if (!frozenRef.current) {
setElapsed(Math.max(0, Math.floor((Date.now() - data.startedAt) / 1000)));
}
}
} catch {
// Best-effort — the local timer still ticks if the beacon fails.
}
})();
return () => {
cancelled = true;
};
}, [practice, slug, user]);
const solved = mySolveSeconds != null;
// No proctoring on practice (past) problems — they aren't ranked.
const integrity = useIntegrityMonitor(!solved && !practice);
// Live today leaderboard from the DB (refetched after an accepted submit).
const fetchBoardRows = useCallback(async (): Promise<LeaderRow[]> => {
try {
const res = await fetch("/api/leaderboard?scope=today");
const data = await res.json();
return (data.rows ?? []) as LeaderRow[];
} catch {
return [];
}
}, []);
useEffect(() => {
if (practice) return; // practice pages don't show the ranked today board
fetchBoardRows().then((rows) => setBoard(rows));
}, [fetchBoardRows, practice]);
// Blur the problem when the window/tab loses focus — a screenshot deterrent
// (e.g. the OS snip overlay steals focus, so it captures a blurred panel).
useEffect(() => {
const focus = () => setPageFocused(true);
const blur = () => setPageFocused(false);
const visibility = () =>
setPageFocused(document.visibilityState === "visible");
window.addEventListener("focus", focus);
window.addEventListener("blur", blur);
document.addEventListener("visibilitychange", visibility);
return () => {
window.removeEventListener("focus", focus);
window.removeEventListener("blur", blur);
document.removeEventListener("visibilitychange", visibility);
};
}, []);
// Autosave the draft per problem + language so a refresh doesn't lose work.
useEffect(() => {
const id = setTimeout(() => {
try {
localStorage.setItem(`cp-arena:code:${slug}:${language}`, code);
} catch {}
}, 400);
return () => clearTimeout(id);
}, [code, language, slug]);
// Restore the saved problem/editor split once on the client. Deferred to the
// next frame so the first (hydration) paint still matches SSR at 50% — no
// hydration mismatch on the inline width — then it snaps to the stored value.
useEffect(() => {
const raf = requestAnimationFrame(() => {
try {
const raw = localStorage.getItem(SPLIT_KEY);
const n = raw == null ? NaN : Number(raw);
if (Number.isFinite(n)) setSplitPct(clampSplit(n));
} catch {}
});
return () => cancelAnimationFrame(raf);
}, []);
// Persist the split (debounced) so it survives reloads.
useEffect(() => {
const id = setTimeout(() => {
try {
localStorage.setItem(SPLIT_KEY, String(Math.round(splitPct)));
} catch {}
}, 300);
return () => clearTimeout(id);
}, [splitPct]);
// Maximized editor: lock page scroll and let Escape exit. Purely a CSS overlay
// (no Fullscreen API), so it never blurs the window and can't trip the
// integrity monitor's tab-switch/screenshot flags.
useEffect(() => {
if (!editorFullscreen) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setEditorFullscreen(false);
};
document.addEventListener("keydown", onKey);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.removeEventListener("keydown", onKey);
document.body.style.overflow = prevOverflow;
};
}, [editorFullscreen]);
// Drag the divider: translate the cursor's x within the row into a width %.
const startResize = (e: ReactPointerEvent) => {
e.preventDefault();
const applyFromClientX = (clientX: number) => {
const el = splitContainerRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
if (rect.width === 0) return;
setSplitPct(clampSplit(((clientX - rect.left) / rect.width) * 100));
};
const onMove = (ev: PointerEvent) => applyFromClientX(ev.clientX);
const onUp = () => {
document.removeEventListener("pointermove", onMove);
document.removeEventListener("pointerup", onUp);
document.body.style.userSelect = "";
document.body.style.cursor = "";
};
document.addEventListener("pointermove", onMove);
document.addEventListener("pointerup", onUp);
document.body.style.userSelect = "none";
document.body.style.cursor = "col-resize";
};
const onResizeKey = (e: ReactKeyboardEvent) => {
if (e.key === "ArrowLeft") {
e.preventDefault();
setSplitPct((p) => clampSplit(p - SPLIT_STEP));
} else if (e.key === "ArrowRight") {
e.preventDefault();
setSplitPct((p) => clampSplit(p + SPLIT_STEP));
} else if (e.key === "Home") {
e.preventDefault();
setSplitPct(50);
}
};
const changeLanguage = (next: LanguageId) => {
// Persist the current draft before swapping so switching never loses work.
try {
localStorage.setItem(`cp-arena:code:${slug}:${language}`, code);
} catch {}
setCode(loadCode(next));
setLanguage(next);
};
const resetCode = () => {
setCode(STARTER_CODE[language]);
try {
localStorage.removeItem(codeKey(language));
} catch {}
};
const run = async () => {
if (running) return;
setRunning(true);
setBusyLabel("Running your code…");
setJudgement(null);
const custom =
customInput.trim() !== "" && customInput.trim() !== sampleInput.trim();
const stdin = custom ? customInput : sampleInput;
try {
const res = await fetch("/api/run", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ language, code, stdin, slug }),
});
const data = await res.json();
if (!data.ok) {
setJudgement({
mode: "run",
status: "ERR",
input: stdin,
message: data.error ?? "Run failed.",
});
} else if (data.compileFailed) {
setJudgement({
mode: "run",
status: "CE",
input: stdin,
stderr: data.compileStderr,
});
} else if (data.timedOut) {
setJudgement({
mode: "run",
status: "TLE",
input: stdin,
output: data.stdout,
message: `Exceeded the ${(data.timeLimitMs / 1000).toFixed(1)}s time limit.`,
});
} else if (custom) {
setJudgement({
mode: "run",
status: "RAN",
input: stdin,
output: data.stdout,
stderr: data.stderr,
});
} else {
const pass = (data.stdout ?? "").trim() === sampleOutput.trim();
setJudgement({
mode: "run",
status: pass ? "AC" : "WA",
input: stdin,
output: data.stdout,
stderr: data.stderr,
});
}
} catch {
setJudgement({
mode: "run",
status: "ERR",
input: stdin,
message: "Could not reach the judge.",
});
} finally {
setRunning(false);
}
};
const addHistory = (status: Verdict, clock: string, detail: string) =>
setHistory((h) => [
{ id: h.length + 1, language: languageLabel(language), status, clock, detail },
...h,
]);
const submit = async () => {
if (running || solved || !user) return;
if (turnstileConfigured && !turnstileToken) {
setJudgement({
mode: "submit",
status: "ERR",
message: "Please complete the verification challenge, then submit.",
});
return;
}
setRunning(true);
setBusyLabel("Judging against the hidden tests…");
setJudgement(null);
const solveSecs = elapsed;
const flagsNow = integrity.total;
try {
const res = await fetch("/api/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
slug,
language,
code,
elapsedSeconds: solveSecs,
flags: flagsNow,
flagsBreakdown: integrity.counts,
turnstileToken,
}),
});
const data = await res.json();
if (res.status === 429 || data.rateLimited) {
setJudgement({
mode: "submit",
status: "ERR",
message: data.error ?? "Too many submissions — slow down a moment.",
});
return;
}
if (res.status === 401 || data.needsAuth) {
setJudgement({
mode: "submit",
status: "ERR",
message: "Your session expired — please log in again to submit.",
});
return;
}
if (res.status === 403 || data.needsVerify) {
setJudgement({
mode: "submit",
status: "ERR",
message:
"Verify your email before submitting — open the verification page from your profile.",
});
return;
}
if (!data.ok) {
setJudgement({
mode: "submit",
status: "ERR",
message: data.error ?? "Judge error.",
});
return;
}
const verdict = data.verdict as Verdict;
if (verdict === "AC") {
// Prefer the server's authoritative solve time (submit − first-open);
// fall back to the local stopwatch only if it's somehow absent.
const official =
typeof data.elapsedSeconds === "number" ? data.elapsedSeconds : solveSecs;
frozenRef.current = true;
setMySolveSeconds(official);
setMyFlags(flagsNow);
setJudgement({ mode: "submit", status: "AC", total: data.total });
if (practice || data.practice) {
// Past problem: judged for feedback, but no rank/points/board.
addHistory("AC", formatClock(official), "Practice");
} else {
// Prefer the server-computed rank/points (immune to read-after-write lag).
let rank: number | null = data.rank ?? null;
let points: number | null = data.points ?? null;
let flagged: boolean = data.flagged ?? flagsNow > FLAG_LIMIT;
// Still refresh the board for display, but don't use it for self-identity
// unless the server didn't return rank/points (older API or compute failure).
const rows = await fetchBoardRows();
setBoard(rows);
if (rank == null && points == null) {
const me = rows.find((r) => r.display === (user.srn ?? user.prn));
rank = me?.rank ?? null;
points = me?.points ?? (flagsNow > FLAG_LIMIT ? BASE_POINTS : null);
flagged = me?.flagged ?? flagsNow > FLAG_LIMIT;
}
setMyRank(rank);
setMyPoints(points);
setMyFlaggedSolve(flagged);
// Surface a soft warning if the server recorded the AC verdict but
// failed to persist the submission row (leaderboard won't reflect it).
if (data.persistFailed) {
setJudgement({
mode: "submit",
status: "AC",
total: data.total,
warning:
"Accepted, but recording to the leaderboard failed. Try re-submitting or contact staff.",
});
}
const detail = flagged
? `Flagged · +${points ?? BASE_POINTS} pts`
: rank
? `${ordinal(rank)} · +${points} pts`
: `+${points ?? 0} pts`;
addHistory("AC", formatClock(official), detail);
}
} else {
setJudgement({
mode: "submit",
status: verdict,
stderr: data.detail,
passed: data.passed,
total: data.total,
failedOn: data.failedOn,
});
const detail =
verdict === "CE"
? "Compilation error"
: `on test ${data.failedOn ?? "?"}/${data.total ?? "?"}`;
addHistory(verdict, formatClock(solveSecs), detail);
}
} catch {
setJudgement({
mode: "submit",
status: "ERR",
message: "Could not reach the judge.",
});
} finally {
setRunning(false);
// Turnstile tokens are single-use — refresh the widget for a next attempt.
if (turnstileConfigured) {
setTurnstileToken(null);
setTurnstileNonce((n) => n + 1);
}
}
};
return (
<div className="mt-8 space-y-6">
{/* Dim + blur the whole page behind the maximized editor. Portaled to
<body> so the backdrop-filter's root is the document — a nested scrim
only blurs its own stacking context, letting late-painted fixed layers
(e.g. the HUD frame) escape the blur. The editor panel stays in place
(z-100 > this z-95), so it isn't blurred and CodeMirror never
remounts. Clicking the scrim exits full screen. */}
{editorFullscreen &&
typeof document !== "undefined" &&
createPortal(
<div
aria-hidden
onClick={() => setEditorFullscreen(false)}
className="fixed inset-0 z-[95] bg-black/40 backdrop-blur-sm"
/>,
document.body,
)}
<div
ref={splitContainerRef}
className="flex flex-col gap-6 lg:flex-row lg:items-start"
style={{ "--arena-left": `${splitPct}%` } as CSSProperties}
>
{/* Problem statement */}
<MechaPanel
label={practice ? "Practice" : "Problem"}
index="01"
ticks
className="w-full lg:w-[var(--arena-left)] lg:shrink-0"
>
<div className="relative">
<div
// `data-lenis-prevent` lets this panel scroll natively instead of
// Lenis hijacking the wheel for the whole page.
data-lenis-prevent
className={`arena-no-print max-h-[560px] overflow-y-auto overscroll-contain px-6 py-6 lg:max-h-[720px] ${
practice ? "" : "select-none"
}`}
onCopyCapture={
practice
? undefined
: (e) => {
e.preventDefault();
integrity.record("copy");
}
}
onCutCapture={
practice
? undefined
: (e) => {
e.preventDefault();
integrity.record("cut");
}
}
onContextMenu={
practice
? undefined
: (e) => {
e.preventDefault();
integrity.record("context-menu");
}
}
>
{problem}
</div>
{!practice && (
<Watermark tag={`@${user?.username ?? "guest"} · PESUECC Arena`} />
)}
{!practice && !pageFocused && <ScreenGuard />}
</div>
</MechaPanel>
{/* Draggable divider — resizes the problem/editor split on desktop.
The whole bar is grabbable; arrow keys nudge it, double-click resets. */}
<div
role="separator"
aria-orientation="vertical"
aria-label="Resize the problem and editor panels"
aria-valuemin={SPLIT_MIN}
aria-valuemax={SPLIT_MAX}
aria-valuenow={Math.round(splitPct)}
tabIndex={0}
onPointerDown={startResize}
onKeyDown={onResizeKey}
onDoubleClick={() => setSplitPct(50)}
title="Drag to resize · double-click to reset"
className="group relative hidden w-1.5 shrink-0 cursor-col-resize touch-none select-none self-stretch rounded-full bg-[var(--ide-border)] transition-colors hover:bg-bronze/60 focus-visible:bg-bronze focus-visible:outline-none lg:block"
>
<span
aria-hidden
className="pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-[var(--ide-ink-dim)] transition-colors group-hover:text-bronze"
>
<GripDotsIcon />
</span>
</div>
{/* Editor + console */}
<section className="w-full space-y-4 lg:min-w-0 lg:flex-1">
<MechaPanel
className={`mecha--ide ${
editorFullscreen
? "fixed inset-x-0 top-6 bottom-6 z-[100] mx-auto w-[min(1100px,94vw)]"
: ""
}`}
bodyClassName={editorFullscreen ? "flex flex-col" : ""}
>
{/* IDE title bar */}
<div className="flex shrink-0 items-center gap-3 border-b border-[var(--ide-border)] bg-[var(--ide-bar)] px-4 py-2.5">
<span className="flex gap-1.5" aria-hidden>
<span className="h-2.5 w-2.5 rounded-full bg-[#e06c5b]" />
<span className="h-2.5 w-2.5 rounded-full bg-[#e0b24b]" />
<span className="h-2.5 w-2.5 rounded-full bg-[#5bbf7a]" />
</span>
<span className="font-mono text-xs text-[var(--ide-ink)]">
main.{FILE_EXT[language]}
</span>
<div className="ml-auto flex items-center gap-3">
<label className="sr-only" htmlFor="language">
Language
</label>
<select
id="language"
value={language}
onChange={(e) => changeLanguage(e.target.value as LanguageId)}
className="mecha-input w-auto px-2 py-1 text-xs font-medium"
>
{LANGUAGES.map((l) => (
<option
key={l.id}
value={l.id}
style={{
backgroundColor: "var(--ide-body)",
color: "var(--ide-ink-strong)",
}}
>
{l.label}
</option>
))}
</select>
<span
title="Indicative timer — your official solve time is recorded server-side on an accepted submission."
className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--ide-ink)]"
>
<ClockIcon />
{formatClock(elapsed)}
</span>
{practice ? (
<span className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--ide-ink-dim)]">
<TerminalIcon />
<span className="hidden sm:inline">Practice</span>
</span>
) : (
<span
title={`Copy, paste and right-click are disabled · tab switches are recorded · more than ${FLAG_LIMIT} flags removes you from the top 10`}
className={`inline-flex items-center gap-1.5 font-mono text-xs ${
integrity.flagged
? "text-red-400"
: integrity.total > 0
? "text-amber-400"
: "text-[var(--ide-ink-dim)]"
}`}
>
<ShieldIcon />
<span className="hidden sm:inline">
{integrity.flagged ? "Flagged" : "Proctored"}
</span>
{integrity.total > 0 && <span>· {integrity.total}</span>}
</span>
)}
<button
type="button"
onClick={() => setEditorFullscreen((v) => !v)}
aria-pressed={editorFullscreen}
title={
editorFullscreen
? "Exit full screen (Esc)"
: "Full screen editor"
}
className="inline-flex items-center justify-center rounded-md p-1 text-[var(--ide-ink)] transition-colors hover:text-[var(--ide-ink-strong)]"
>
{editorFullscreen ? <CompressIcon /> : <ExpandIcon />}
</button>
</div>
</div>
<div
// Let the editor scroll natively — otherwise Lenis hijacks the
// wheel for the page (which is scroll-locked in fullscreen) and
// the editor never receives it.
data-lenis-prevent
className={
editorFullscreen ? "min-h-0 flex-1 overflow-hidden" : ""
}
>
<CodeEditor
value={code}
onChange={setCode}
language={language}
lockClipboard
onBlocked={integrity.record}
fullscreen={editorFullscreen}
/>
</div>
{turnstileConfigured && !solved && (
<div className="shrink-0 border-t border-[var(--ide-border)] bg-[var(--ide-bar)] px-4 py-3">
<Turnstile key={turnstileNonce} onToken={setTurnstileToken} />
</div>
)}
{/* Action bar */}
<div className="flex shrink-0 items-center gap-3 border-t border-[var(--ide-border)] bg-[var(--ide-bar)] px-4 py-3">
<button
type="button"
onClick={resetCode}
className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-2 text-xs font-medium text-[var(--ide-ink)] transition-colors hover:text-[var(--ide-ink-strong)]"
>
<ResetIcon />
Reset
</button>
<span
title="Your code is auto-saved in this browser."
className="hidden items-center gap-1.5 font-mono text-[11px] text-[var(--ide-ink-dim)] sm:inline-flex"
>
<CheckIcon />
Auto-saved
</span>
<div className="ml-auto flex items-center gap-2.5">
<button
type="button"
onClick={run}
disabled={running}
className="mecha-btn mecha-btn--ghost mecha-btn--sm"
>
<PlayIcon />
Run
</button>
{user === null ? (
<Link
href="/login"
className="mecha-btn mecha-btn--solid mecha-btn--sm"
>
<BoltIcon />
Log in to submit
</Link>
) : (
<button
type="button"
onClick={submit}
disabled={running || solved || user === undefined}
className={`mecha-btn mecha-btn--sm ${
solved ? "mecha-btn--ok" : "mecha-btn--solid"
}`}
>
{solved ? (
<>
<CheckIcon />
Solved
</>
) : (
<>
<BoltIcon />
Submit
</>
)}
</button>
)}
</div>
</div>
</MechaPanel>
<CustomInputPanel
value={customInput}
onChange={setCustomInput}
onResetToSample={() => setCustomInput(sampleInput)}
isCustom={
customInput.trim() !== "" &&
customInput.trim() !== sampleInput.trim()
}
/>
{integrity.total > 0 && (
<div
role="status"
className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium ${
integrity.flagged
? "border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-400"
: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400"
}`}
>
<ShieldIcon />
<span>
{integrity.notice ??
(integrity.flagged
? "Removed from today's top 10 — an accepted solve now earns only the 100-point base."
: "Stay under 5 flags to keep your top-10 bounty eligibility.")}
</span>
<span className="ml-auto shrink-0 font-mono">
{integrity.total}/{FLAG_LIMIT} flags
</span>
</div>
)}
<Console
running={running}
busyLabel={busyLabel}
judgement={judgement}
sampleOutput={sampleOutput}
myRank={myRank}
myPoints={myPoints}
flagged={myFlaggedSolve}
flagCount={myFlags}
practice={practice}
solveClock={mySolveSeconds != null ? formatClock(mySolveSeconds) : ""}
/>
<SubmissionsPanel history={history} />
</section>
</div>
{practice ? (
<MechaPanel label="Practice">
<div className="px-6 pb-6 pt-3 text-center">
<p className="text-sm text-charcoal/70">
This is a past problem, open for practice. Submissions are judged
against the hidden tests but don't affect the leaderboard.
</p>
<Link
href="/cp-arena"
className="mt-3 inline-block text-sm font-semibold text-bronze hover:underline"
>
Go to today's Problem of the Day
</Link>
</div>
</MechaPanel>
) : (
<>
<SpeedBounty />
<MechaPanel label="Live Standings" ticks>
<div className="flex items-center justify-end border-b border-hairline px-6 py-4">
<span className="inline-flex items-center gap-1.5 text-xs font-medium text-charcoal/60">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-emerald-500" />
{board?.length ?? 0} solved today
</span>
</div>
{board === null ? (
<p className="px-6 py-8 text-center text-sm text-charcoal/50">
Loading…
</p>
) : (
<LeaderboardTable
rows={board}
scope="today"
currentIdentity={user ? user.srn ?? user.prn : undefined}
/>
)}
</MechaPanel>
</>
)}
</div>
);
}
/* --- Console --- */
function Console({
running,
busyLabel,
judgement,
sampleOutput,
myRank,
myPoints,
flagged,
flagCount,
practice,
solveClock,
}: {
running: boolean;
busyLabel: string;
judgement: Judgement;
sampleOutput: string;
myRank: number | null;
myPoints: number | null;
flagged: boolean;
flagCount: number;
practice: boolean;
solveClock: string;
}) {
return (
<MechaPanel
className="mecha--ide"
label="Console"
index={<VerdictBadge running={running} judgement={judgement} />}
>
<div className="min-h-[150px] px-4 py-4 font-mono text-xs leading-relaxed text-[var(--ide-code)]">
{running ? (
<p className="flex items-center gap-2 text-bronze">
<span className="h-2 w-2 animate-pulse rounded-full bg-bronze" />
{busyLabel}
</p>
) : !judgement ? (
<p className="text-[var(--ide-ink-dim)]">
Write your solution, then{" "}
<span className="text-bronze">Run</span> it against the sample or{" "}
<span className="text-bronze">Submit </span> to the judge's hidden
tests.{" "}
{practice
? "This past problem is for practice — it won't change the leaderboard."
: "Faster accepted solves earn more of the daily bounty."}
</p>
) : judgement.mode === "submit" ? (
<SubmitResult
judgement={judgement}
myRank={myRank}
myPoints={myPoints}
flagged={flagged}
flagCount={flagCount}
practice={practice}
solveClock={solveClock}
/>
) : (
<RunResult judgement={judgement} sampleOutput={sampleOutput} />
)}
</div>
</MechaPanel>
);
}
function SubmitResult({
judgement,
myRank,
myPoints,
flagged,
flagCount,
practice,
solveClock,
}: {
judgement: NonNullable<Judgement>;
myRank: number | null;
myPoints: number | null;
flagged: boolean;
flagCount: number;
practice: boolean;
solveClock: string;
}) {
if (judgement.status === "AC" && practice) {
return (
<div className="space-y-2">
<p className="text-sm font-semibold text-emerald-600 dark:text-emerald-400">
Accepted — all {judgement.total ?? ""} tests passed.
</p>
<p className="text-[var(--ide-code)]">
Practice solve in{" "}
<span className="font-semibold text-[var(--ide-ink-strong)]">
{solveClock}
</span>
. Past problems don't affect the leaderboard — nice work.
</p>
</div>
);
}
if (judgement.status === "AC") {
return (
<div className="space-y-2">
<p className="text-sm font-semibold text-emerald-600 dark:text-emerald-400">
Accepted — all {judgement.total ?? ""} tests passed.
</p>
{flagged ? (
<>
<p className="flex items-center gap-1.5 text-sm font-semibold text-red-600 dark:text-red-400">
<ShieldIcon />