File size: 50,392 Bytes
8800c81
 
59a8d26
8800c81
 
 
 
1993562
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
 
 
 
 
 
1993562
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
1993562
8800c81
 
 
1993562
 
 
 
 
 
 
 
 
 
8800c81
 
1993562
8800c81
1993562
8800c81
 
 
1993562
 
 
8800c81
 
1993562
 
 
 
 
 
 
 
 
59a8d26
1993562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
1993562
8800c81
 
 
1993562
 
 
8800c81
 
 
59a8d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
1993562
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
8800c81
 
 
 
 
 
 
59a8d26
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
8800c81
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
1993562
8800c81
 
 
59a8d26
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
 
 
 
 
 
 
1993562
 
 
 
 
 
 
 
59a8d26
1993562
59a8d26
1993562
 
59a8d26
 
1993562
 
59a8d26
 
1993562
 
 
 
 
 
 
 
59a8d26
1993562
59a8d26
1993562
 
59a8d26
 
1993562
 
59a8d26
 
 
1993562
 
 
8800c81
 
1993562
 
8800c81
 
 
 
 
1993562
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
c05acd1
 
8800c81
 
 
 
 
 
c05acd1
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
c05acd1
 
 
8800c81
 
c05acd1
8800c81
 
 
 
 
 
 
 
59a8d26
 
8800c81
59a8d26
 
 
 
 
 
8800c81
 
 
 
 
59a8d26
8800c81
 
 
59a8d26
 
 
 
 
 
8800c81
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a8d26
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05acd1
59a8d26
 
 
 
 
 
 
 
c05acd1
59a8d26
 
8800c81
 
59a8d26
 
8800c81
59a8d26
8800c81
 
 
59a8d26
 
 
 
 
 
 
c05acd1
 
 
 
59a8d26
 
 
c05acd1
 
59a8d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c05acd1
 
 
8800c81
 
c05acd1
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
8800c81
 
 
 
 
 
59a8d26
 
 
 
 
 
8800c81
 
 
59a8d26
 
 
 
8800c81
59a8d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
59a8d26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
59a8d26
 
8800c81
 
 
 
 
 
1993562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1993562
 
 
 
 
 
 
 
8800c81
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
import React, { useState } from 'react';
import { supabase } from '../firebaseClient';
import type { ProblemItem, ProblemSolution } from '../types/reviewTypes';

interface CreateProblemFormProps {
  onClose: () => void;
  onSuccess: () => void;
  initialProblem?: ProblemItem | null;
  mode?: 'create' | 'edit';
}

interface ExampleItem {
  input: string;
  output: string;
  explanation?: string;
}

const COMMON_PATTERNS = [
  'Arrays & Hashing',
  'Two Pointers',
  'Sliding Window',
  'Stack',
  'Binary Search',
  'Linked List',
  'Trees',
  'Tries',
  'Heap / Priority Queue',
  'Backtracking',
  'Graphs',
  'Advanced Graphs',
  '1-D Dynamic Programming',
  '2-D Dynamic Programming',
  'Greedy',
  'Intervals',
  'Math & Geometry',
  'Bit Manipulation'
];

function generateSolutionId(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return `sol-${crypto.randomUUID()}`;
  }
  return `sol-${Date.now()}`;
}

