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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
"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  Play,
  Send,
  Loader2,
  CheckCircle2,
  XCircle,
  RotateCcw,
  ArrowLeft,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { CodeBlock } from "@/components/coding/code-block";
import { XpResults } from "@/components/shared/xp-results";
import { LevelUpOverlay } from "@/components/shared/level-up";
import {
  apiClient,
  type CodingGenerateResponse,
  type CodingRunResponse,
  type CodingSubmitCodeResponse,
  type CodingSubmitWrittenResponse,
  type CodingLanguage,
} from "@/lib/api-client";

const CODING_COLOR = "var(--color-coding)";

const TYPE_LABELS: Record<string, string> = {
  "code-creation": "Code Creation",
  debugging: "Debugging",
  "code-review": "Code Review",
  architecture: "Architecture",
};

function Badge({ children }: { children: React.ReactNode }) {
  return (
    <span
      className="text-xs font-semibold px-2 py-0.5 rounded-md"
      style={{ background: `${CODING_COLOR}1a`, color: CODING_COLOR }}
    >
      {children}
    </span>
  );
}

export default function CodingProblemPage() {
  const router = useRouter();
  const [data, setData] = useState<CodingGenerateResponse | null>(null);
  const [missing, setMissing] = useState(false);

  const [code, setCode] = useState("");
  const [answer, setAnswer] = useState("");

  const [running, setRunning] = useState(false);
  const [runResult, setRunResult] = useState<CodingRunResponse | null>(null);
  const [submittingCode, setSubmittingCode] = useState(false);
  const [codeResult, setCodeResult] = useState<CodingSubmitCodeResponse | null>(null);
  const [submittingWritten, setSubmittingWritten] = useState(false);
  const [writtenResult, setWrittenResult] = useState<CodingSubmitWrittenResponse | null>(null);
  const [showLevelUp, setShowLevelUp] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const startRef = useRef<number>(0);

  useEffect(() => {
    const raw = typeof window !== "undefined" ? sessionStorage.getItem("coding:problem") : null;
    if (!raw) {
      setMissing(true);
      return;
    }
    try {
      const parsed = JSON.parse(raw) as CodingGenerateResponse;
      setData(parsed);
      const p = parsed.problem;
      setCode(p.buggyCode ?? p.starterCode ?? "");
      startRef.current = Date.now();
    } catch {
      setMissing(true);
    }
  }, []);

  const problem = data?.problem;
  const language = (problem?.language ?? "javascript") as CodingLanguage;
  const isExecutable =
    problem?.type === "code-creation" || problem?.type === "debugging";
  const isWritten =
    problem?.type === "code-review" || problem?.type === "architecture";

  const elapsed = () => Math.max(0, Math.round((Date.now() - startRef.current) / 1000));

  async function handleRun() {
    if (!data) return;
    setRunning(true);
    setError(null);
    try {
      const res = await apiClient.runCode(data.instanceId, code);
      setRunResult(res);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Run failed.");
    } finally {
      setRunning(false);
    }
  }

  async function handleSubmitCode() {
    if (!data) return;
    setSubmittingCode(true);
    setError(null);
    try {
      const res = await apiClient.submitCode(data.instanceId, code, elapsed());
      setCodeResult(res);
      if (res.awarded && res.categoryXp?.levelUp) setShowLevelUp(true);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Submit failed.");
    } finally {
      setSubmittingCode(false);
    }
  }

  async function handleSubmitWritten() {
    if (!data) return;
    setSubmittingWritten(true);
    setError(null);
    try {
      const res = await apiClient.submitWrittenAnswer(data.instanceId, answer, elapsed());
      setWrittenResult(res);
      if (res.awarded && res.categoryXp?.levelUp) setShowLevelUp(true);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Submit failed.");
    } finally {
      setSubmittingWritten(false);
    }
  }

  const runSummary = useMemo(() => {
    if (!runResult) return null;
    if (runResult.compileError) return { ok: false, text: runResult.compileError };
    return {
      ok: runResult.allPassed,
      text: `${runResult.passed}/${runResult.total} example tests passed`,
    };
  }, [runResult]);

  if (missing) {
    return (
      <div className="max-w-2xl mx-auto py-16 text-center space-y-4">
        <p style={{ color: "var(--text-secondary)" }}>
          No problem loaded. Generate one to get started.
        </p>
        <Link href="/coding">
          <Button style={{ background: CODING_COLOR, color: "#0a0e14" }}>
            Go to Coding Training
          </Button>
        </Link>
      </div>
    );
  }

  if (!problem) {
    return (
      <div className="max-w-2xl mx-auto py-16 text-center" style={{ color: "var(--text-muted)" }}>
        <Loader2 className="animate-spin mx-auto" />
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto space-y-5 pb-16">
      {/* Header */}
      <div className="flex items-center justify-between gap-3">
        <Link
          href="/coding"
          className="flex items-center gap-1.5 text-sm"
          style={{ color: "var(--text-muted)" }}
        >
          <ArrowLeft size={15} /> Back
        </Link>
        <div className="flex items-center gap-2">
          <Badge>{TYPE_LABELS[problem.type] ?? problem.type}</Badge>
          <Badge>{problem.difficulty}</Badge>
          <Badge>{problem.language}</Badge>
        </div>
      </div>

      <div className="space-y-2">
        <h1 data-testid="problem-title" className="text-xl font-bold" style={{ color: "var(--text-primary)" }}>
          {problem.title}
        </h1>
        <p
          data-testid="problem-prompt"
          className="text-sm whitespace-pre-wrap leading-relaxed"
          style={{ color: "var(--text-secondary)" }}
        >
          {problem.prompt}
        </p>
      </div>

      {/* Code under review (read-only) */}
      {problem.type === "code-review" && problem.code && (
        <CodeBlock code={problem.code} language={language} testId="review-code" />
      )}

      {/* Example tests for executable problems */}
      {isExecutable && problem.tests && problem.tests.length > 0 && (
        <div className="glass rounded-lg p-3 text-xs" style={{ color: "var(--text-muted)" }}>
          <span className="font-semibold">Example tests:</span>{" "}
          {problem.tests.map((t, i) => (
            <span key={i} className="font-mono">
              {problem.entryFunction}({JSON.stringify(t.input).slice(1, -1)}) → {JSON.stringify(t.expected)}
              {i < problem.tests!.length - 1 ? " · " : ""}
            </span>
          ))}
        </div>
      )}

      {/* Executable: editor + run + submit */}
      {isExecutable && (
        <div className="space-y-3">
          <label className="text-xs font-semibold tracking-wide" style={{ color: "var(--text-muted)" }}>
            YOUR CODE
          </label>
          <textarea
            data-testid="code-editor"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            spellCheck={false}
            rows={Math.max(8, code.split("\n").length + 1)}
            className="w-full rounded-lg p-3 text-sm font-mono leading-relaxed outline-none resize-y"
            style={{
              background: "rgba(10,14,20,0.7)",
              border: "1px solid rgba(255,255,255,0.1)",
              color: "var(--text-primary)",
            }}
          />

          <div className="flex gap-2">
            <Button
              data-testid="run-btn"
              onClick={handleRun}
              disabled={running}
              variant="secondary"
              className="flex items-center gap-1.5"
            >
              {running ? <Loader2 size={15} className="animate-spin" /> : <Play size={15} />}
              Run
            </Button>
            <Button
              data-testid="submit-code-btn"
              onClick={handleSubmitCode}
              disabled={submittingCode}
              className="flex items-center gap-1.5"
              style={{ background: CODING_COLOR, color: "#0a0e14" }}
            >
              {submittingCode ? <Loader2 size={15} className="animate-spin" /> : <Send size={15} />}
              Submit Code
            </Button>
          </div>

          {/* Run output */}
          {runResult && runSummary && (
            <div data-testid="run-output" className="glass rounded-lg p-3 space-y-2 text-sm">
              <div
                className="flex items-center gap-2 font-semibold"
                style={{ color: runSummary.ok ? "#34d399" : "#fb7185" }}
              >
                {runSummary.ok ? <CheckCircle2 size={16} /> : <XCircle size={16} />}
                {runSummary.text}
              </div>
              {runResult.results.map((r, i) => (
                <div key={i} className="flex items-start gap-2 font-mono text-xs">
                  <span style={{ color: r.passed ? "#34d399" : "#fb7185" }}>
                    {r.passed ? "✓" : "✗"}
                  </span>
                  <span style={{ color: "var(--text-secondary)" }}>
                    {r.name}
                    {!r.passed && r.error ? ` — ${r.error}` : ""}
                    {!r.passed && !r.error
                      ? ` — expected ${JSON.stringify(r.expected)}, got ${JSON.stringify(r.actual)}`
                      : ""}
                  </span>
                </div>
              ))}
              {runResult.stdout.length > 0 && (
                <pre className="text-xs rounded p-2 overflow-x-auto" style={{ background: "rgba(0,0,0,0.3)", color: "var(--text-muted)" }}>
                  {runResult.stdout.join("\n")}
                </pre>
              )}
            </div>
          )}
        </div>
      )}

      {/* Written answer */}
      {isWritten && (
        <div className="space-y-3">
          <label className="text-xs font-semibold tracking-wide" style={{ color: "var(--text-muted)" }}>
            {problem.type === "code-review" ? "YOUR REVIEW" : "YOUR ANSWER"}
          </label>
          <textarea
            data-testid="written-answer"
            value={answer}
            onChange={(e) => setAnswer(e.target.value)}
            rows={8}
            placeholder={
              problem.type === "code-review"
                ? "Describe each issue you find (or state the code is correct)…"
                : "Lay out your design — components, tradeoffs, failure modes…"
            }
            className="w-full rounded-lg p-3 text-sm leading-relaxed outline-none resize-y"
            style={{
              background: "rgba(255,255,255,0.05)",
              border: "1px solid rgba(255,255,255,0.1)",
              color: "var(--text-primary)",
            }}
          />
          <Button
            data-testid="submit-written-btn"
            onClick={handleSubmitWritten}
            disabled={submittingWritten}
            className="flex items-center gap-1.5"
            style={{ background: CODING_COLOR, color: "#0a0e14" }}
          >
            {submittingWritten ? <Loader2 size={15} className="animate-spin" /> : <Send size={15} />}
            Submit Answer
          </Button>
        </div>
      )}

      {error && (
        <p data-testid="problem-error" className="text-sm rounded-lg px-3 py-2" style={{ background: "rgba(244,63,94,0.12)", color: "#fb7185" }}>
          {error}
        </p>
      )}

      {/* Code result */}
      {codeResult && (
        <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} data-testid="code-result" className="space-y-3">
          <div
            className="flex items-center gap-2 font-semibold"
            style={{ color: codeResult.correct ? "#34d399" : "#fb7185" }}
          >
            {codeResult.correct ? <CheckCircle2 size={18} /> : <XCircle size={18} />}
            <span data-testid="code-result-message">{codeResult.message}</span>
          </div>
          {codeResult.awarded && codeResult.xp && codeResult.categoryXp && (
            <div data-testid="xp-results-code">
              <p className="text-xs font-semibold mb-1" style={{ color: CODING_COLOR }}>
                CODE XP
              </p>
              <XpResults
                category="coding"
                baseXp={codeResult.xp.baseXp}
                qualityBonus={codeResult.xp.qualityBonus}
                isCriticalHit={codeResult.isCriticalHit ?? false}
                totalXp={codeResult.xp.totalXp}
                categoryCurrentXp={codeResult.categoryXp.currentXp}
                categoryXpToNext={codeResult.categoryXp.xpToNext}
                categoryLevel={codeResult.categoryXp.level}
                levelUp={codeResult.categoryXp.levelUp}
                multiplierBonus={codeResult.xp.multiplierBonus}
                multiplierPercent={codeResult.xp.multiplierPercent}
                onNext={() => router.push("/coding")}
                nextLabel="New Problem"
              />
            </div>
          )}
        </motion.div>
      )}

      {/* Written result */}
      {writtenResult && (
        <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} data-testid="written-result" className="space-y-3">
          <div
            className="flex items-center gap-2 font-semibold"
            style={{ color: writtenResult.correct ? "#34d399" : "#fb7185" }}
          >
            {writtenResult.correct ? <CheckCircle2 size={18} /> : <XCircle size={18} />}
            <span data-testid="written-result-message">{writtenResult.message}</span>
          </div>
          {writtenResult.feedback && (
            <p className="text-sm" style={{ color: "var(--text-secondary)" }}>
              {writtenResult.feedback}
            </p>
          )}
          {writtenResult.expectations && writtenResult.expectations.length > 0 && (
            <div className="glass rounded-lg p-3 text-xs space-y-1" style={{ color: "var(--text-muted)" }}>
              <span className="font-semibold">What a strong answer covers:</span>
              {writtenResult.expectations.map((e) => (
                <div key={e.id}>• {e.title ?? e.point}</div>
              ))}
            </div>
          )}
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Graded by: {writtenResult.gradedBy === "llm-judge" ? "LLM judge" : "offline heuristic"}
          </p>
          {writtenResult.awarded && writtenResult.xp && writtenResult.categoryXp && (
            <div data-testid="xp-results-written">
              <p className="text-xs font-semibold mb-1" style={{ color: CODING_COLOR }}>
                WRITTEN XP
              </p>
              <XpResults
                category="coding"
                baseXp={writtenResult.xp.baseXp}
                qualityBonus={writtenResult.xp.qualityBonus}
                isCriticalHit={writtenResult.isCriticalHit ?? false}
                totalXp={writtenResult.xp.totalXp}
                categoryCurrentXp={writtenResult.categoryXp.currentXp}
                categoryXpToNext={writtenResult.categoryXp.xpToNext}
                categoryLevel={writtenResult.categoryXp.level}
                levelUp={writtenResult.categoryXp.levelUp}
                multiplierBonus={writtenResult.xp.multiplierBonus}
                multiplierPercent={writtenResult.xp.multiplierPercent}
                onNext={() => router.push("/coding")}
                nextLabel="New Problem"
              />
            </div>
          )}
        </motion.div>
      )}

      {/* New problem shortcut when nothing solved yet */}
      {!codeResult?.awarded && !writtenResult?.awarded && (
        <button
          onClick={() => router.push("/coding")}
          className="flex items-center gap-1.5 text-xs mx-auto"
          style={{ color: "var(--text-muted)" }}
        >
          <RotateCcw size={13} /> Generate a different problem
        </button>
      )}

      <LevelUpOverlay
        show={showLevelUp}
        level={(codeResult?.categoryXp?.level ?? writtenResult?.categoryXp?.level) ?? 1}
        title={codeResult?.newTitle ?? writtenResult?.newTitle}
        category="coding"
        onDismiss={() => setShowLevelUp(false)}
      />
    </div>
  );
}