export default function CreateProblemForm({
  onClose,
  onSuccess,
  initialProblem,
  mode = initialProblem ? 'edit' : 'create'
}: CreateProblemFormProps) {
  const isEditMode = mode === 'edit' || Boolean(initialProblem);

  // Navigation / Tab
  const [activeTab, setActiveTab] = useState<'form' | 'preview'>('form');

  // URL / Quick import
  const [urlQuery, setUrlQuery] = useState('');
  const [fetchingUrl, setFetchingUrl] = useState(false);

  // Form Fields
  const [newFileName, setNewFileName] = useState(() => {
    if (initialProblem?.name) return initialProblem.name;
    try {
      const draft = localStorage.getItem('algospaced_prefill_draft');
      if (draft) return JSON.parse(draft).name || '';
    } catch {
      /* ignore invalid json */
    }
    return '';
  });

  const [newFileProblemNumber, setNewFileProblemNumber] = useState<number | ''>(() => {
    if (initialProblem?.problem_number !== undefined && initialProblem?.problem_number !== null) {
      return initialProblem.problem_number;
    }
    return '';
  });

  const [newFilePattern, setNewFilePattern] = useState(() => {
    if (initialProblem?.pattern) return initialProblem.pattern;
    try {
      const draft = localStorage.getItem('algospaced_prefill_draft');
      if (draft) return JSON.parse(draft).pattern || '';
    } catch {
      /* ignore invalid json */
    }
    return 'Arrays & Hashing';
  });

  const [newFileDifficulty, setNewFileDifficulty] = useState<'Easy' | 'Medium' | 'Hard'>(() => {
    if (initialProblem?.difficulty === 'Easy' || initialProblem?.difficulty === 'Medium' || initialProblem?.difficulty === 'Hard') {
      return initialProblem.difficulty;
    }
    return 'Medium';
  });

  const [newFileOptimalTime, setNewFileOptimalTime] = useState(() => initialProblem?.optimal_time || 'O(N)');
  const [newFileOptimalSpace, setNewFileOptimalSpace] = useState(() => initialProblem?.optimal_space || 'O(1)');
  const [newFileDescription, setNewFileDescription] = useState(() => initialProblem?.description || '');

  const [newFileExamples, setNewFileExamples] = useState<ExampleItem[]>(() => {
    if (initialProblem?.examples && Array.isArray(initialProblem.examples) && initialProblem.examples.length > 0) {
      return initialProblem.examples.map((ex: { input?: unknown; output?: unknown; explanation?: string } | string) =>
        typeof ex === 'string'
          ? { input: ex, output: '', explanation: '' }
          : { input: String(ex?.input ?? ''), output: String(ex?.output ?? ''), explanation: ex?.explanation || '' }
      );
    }
    return [{ input: '', output: '', explanation: '' }];
  });

  const [newFileConstraints, setNewFileConstraints] = useState(() => {
    if (initialProblem?.constraints) {
      if (Array.isArray(initialProblem.constraints)) return initialProblem.constraints.join('\n');
      return String(initialProblem.constraints);
    }
    return '';
  });

  const [newFileHowToSolve, setNewFileHowToSolve] = useState(
    () => (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || ''
  );

  const [newFileCode, setNewFileCode] = useState(() => {
    if (initialProblem?.reference_code) return initialProblem.reference_code;
    try {
      const draft = localStorage.getItem('algospaced_prefill_draft');
      if (draft) return JSON.parse(draft).code || '';
    } catch {
      /* ignore invalid json */
    }
    return '';
  });

  // Multi-solution state
  const [solutions, setSolutions] = useState<ProblemSolution[]>(() => {
    if (initialProblem?.solutions && Array.isArray(initialProblem.solutions) && initialProblem.solutions.length > 0) {
      return initialProblem.solutions.map((s, idx) => ({
        id: s.id || `sol-${idx + 1}`,
        name: s.name || `Method ${idx + 1}`,
        pattern: s.pattern || initialProblem.pattern || 'Arrays & Hashing',
        time_complexity: s.time_complexity || initialProblem.optimal_time || 'O(N)',
        space_complexity: s.space_complexity || initialProblem.optimal_space || 'O(1)',
        code: s.code || '',
        explanation: s.explanation || '',
        is_optimal: s.is_optimal ?? (idx === 0)
      }));
    }

    let initCode = initialProblem?.reference_code || '';
    let initPattern = initialProblem?.pattern || 'Arrays & Hashing';
    try {
      const draft = localStorage.getItem('algospaced_prefill_draft');
      if (draft) {
        const parsed = JSON.parse(draft);
        if (parsed.code && !initCode) initCode = parsed.code;
        if (parsed.pattern && !initPattern) initPattern = parsed.pattern;
      }
    } catch {
      /* ignore invalid json */
    }

    return [
      {
        id: 'sol-1',
        name: 'Optimal Method',
        pattern: initPattern,
        time_complexity: initialProblem?.optimal_time || 'O(N)',
        space_complexity: initialProblem?.optimal_space || 'O(1)',
        code: initCode,
        explanation: (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || '',
        is_optimal: true
      }
    ];
  });
  const [activeSolutionIdx, setActiveSolutionIdx] = useState(0);

  const activeSolution = solutions[activeSolutionIdx] || solutions[0] || {
    id: 'sol-1',
    name: 'Method 1',
    pattern: 'Arrays & Hashing',
    time_complexity: 'O(N)',
    space_complexity: 'O(1)',
    code: '',
    explanation: '',
    is_optimal: true
  };

  const updateActiveSolution = (updates: Partial<ProblemSolution>) => {
    setSolutions(prev => {
      const next = [...prev];
      const targetIdx = activeSolutionIdx < next.length ? activeSolutionIdx : 0;
      next[targetIdx] = { ...next[targetIdx], ...updates };
      if (updates.is_optimal) {
        next.forEach((s, idx) => {
          if (idx !== targetIdx) s.is_optimal = false;
        });
        if (next[targetIdx].time_complexity) setNewFileOptimalTime(next[targetIdx].time_complexity);
        if (next[targetIdx].space_complexity) setNewFileOptimalSpace(next[targetIdx].space_complexity);
        if (next[targetIdx].pattern) setNewFilePattern(next[targetIdx].pattern);
      }
      return next;
    });
  };

  const addSolution = () => {
    const nextNum = solutions.length + 1;
    const newSol: ProblemSolution = {
      id: generateSolutionId(),
      name: `Method ${nextNum}`,
      pattern: newFilePattern || 'Arrays & Hashing',
      time_complexity: 'O(N)',
      space_complexity: 'O(1)',
      code: '',
      explanation: '',
      is_optimal: solutions.length === 0
    };
    setSolutions(prev => [...prev, newSol]);
    setActiveSolutionIdx(solutions.length);
  };

  const removeSolution = (idxToRemove: number) => {
    if (solutions.length <= 1) return;
    setSolutions(prev => {
      const next = prev.filter((_, i) => i !== idxToRemove);
      if (!next.some(s => s.is_optimal)) {
        next[0].is_optimal = true;
      }
      return next;
    });
    if (activeSolutionIdx >= solutions.length - 1) {
      setActiveSolutionIdx(Math.max(0, solutions.length - 2));
    }
  };

  // Dual-write & Status
  const [syncToGDoc, setSyncToGDoc] = useState(true);
  const [createError, setCreateError] = useState('');
  const [createSuccess, setCreateSuccess] = useState('');
  const [creating, setCreating] = useState(false);

  // AI loading flags
  const [loadingIntuition, setLoadingIntuition] = useState(false);
  const [loadingComments, setLoadingComments] = useState(false);
  const [prefilling, setPrefilling] = useState(false);

  React.useEffect(() => {
    if (!isEditMode) {
      localStorage.removeItem('algospaced_prefill_draft');
    }
  }, [isEditMode]);

  const getHeaders = async () => {
    const { data: { session } } = await supabase.auth.getSession();
    const token = session ? session.access_token : 'sandbox';
    const customKey = localStorage.getItem('algospaced_custom_api_key') || localStorage.getItem('sandbox_gemini_api_key') || '';
    const customProvider = localStorage.getItem('algospaced_custom_ai_provider') || 'default';
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    };
    if (customProvider && customProvider !== 'default' && customKey && customKey.trim()) {
      headers['x-custom-api-key'] = customKey.trim();
      headers['x-gemini-api-key'] = customKey.trim();
      headers['x-ai-provider'] = customProvider;
    }
    return headers;
  };

  // 1. Fetch LeetCode Details via URL or Title
  const handleFetchLeetCode = async () => {
    if (!urlQuery.trim()) return;
    setFetchingUrl(true);
    setCreateError('');
    try {
      const headers = await getHeaders();
      const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/fetch-leetcode`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ query: urlQuery.trim() })
      });

      if (res.ok) {
        const data = await res.json();
        if (data.problem_number !== undefined && data.problem_number !== null) {
          setNewFileProblemNumber(data.problem_number);
        }
        if (data.title) setNewFileName(data.title);
        if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard');
        if (data.pattern) setNewFilePattern(data.pattern);
        if (data.optimal_time) setNewFileOptimalTime(data.optimal_time);
        if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space);
        if (data.description) setNewFileDescription(data.description);
        if (data.how_to_solve) setNewFileHowToSolve(data.how_to_solve);
        if (data.starter_code && !newFileCode.trim()) setNewFileCode(data.starter_code);

        setSolutions(prev => {
          const next = [...prev];
          const active = { ...next[activeSolutionIdx] };
          if (data.pattern) active.pattern = data.pattern;
          if (data.optimal_time) active.time_complexity = data.optimal_time;
          if (data.optimal_space) active.space_complexity = data.optimal_space;
          if (data.how_to_solve) active.explanation = data.how_to_solve;
          if (data.starter_code && !active.code?.trim()) active.code = data.starter_code;
          next[activeSolutionIdx] = active;
          return next;
        });

        if (Array.isArray(data.examples) && data.examples.length > 0) {
          setNewFileExamples(data.examples);
        }
        if (Array.isArray(data.constraints)) {
          setNewFileConstraints(data.constraints.join('\n'));
        } else if (typeof data.constraints === 'string') {
          setNewFileConstraints(data.constraints);
        }
      } else {
        const errData = await res.json();
        setCreateError(errData.detail || 'Failed to fetch LeetCode problem data.');
      }
    } catch {
      setCreateError('Fetch request failed due to connection error.');
    } finally {
      setFetchingUrl(false);
    }
  };

  // 1b. AI Prefill based on Problem Title / Code
  const handlePrefill = async () => {
    const codeToUse = activeSolution.code || newFileCode;
    if (!newFileName.trim() && !codeToUse.trim()) return;
    setPrefilling(true);
    setCreateError('');
    try {
      const headers = await getHeaders();
      const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/prefill`, {
        method: 'POST',
        headers,
        body: JSON.stringify({ name: newFileName, code: codeToUse })
      });
      if (res.ok) {
        const data = await res.json();
        if (data.problem_number !== undefined && data.problem_number !== null) {
          setNewFileProblemNumber(data.problem_number);
        }
        if (data.title && !newFileName) setNewFileName(data.title);
        if (data.pattern) setNewFilePattern(data.pattern);
        if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard');
        if (data.optimal_time) setNewFileOptimalTime(data.optimal_time);
        if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space);
        if (data.description) setNewFileDescription(data.description);
        if (data.reference_code && !codeToUse.trim()) setNewFileCode(data.reference_code);

        setSolutions(prev => {
          const next = [...prev];
          const active = { ...next[activeSolutionIdx] };
          if (data.pattern) active.pattern = data.pattern;
          if (data.optimal_time) active.time_complexity = data.optimal_time;
          if (data.optimal_space) active.space_complexity = data.optimal_space;
          if (data.reference_code && !active.code?.trim()) active.code = data.reference_code;
          next[activeSolutionIdx] = active;
          return next;
        });
      } else {
        const errData = await res.json();
        setCreateError(errData.detail || 'Prefill failed.');
      }
    } catch {
      setCreateError('Prefill request failed due to connection error.');
    } finally {
      setPrefilling(false);
    }
  };

  // 2. AI Assist: Generate "How to solve?" Intuition
  const handleGenerateIntuition = async () => {
    const codeToUse = activeSolution.code || newFileCode;
    if (!newFileName.trim() && !codeToUse.trim()) {
      setCreateError('Please enter a problem name or code first.');
      return;
    }
    setLoadingIntuition(true);
    setCreateError('');
    try {
      const headers = await getHeaders();
      const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          field: 'intuition',
          title: newFileName,
          code: codeToUse,
          description: newFileDescription
        })
      });

      if (res.ok) {
        const data = await res.json();
        if (data.how_to_solve) {
          setNewFileHowToSolve(data.how_to_solve);
          updateActiveSolution({ explanation: data.how_to_solve });
        }
      } else {
        const errData = await res.json();
        setCreateError(errData.detail || 'Failed to generate intuition.');
      }
    } catch {
      setCreateError('Intuition generator failed due to connection error.');
    } finally {
      setLoadingIntuition(false);
    }
  };

  // 3. AI Assist: Format Code with Step-by-Step Comments
  const handleFormatCode = async () => {
    const codeToUse = activeSolution.code || newFileCode;
    if (!codeToUse.trim()) {
      setCreateError('Please enter some Python code to format.');
      return;
    }
    setLoadingComments(true);
    setCreateError('');
    try {
      const headers = await getHeaders();
      const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          field: 'comments',
          title: newFileName,
          code: codeToUse
        })
      });

      if (res.ok) {
        const data = await res.json();
        if (data.formatted_code) {
          setNewFileCode(data.formatted_code);
          updateActiveSolution({ code: data.formatted_code });
        }
      } else {
        const errData = await res.json();
        setCreateError(errData.detail || 'Failed to format code.');
      }
    } catch {
      setCreateError('Code formatter failed due to connection error.');
    } finally {
      setLoadingComments(false);
    }
  };

  // 4. Submit Problem (Dual-write to Database & Google Docs)
  const handleCreateProblem = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFileName.trim()) {
      setCreateError('Problem name cannot be empty');
      return;
    }
    setCreating(true);
    setCreateError('');
    setCreateSuccess('');

    try {
      const headers = await getHeaders();
      const constraintsList = newFileConstraints
        .split('\n')
        .map(c => c.trim())
        .filter(Boolean);

      const optimalSol = solutions.find(s => s.is_optimal) || solutions[0];
      const finalPattern = optimalSol?.pattern || newFilePattern.trim() || 'General';
      const finalCode = optimalSol?.code || newFileCode;
      const finalHowToSolve = optimalSol?.explanation || newFileHowToSolve;
      const finalOptimalTime = newFileOptimalTime || optimalSol?.time_complexity || 'O(N)';
      const finalOptimalSpace = newFileOptimalSpace || optimalSol?.space_complexity || 'O(1)';

      let res: Response;
      if (isEditMode && initialProblem) {
        const targetId = initialProblem.id || (initialProblem.problem_number ? String(initialProblem.problem_number) : '') || newFileName.trim();
        res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/${encodeURIComponent(targetId)}`, {
          method: 'PUT',
          headers,
          body: JSON.stringify({
            name: newFileName.trim(),
            pattern: finalPattern,
            difficulty: newFileDifficulty,
            reference_code: finalCode,
            description: newFileDescription,
            problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber),
            optimal_time: finalOptimalTime,
            optimal_space: finalOptimalSpace,
            examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()),
            constraints: constraintsList,
            how_to_solve: finalHowToSolve,
            solutions: solutions
          })
        });
      } else {
        res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/create`, {
          method: 'POST',
          headers,
          body: JSON.stringify({
            name: newFileName.trim(),
            pattern: finalPattern,
            difficulty: newFileDifficulty,
            reference_code: finalCode,
            description: newFileDescription,
            problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber),
            optimal_time: finalOptimalTime,
            optimal_space: finalOptimalSpace,
            examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()),
            constraints: constraintsList,
            how_to_solve: finalHowToSolve,
            sync_to_gdoc: syncToGDoc,
            solutions: solutions
          })
        });
      }

      const data = await res.json();
      if (res.ok && (data.success || data.problem_id)) {
        setCreateSuccess(isEditMode ? 'Problem updated successfully!' : 'Problem saved and synced successfully!');
        setTimeout(() => {
          onSuccess();
          onClose();
        }, 1000);
      } else {
        setCreateError(data.detail || (isEditMode ? 'Failed to update problem.' : 'Failed to create problem.'));
      }
    } catch {
      setCreateError('Connection timed out.');
    } finally {
      setCreating(false);
    }
  };

  const addExample = () => {
    setNewFileExamples([...newFileExamples, { input: '', output: '', explanation: '' }]);
  };

  const removeExample = (idx: number) => {
    if (newFileExamples.length <= 1) return;
    setNewFileExamples(newFileExamples.filter((_, i) => i !== idx));
  };

  const updateExample = (idx: number, field: keyof ExampleItem, val: string) => {
    const next = [...newFileExamples];
    next[idx] = { ...next[idx], [field]: val };
    setNewFileExamples(next);
  };

  return (
    <form onSubmit={handleCreateProblem} className="flex flex-col h-full bg-[#fdf8e1] text-ink-black font-sans overflow-hidden">
      {/* Top Header & Tab Bar */}
      <div className="bg-[#f0e6c8] p-2.5 border-b-2 border-ink-black flex flex-col gap-2 shrink-0">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-1.5">
            <span className="font-arcade text-xs text-primary-purple">✦</span>
            <h2 className="text-xs font-bold font-arcade tracking-tight uppercase">
              {isEditMode ? 'Edit Problem Specification' : 'Problem & Note Studio'}
            </h2>
            {isEditMode && (
              <span className="text-[9px] bg-primary-purple/10 text-primary-purple font-mono px-1.5 py-0.5 rounded border border-primary-purple/30 font-bold">
                EDIT MODE
              </span>
            )}
          </div>
          {/* Tab Switcher */}
          <div className="flex border-2 border-ink-black bg-white rounded overflow-hidden shadow-[1px_1px_0px_#1E293B]">
            <button
              type="button"
              onClick={() => setActiveTab('form')}
              className={`px-3 py-1 text-[10px] font-bold uppercase transition-colors ${activeTab === 'form' ? 'bg-primary-purple text-white' : 'hover:bg-slate-100'
                }`}
            >
              ✏️ Editor
            </button>
            <button
              type="button"
              onClick={() => setActiveTab('preview')}
              className={`px-3 py-1 text-[10px] font-bold uppercase transition-colors ${activeTab === 'preview' ? 'bg-primary-purple text-white' : 'hover:bg-slate-100'
                }`}
            >
              📄 Doc Preview
            </button>
          </div>
        </div>

        {/* Quick LeetCode Fetch Bar */}
        <div className="flex gap-1.5 items-center">
          <input
            type="text"
            value={urlQuery}
            onChange={(e) => setUrlQuery(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleFetchLeetCode(); } }}
            placeholder="Paste LeetCode URL (e.g. https://leetcode.com/problems/two-sum/) or Title..."
            className="flex-1 bg-white border-2 border-ink-black px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-medium"
          />
          <button
            type="button"
            onClick={handleFetchLeetCode}
            disabled={fetchingUrl || !urlQuery.trim()}
            className="bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 text-ink-black font-arcade text-[9px] font-bold px-2.5 py-1.5 border-2 border-ink-black shadow-[1px_1px_0px_#1E293B] active:translate-y-0.5 cursor-pointer flex items-center gap-1 shrink-0"
          >
            <span>⚡</span> {fetchingUrl ? 'FETCHING...' : 'FETCH LEETCODE'}
          </button>
        </div>
      </div>

      {/* Messages */}
      {createError && (
        <div className="mx-3 mt-2 p-2 border-2 border-red-500 bg-red-50 text-red-800 text-[11px] font-mono leading-relaxed shrink-0">
          ⚠️ {createError}
        </div>
      )}
      {createSuccess && (
        <div className="mx-3 mt-2 p-2 border-2 border-green-500 bg-green-50 text-green-800 text-[11px] font-mono leading-relaxed shrink-0">
          ✅ {createSuccess}
        </div>
      )}

      {/* Main Body */}
      <div className="flex-1 overflow-y-auto custom-scrollbar p-3 space-y-3">
        {activeTab === 'form' ? (
          <>
            {/* Row 1: Problem #, Title, Difficulty */}
            <div className="grid grid-cols-12 gap-2">
              <div className="col-span-3 flex flex-col gap-1">
                <label className="text-[10px] font-bold text-slate-600 uppercase">Problem #:</label>
                <input
                  type="number"
                  value={newFileProblemNumber}
                  onChange={(e) => setNewFileProblemNumber(e.target.value === '' ? '' : Number(e.target.value))}
                  placeholder="e.g. 1"
                  className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold"
                />
              </div>
              <div className="col-span-6 flex flex-col gap-1">
                <div className="flex justify-between items-center">
                  <label className="text-[10px] font-bold text-slate-600 uppercase">Title:</label>
                  <button
                    type="button"
                    onClick={handlePrefill}
                    disabled={prefilling || (!newFileName.trim() && !activeSolution.code?.trim())}
                    className="text-[8px] font-arcade font-bold px-1.5 py-0.5 border border-ink-black bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer"
                  >
                    <span>✦</span> {prefilling ? '...' : 'AUTO-FILL'}
                  </button>
                </div>
                <input
                  type="text"
                  required
                  value={newFileName}
                  onChange={(e) => setNewFileName(e.target.value)}
                  placeholder="e.g. Two Sum"
                  className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold"
                />
              </div>
              <div className="col-span-3 flex flex-col gap-1">
                <label className="text-[10px] font-bold text-slate-600 uppercase">Difficulty:</label>
                <select
                  value={newFileDifficulty}
                  onChange={(e) => setNewFileDifficulty(e.target.value as 'Easy' | 'Medium' | 'Hard')}
                  className={`border-2 border-ink-black p-1.5 text-xs font-bold outline-none cursor-pointer ${newFileDifficulty === 'Easy'
                    ? 'bg-emerald-100 text-emerald-900'
                    : newFileDifficulty === 'Medium'
                      ? 'bg-amber-100 text-amber-900'
                      : 'bg-rose-100 text-rose-900'
                    }`}
                >
                  <option value="Easy">Easy</option>
                  <option value="Medium">Medium</option>
                  <option value="Hard">Hard</option>
                </select>
              </div>
            </div>

            {/* Row 2: Target Optimal Complexities (Active Recall Shielded on Review) */}
            <div className="grid grid-cols-2 gap-2 bg-[#f6edd2] p-2 border-2 border-ink-black rounded">
              <div className="flex flex-col gap-1">
                <div className="flex items-center justify-between">
                  <label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
                    <span>⏱️</span> Target Optimal Time:
                  </label>
                  <span className="text-[8px] font-mono text-slate-500">(hidden behind spoiler on review)</span>
                </div>
                <input
                  type="text"
                  value={newFileOptimalTime}
                  onChange={(e) => setNewFileOptimalTime(e.target.value)}
                  placeholder="e.g. O(N)"
                  className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold"
                />
              </div>
              <div className="flex flex-col gap-1">
                <div className="flex items-center justify-between">
                  <label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
                    <span>📦</span> Target Optimal Space:
                  </label>
                  <span className="text-[8px] font-mono text-slate-500">(hidden behind spoiler on review)</span>
                </div>
                <input
                  type="text"
                  value={newFileOptimalSpace}
                  onChange={(e) => setNewFileOptimalSpace(e.target.value)}
                  placeholder="e.g. O(1)"
                  className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold"
                />
              </div>
            </div>

            {/* Row 3: Problem Description */}
            <div className="flex flex-col gap-1">
              <label className="text-[10px] font-bold text-slate-600 uppercase">Problem Description:</label>
              <textarea
                value={newFileDescription}
                onChange={(e) => setNewFileDescription(e.target.value)}
                placeholder="Given an array of integers nums and an integer target..."
                className="bg-white border-2 border-ink-black p-2 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-sans h-20 resize-y leading-relaxed"
              />
            </div>

            {/* Row 4: Examples */}
            <div className="flex flex-col gap-1.5 bg-[#f6edd2] p-2.5 border-2 border-ink-black rounded">
              <div className="flex justify-between items-center">
                <label className="text-[10px] font-bold text-slate-700 uppercase flex items-center gap-1">
                  <span>🧪</span> Examples ({newFileExamples.length})
                </label>
                <button
                  type="button"
                  onClick={addExample}
                  className="text-[9px] font-bold px-2 py-0.5 border border-ink-black bg-white hover:bg-slate-100 cursor-pointer shadow-[1px_1px_0px_#1E293B]"
                >
                  + Add Example
                </button>
              </div>

              {newFileExamples.map((ex, idx) => (
                <div key={idx} className="bg-white border border-ink-black p-2 space-y-1.5 rounded relative text-xs">
                  <div className="flex justify-between items-center">
                    <span className="font-bold text-[10px] text-slate-500">Example {idx + 1}:</span>
                    {newFileExamples.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeExample(idx)}
                        className="text-[10px] text-red-600 hover:text-red-800 font-bold cursor-pointer"
                      >
                        ✕
                      </button>
                    )}
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <input
                      type="text"
                      value={ex.input}
                      onChange={(e) => updateExample(idx, 'input', e.target.value)}
                      placeholder="Input: nums = [2,7,11,15], target = 9"
                      className="bg-slate-50 border border-slate-300 p-1 text-[11px] font-mono outline-none"
                    />
                    <input
                      type="text"
                      value={ex.output}
                      onChange={(e) => updateExample(idx, 'output', e.target.value)}
                      placeholder="Output: [0,1]"
                      className="bg-slate-50 border border-slate-300 p-1 text-[11px] font-mono outline-none"
                    />
                  </div>
                  <input
                    type="text"
                    value={ex.explanation || ''}
                    onChange={(e) => updateExample(idx, 'explanation', e.target.value)}
                    placeholder="Explanation (Optional): Because nums[0] + nums[1] == 9, we return [0, 1]."
                    className="bg-slate-50 border border-slate-300 p-1 text-[11px] outline-none w-full"
                  />
                </div>
              ))}
            </div>

            {/* Row 5: Constraints */}
            <div className="flex flex-col gap-1">
              <label className="text-[10px] font-bold text-slate-600 uppercase">Constraints (1 per line):</label>
              <textarea
                value={newFileConstraints}
                onChange={(e) => setNewFileConstraints(e.target.value)}
                placeholder="2 <= nums.length <= 10^4&#10;-10^9 <= nums[i] <= 10^9&#10;Only one valid answer exists."
                className="bg-white border-2 border-ink-black p-2 text-xs font-mono outline-none focus:ring-1 focus:ring-primary-purple h-16 resize-y leading-snug"
              />
            </div>

            {/* Row 6: Solutions & Methods*/}
            <div className="border-2 border-ink-black bg-[#faf6eb] p-3 rounded space-y-3">
              <div className="flex flex-wrap items-center justify-between gap-2 border-b-2 border-ink-black pb-2">
                <div className="flex items-center gap-2">
                  <span className="text-xs">💡</span>
                  <label className="text-[11px] font-bold font-arcade uppercase tracking-wide">
                    Solutions & Methods ({solutions.length})
                  </label>
                  <span className="text-[9px] bg-slate-200 text-slate-700 font-mono px-1.5 py-0.5 rounded border border-slate-300">
                    Visible on the Solutions tab during review
                  </span>
                </div>
                <button
                  type="button"
                  onClick={addSolution}
                  className="px-2.5 py-1 text-[9px] font-bold font-arcade bg-[#ffe24c] hover:bg-yellow-300 border-2 border-ink-black shadow-[1px_1px_0px_#1E293B] cursor-pointer flex items-center gap-1"
                >
                  <span>+</span> ADD METHOD
                </button>
              </div>

              {/* Solution Tabs */}
              <div className="flex flex-wrap gap-1.5">
                {solutions.map((sol, idx) => (
                  <button
                    key={sol.id || idx}
                    type="button"
                    onClick={() => setActiveSolutionIdx(idx)}
                    className={`px-2.5 py-1 text-[10px] font-bold border-2 border-ink-black flex items-center gap-1.5 cursor-pointer rounded transition-colors ${activeSolutionIdx === idx
                      ? 'bg-primary-purple text-white shadow-[1px_1px_0px_#1E293B]'
                      : 'bg-white text-slate-700 hover:bg-slate-100'
                      }`}
                  >
                    <span>{sol.name || `Method ${idx + 1}`}</span>
                    {sol.is_optimal && (
                      <span className={`text-[8px] px-1 py-0.2 rounded font-mono uppercase font-black ${activeSolutionIdx === idx ? 'bg-amber-400 text-ink-black' : 'bg-amber-200 text-amber-900'
                        }`}>
                        ★ Optimal
                      </span>
                    )}
                  </button>
                ))}
              </div>

              {/* Active Solution Fields */}
              <div className="bg-white border-2 border-ink-black p-3 rounded space-y-2.5">
                <div className="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 pb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-bold text-slate-500">Method #{activeSolutionIdx + 1}:</span>
                    <input
                      type="text"
                      value={activeSolution.name}
                      onChange={(e) => updateActiveSolution({ name: e.target.value })}
                      placeholder="e.g. Hash Map Lookup or Two Pointers"
                      className="border border-ink-black px-2 py-0.5 text-xs font-bold bg-[#fffdf5] outline-none focus:ring-1 focus:ring-primary-purple w-56"
                    />
                  </div>

                  <div className="flex items-center gap-3">
                    <label className="flex items-center gap-1.5 text-[10px] font-bold text-amber-800 cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={Boolean(activeSolution.is_optimal)}
                        onChange={(e) => updateActiveSolution({ is_optimal: e.target.checked })}
                        className="w-3.5 h-3.5 accent-amber-500 cursor-pointer"
                      />
                      <span>Mark as Optimal Solution</span>
                    </label>

                    {solutions.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeSolution(activeSolutionIdx)}
                        className="text-[10px] font-bold text-red-600 hover:text-red-800 border border-red-300 hover:border-red-500 px-2 py-0.5 rounded cursor-pointer"
                      >
                        Remove Method
                      </button>
                    )}
                  </div>
                </div>

                {/* Method Pattern and Big-O */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-bold text-slate-600 uppercase">Pattern / Technique:</label>
                    <input
                      type="text"
                      list="pattern-suggestions"
                      value={activeSolution.pattern || ''}
                      onChange={(e) => updateActiveSolution({ pattern: e.target.value })}
                      placeholder="e.g. Arrays & Hashing"
                      className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-medium"
                    />
                    <datalist id="pattern-suggestions">
                      {COMMON_PATTERNS.map(p => (
                        <option key={p} value={p} />
                      ))}
                    </datalist>
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-bold text-slate-600 uppercase">Method Time Complexity:</label>
                    <input
                      type="text"
                      value={activeSolution.time_complexity || ''}
                      onChange={(e) => updateActiveSolution({ time_complexity: e.target.value })}
                      placeholder="e.g. O(N)"
                      className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-semibold"
                    />
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-[10px] font-bold text-slate-600 uppercase">Method Space Complexity:</label>
                    <input
                      type="text"
                      value={activeSolution.space_complexity || ''}
                      onChange={(e) => updateActiveSolution({ space_complexity: e.target.value })}
                      placeholder="e.g. O(1)"
                      className="bg-[#fafafa] border border-ink-black p-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-semibold"
                    />
                  </div>
                </div>

                {/* Method Intuition */}
                <div className="flex flex-col gap-1">
                  <div className="flex justify-between items-center">
                    <label className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
                      <span>💡</span> Intuition / Mental Model:
                    </label>
                    <button
                      type="button"
                      onClick={handleGenerateIntuition}
                      disabled={loadingIntuition}
                      className="text-[8px] font-arcade font-bold px-2 py-0.5 border border-ink-black bg-[#ffe24c] hover:bg-yellow-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer"
                    >
                      <span>✦</span> {loadingIntuition ? 'GENERATING...' : 'AI INTUITION'}
                    </button>
                  </div>
                  <textarea
                    value={activeSolution.explanation || ''}
                    onChange={(e) => updateActiveSolution({ explanation: e.target.value })}
                    placeholder="Explain how this specific method works, key data structures, invariants, or edge cases..."
                    className="bg-[#fafafa] border border-ink-black p-2 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-sans h-20 resize-y leading-relaxed"
                  />
                </div>

                {/* Method Python Code */}
                <div className="flex flex-col gap-1">
                  <div className="flex justify-between items-center">
                    <label className="text-[10px] font-bold text-slate-600 uppercase flex items-center gap-1">
                      <span>🐍</span> Method Python Code:
                    </label>
                    <button
                      type="button"
                      onClick={handleFormatCode}
                      disabled={loadingComments || !activeSolution.code?.trim()}
                      className="text-[8px] font-arcade font-bold px-2 py-0.5 border border-ink-black bg-[#a7f3d0] hover:bg-emerald-300 disabled:opacity-50 flex items-center gap-1 cursor-pointer text-emerald-950"
                    >
                      <span>✨</span> {loadingComments ? 'FORMATTING...' : 'ADD EMOJI COMMENTS'}
                    </button>
                  </div>
                  <textarea
                    value={activeSolution.code || ''}
                    onChange={(e) => updateActiveSolution({ code: e.target.value })}
                    placeholder="def twoSum(nums: list[int], target: int) -> list[int]:&#10;    # 1. 🗺️ Initialize lookup map&#10;    seen = {}&#10;    ...&#10;    return []"
                    className="bg-slate-900 text-[#4ADE80] font-mono p-2.5 border-2 border-ink-black rounded outline-none h-44 text-xs leading-relaxed resize-y w-full"
                  />
                </div>
              </div>
            </div>
          </>
        ) : (
          /* Real-time Google Docs Preview */
          <div className="bg-white border-2 border-ink-black p-6 rounded shadow-sm font-sans space-y-4 text-slate-800">
            <div className="border-b pb-2">
              <span className="text-[10px] font-mono uppercase bg-purple-100 text-purple-800 px-2 py-0.5 rounded font-bold">
                Google Doc Preview (Exact formatting preview)
              </span>
            </div>

            {/* Title */}
            <h1 className="text-xl font-bold text-slate-900">
              {newFileProblemNumber ? `${newFileProblemNumber}. ` : ''}{newFileName || 'Problem Title'}
            </h1>

            {/* Difficulty Badge */}
            <div>
              <span className={`text-xs font-bold px-2.5 py-0.5 rounded ${newFileDifficulty === 'Easy'
                ? 'bg-emerald-100 text-[#137c36]'
                : newFileDifficulty === 'Medium'
                  ? 'bg-amber-100 text-[#c06100]'
                  : 'bg-rose-100 text-[#c5221f]'
                }`}>
                {newFileDifficulty}
              </span>
            </div>

            {/* Description */}
            {newFileDescription && (
              <div className="text-xs text-slate-700 leading-relaxed whitespace-pre-wrap">
                {newFileDescription}
              </div>
            )}

            {/* Examples */}
            {newFileExamples.some(ex => ex.input.trim() || ex.output.trim()) && (
              <div className="space-y-3 pt-2">
                {newFileExamples.map((ex, i) => (
                  <div key={i} className="text-xs space-y-1">
                    <div className="font-bold text-slate-800">Example {i + 1}:</div>
                    {ex.input && (
                      <div>
                        <span className="text-slate-600">Input: </span>
                        <span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.input}</span>
                      </div>
                    )}
                    {ex.output && (
                      <div>
                        <span className="text-slate-600">Output: </span>
                        <span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.output}</span>
                      </div>
                    )}
                    {ex.explanation && (
                      <div>
                        <span className="text-slate-600">Explanation: </span>
                        <span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{ex.explanation}</span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}

            {/* Constraints */}
            {newFileConstraints && (
              <div className="space-y-1.5 pt-2">
                <div className="font-bold text-xs text-slate-800">Constraints:</div>
                <ul className="list-disc pl-5 text-xs space-y-1">
                  {newFileConstraints.split('\n').filter(Boolean).map((c, i) => (
                    <li key={i}>
                      <span className="bg-[#d9d9d9] font-mono px-1.5 py-0.5 rounded text-[11px]">{c.replace(/^[•\-*]\s*/, '')}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* Target Optimal Complexities */}
            <div className="p-2.5 bg-slate-50 border border-slate-200 rounded space-y-1 text-xs">
              <div className="font-bold text-slate-700">Target Optimal Complexities (Active Recall Shielded on Review):</div>
              <div className="flex gap-4 font-mono text-slate-900">
                <span>Time: {newFileOptimalTime}</span>
                <span>Space: {newFileOptimalSpace}</span>
              </div>
            </div>

            {/* Methods & Solutions List */}
            <div className="pt-3 space-y-4">
              <div className="font-bold text-sm text-slate-900 border-b pb-1">
                Solutions & Methods ({solutions.length})
              </div>
              {solutions.map((sol, i) => (
                <div key={sol.id || i} className="border border-slate-300 p-3 rounded space-y-2 bg-[#fdfdfd]">
                  <div className="flex items-center justify-between">
                    <span className="font-bold text-xs text-slate-900">
                      {sol.name || `Method ${i + 1}`}
                    </span>
                    <div className="flex items-center gap-1.5">
                      {sol.is_optimal && (
                        <span className="text-[9px] bg-amber-100 text-amber-800 font-bold px-1.5 py-0.5 rounded border border-amber-300">
                          ★ Optimal
                        </span>
                      )}
                      <span className="text-[9px] bg-purple-100 text-primary-purple font-bold px-1.5 py-0.5 rounded border border-purple-200">
                        {sol.pattern || 'Standard'}
                      </span>
                    </div>
                  </div>

                  <div className="flex gap-4 text-xs font-mono text-slate-600">
                    <span>T: {sol.time_complexity || 'O(?)'}</span>
                    <span>S: {sol.space_complexity || 'O(?)'}</span>
                  </div>

                  {sol.explanation && (
                    <div className="text-xs text-slate-700 leading-relaxed whitespace-pre-wrap bg-slate-50 p-2 rounded">
                      {sol.explanation}
                    </div>
                  )}

                  {sol.code && (
                    <div className="bg-[#f8fafc] border border-slate-200 p-2.5 rounded font-mono text-[11px] leading-relaxed text-slate-900 overflow-x-auto whitespace-pre">
                      {sol.code}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Bottom Footer & Submit */}
      <div className="p-3 bg-[#f0e6c8] border-t-2 border-ink-black flex flex-wrap items-center justify-between gap-2 shrink-0">
        {/* Sync Checkbox (hide in edit mode) */}
        {!isEditMode ? (
          <label className="flex items-center gap-2 text-xs font-bold text-slate-700 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={syncToGDoc}
              onChange={(e) => setSyncToGDoc(e.target.checked)}
              className="w-4 h-4 accent-primary-purple cursor-pointer"
            />
            <span>Format & Sync to Google Doc</span>
          </label>
        ) : (
          <div className="text-[11px] text-slate-600 font-mono flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-primary-purple inline-block"></span>
            Editing #{initialProblem?.problem_number ?? '—'} {initialProblem?.name}
          </div>
        )}

        {/* Action Buttons */}
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onClose}
            className="px-3 py-1.5 bg-white hover:bg-slate-50 border-2 border-ink-black text-xs font-bold cursor-pointer"
          >
            CANCEL
          </button>
          <button
            type="submit"
            disabled={creating}
            className="px-4 py-1.5 bg-primary-purple hover:bg-purple-600 text-white font-arcade text-[10px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_#1E293B] active:translate-y-0.5 active:shadow-none cursor-pointer flex items-center gap-1.5"
          >
            <span>{isEditMode ? '✏️' : '💾'}</span>{' '}
            {creating
              ? isEditMode
                ? 'UPDATING...'
                : 'SAVING...'
              : isEditMode
                ? 'UPDATE PROBLEM'
                : 'SAVE SOLUTION'}
          </button>
        </div>
      </div>
    </form>
  );
}