File size: 26,181 Bytes
4e7644b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * ProjectSelectModal
 *
 * Shown when the user first enters Coding Mode (or clicks "Switch Project").
 * Four tabs:
 *   1. Default Workspace  – use the agent's default workspace_dir
 *   2. Clone Repository   – git clone a public URL with SSE progress
 *   3. Open Local Path    – enter an absolute path
 *   4. New Project        – create an empty dir + git init
 */

import { useState, useRef, useEffect } from "react";
import { Modal, Tabs, Input, Button, Alert, List } from "antd";
import {
  ChevronRight,
  Eye,
  EyeOff,
  Folder,
  FolderOpen,
  FolderSymlink,
  GitBranch,
  HardDrive,
  Home,
  PlusCircle,
  RotateCcw,
  X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import {
  projectDirectoryApi,
  type BrowseDirsResponse,
  type ProjectListItem,
} from "../../api/modules/projectDirectory";
import { useProjectDir } from "../../stores/projectDirectoryStore";
import styles from "./index.module.less";

interface ProjectSelectModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: (path: string | null) => void;
}

// ---------------------------------------------------------------------------
// Clone progress event
// ---------------------------------------------------------------------------

interface CloneEvent {
  type: "log" | "done" | "error";
  line?: string;
  path?: string;
  name?: string;
  detail?: string;
}

// ---------------------------------------------------------------------------
// Tab: Workspace
// ---------------------------------------------------------------------------

function WorkspaceTab({
  workspaceDir,
  onSelect,
}: {
  workspaceDir: string | null;
  onSelect: (path: null) => void;
}) {
  const { t } = useTranslation();
  return (
    <div className={styles.tabContent}>
      <Alert
        type="info"
        showIcon
        message={t("codingMode.workspaceDesc")}
        className={styles.workspaceAlert}
      />
      {workspaceDir && (
        <div className={styles.currentInfo}>
          <span className={styles.currentLabel}>
            {t("codingMode.workingDir")}:
          </span>
          <code className={styles.currentPath}>{workspaceDir}</code>
        </div>
      )}
      <Button
        type="primary"
        onClick={() => onSelect(null)}
        className={styles.actionBtn}
      >
        {t("codingMode.confirmBtn")}
      </Button>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Tab: Clone
// ---------------------------------------------------------------------------

function CloneTab({ onDone }: { onDone: (path: string) => void }) {
  const { t } = useTranslation();
  const [url, setUrl] = useState("");
  const [name, setName] = useState("");
  const [cloning, setCloning] = useState(false);
  const [logs, setLogs] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);
  const logEndRef = useRef<HTMLDivElement>(null);

  const handleClone = async () => {
    if (!url.trim()) return;
    setCloning(true);
    setLogs([]);
    setError(null);
    try {
      const res = await projectDirectoryApi.cloneStream(
        url.trim(),
        name.trim() || undefined,
      );
      const reader = res.body?.getReader();
      if (!reader) throw new Error("No response body");

      const decoder = new TextDecoder();
      let buf = "";
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += decoder.decode(value, { stream: true });
        const parts = buf.split("\n\n");
        buf = parts.pop() ?? "";
        for (const part of parts) {
          const line = part.startsWith("data: ") ? part.slice(6) : part;
          if (!line.trim()) continue;
          try {
            const evt: CloneEvent = JSON.parse(line);
            if (evt.type === "log" && evt.line) {
              setLogs((prev) => {
                const next = [...prev, evt.line!];
                setTimeout(() => logEndRef.current?.scrollIntoView(), 0);
                return next;
              });
            } else if (evt.type === "done" && evt.path) {
              setCloning(false);
              onDone(evt.path);
              return;
            } else if (evt.type === "error") {
              setError(evt.detail ?? "Unknown error");
              setCloning(false);
              return;
            }
          } catch {
            // ignore non-JSON lines
          }
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
      setCloning(false);
    }
  };

  return (
    <div className={styles.tabContent}>
      <label className={styles.fieldLabel}>{t("codingMode.cloneUrl")}</label>
      <Input
        placeholder={t("codingMode.cloneUrlPlaceholder")}
        value={url}
        onChange={(e) => setUrl(e.target.value)}
        disabled={cloning}
        className={styles.input}
      />
      <label className={styles.fieldLabel}>{t("codingMode.cloneName")}</label>
      <Input
        placeholder={t("codingMode.cloneNamePlaceholder")}
        value={name}
        onChange={(e) => setName(e.target.value)}
        disabled={cloning}
        className={styles.input}
      />
      {error && (
        <Alert type="error" message={error} className={styles.alert} showIcon />
      )}
      {logs.length > 0 && (
        <div className={styles.logBox}>
          {logs.map((l, i) => (
            // eslint-disable-next-line react/no-array-index-key
            <div key={i} className={styles.logLine}>
              {l}
            </div>
          ))}
          <div ref={logEndRef} />
        </div>
      )}
      <Button
        type="primary"
        onClick={() => void handleClone()}
        loading={cloning}
        disabled={!url.trim()}
        className={styles.actionBtn}
      >
        {cloning ? t("codingMode.cloning") : t("codingMode.cloneBtn")}
      </Button>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helpers for LocalPathTab: read a dropped directory recursively, skipping
// common large / generated directories so we don't upload gigabytes.
// ---------------------------------------------------------------------------

const SKIP_SEGMENTS = new Set([
  "node_modules",
  ".git",
  ".next",
  "dist",
  "build",
  "__pycache__",
  ".cache",
  ".venv",
  "venv",
  ".mypy_cache",
  ".tox",
]);

function shouldSkipPath(path: string): boolean {
  return path.split("/").some((seg) => SKIP_SEGMENTS.has(seg));
}

async function readDirFiltered(
  entry: FileSystemDirectoryEntry,
): Promise<Array<{ path: string; file: File }>> {
  const result: Array<{ path: string; file: File }> = [];
  const reader = entry.createReader();
  const readBatch = (): Promise<FileSystemEntry[]> =>
    new Promise((resolve, reject) => reader.readEntries(resolve, reject));
  let batch: FileSystemEntry[];
  do {
    batch = await readBatch();
    for (const item of batch) {
      if (shouldSkipPath(item.fullPath)) continue;
      if (item.isFile) {
        const file = await new Promise<File>((resolve, reject) =>
          (item as FileSystemFileEntry).file(resolve, reject),
        );
        result.push({ path: item.fullPath.replace(/^\//, ""), file });
      } else if (item.isDirectory) {
        const sub = await readDirFiltered(item as FileSystemDirectoryEntry);
        result.push(...sub);
      }
    }
  } while (batch.length > 0);
  return result;
}

type FolderSelection = {
  name: string;
  entries: Array<{ path: string; file: File }>;
};

// ---------------------------------------------------------------------------
// Tab: Open Local Path
// ---------------------------------------------------------------------------

function LocalPathTab({ onSelect }: { onSelect: (path: string) => void }) {
  const { t } = useTranslation();
  const [localSel, setLocalSel] = useState<FolderSelection | null>(null);
  const [dragOver, setDragOver] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const dirInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const prevent = (e: DragEvent) => e.preventDefault();
    const clear = () => setDragOver(false);
    document.addEventListener("dragover", prevent);
    document.addEventListener("drop", prevent);
    window.addEventListener("dragend", clear);
    window.addEventListener("drop", clear);
    return () => {
      document.removeEventListener("dragover", prevent);
      document.removeEventListener("drop", prevent);
      window.removeEventListener("dragend", clear);
      window.removeEventListener("drop", clear);
    };
  }, []);

  // System folder picker — same hidden input pattern as plugin install modal
  const handleDirPicked = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []).filter(
      (f) => !shouldSkipPath(f.webkitRelativePath),
    );
    if (files.length === 0) return;
    const folderName = files[0].webkitRelativePath.split("/")[0];
    setLocalSel({
      name: folderName,
      entries: files.map((f) => ({ path: f.webkitRelativePath, file: f })),
    });
    e.target.value = "";
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);
  };

  const handleDrop = async (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);
    const items = Array.from(e.dataTransfer.items);
    if (items.length === 0) return;
    const entry = items[0].webkitGetAsEntry();
    if (!entry?.isDirectory) return;
    try {
      const entries = await readDirFiltered(entry as FileSystemDirectoryEntry);
      setLocalSel({ name: entry.name, entries });
    } catch {
      setError(t("codingMode.dropFailed"));
    }
  };

  const handleImport = async () => {
    if (!localSel) return;
    setLoading(true);
    setError(null);
    try {
      const { default: JSZip } = await import("jszip");
      const zip = new JSZip();
      for (const { path, file } of localSel.entries) {
        zip.file(path, file);
      }
      const blob = await zip.generateAsync({ type: "blob" });
      const zipFile = new File([blob], `${localSel.name}.zip`, {
        type: "application/zip",
      });
      const res = await projectDirectoryApi.uploadZip(zipFile, localSel.name);
      onSelect(res.path);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Import failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.tabContent}>
      <Alert
        type="info"
        showIcon
        message={t("codingMode.importCopyDesc")}
        className={styles.alert}
      />
      <input
        ref={dirInputRef}
        type="file"
        // @ts-expect-error webkitdirectory is not in standard HTML typings
        webkitdirectory=""
        multiple
        style={{ display: "none" }}
        onChange={handleDirPicked}
      />

      {localSel ? (
        <>
          <div className={styles.selectionCard}>
            <FolderOpen size={18} />
            <span className={styles.selectionName}>{localSel.name}</span>
            <Button
              type="text"
              size="small"
              icon={<X size={14} />}
              onClick={() => {
                setLocalSel(null);
                setError(null);
              }}
            />
          </div>
          <Alert
            type="warning"
            showIcon
            message={t("codingMode.importCopyNote")}
            className={styles.alert}
          />
          {error && (
            <Alert
              type="error"
              message={error}
              showIcon
              className={styles.alert}
            />
          )}
          <Button
            type="primary"
            block
            loading={loading}
            onClick={() => void handleImport()}
          >
            {loading ? t("codingMode.importing") : t("codingMode.openBtn")}
          </Button>
        </>
      ) : (
        <div
          className={`${styles.dropZone} ${
            dragOver ? styles.dropZoneActive : ""
          }`}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={(e) => void handleDrop(e)}
          onClick={() => dirInputRef.current?.click()}
          role="button"
          tabIndex={0}
          onKeyDown={(e) => e.key === "Enter" && dirInputRef.current?.click()}
        >
          <FolderOpen size={36} strokeWidth={1.2} className={styles.dropIcon} />
          <span className={styles.dropPrimary}>
            {t("codingMode.dropPrimary")}
          </span>
          <span className={styles.dropSecondary}>
            {t("codingMode.dropSecondary")}
          </span>
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Tab: Open Existing Directory (server-side file browser, no copy)
// ---------------------------------------------------------------------------

function OpenDirTab({ onSelect }: { onSelect: (path: string) => void }) {
  const { t } = useTranslation();
  const [browsePath, setBrowsePath] = useState<string>("~");
  const [data, setData] = useState<BrowseDirsResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showHidden, setShowHidden] = useState(false);
  const listRef = useRef<HTMLDivElement>(null);
  const navSeq = useRef(0);

  const navigate = (path: string) => {
    const seq = ++navSeq.current;
    setBrowsePath(path);
    setLoading(true);
    setError(null);
    projectDirectoryApi
      .browseDirs(path, showHidden)
      .then((res) => {
        if (seq !== navSeq.current) return;
        setData(res);
        listRef.current?.scrollTo(0, 0);
      })
      .catch((err: unknown) => {
        if (seq !== navSeq.current) return;
        setError(err instanceof Error ? err.message : String(err));
      })
      .finally(() => {
        if (seq === navSeq.current) setLoading(false);
      });
  };

  useEffect(() => {
    navigate("~");
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Re-fetch current directory when the hidden-folders toggle changes.
  // navSeq already discards stale responses, so unconditional re-fetch is safe.
  useEffect(() => {
    navigate(browsePath);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showHidden]);

  const breadcrumbParts = data?.current.split("/").filter(Boolean) ?? [];

  return (
    <div className={styles.tabContent}>
      <Alert
        type="info"
        showIcon
        message={t("codingMode.openDirDesc")}
        className={styles.alert}
      />

      {/* Quick-access shortcuts */}
      <div className={styles.browseShortcuts}>
        <Button
          size="small"
          type="text"
          icon={<Home size={13} />}
          onClick={() => navigate("~")}
        >
          {t("codingMode.openDirHome")}
        </Button>
        <Button
          size="small"
          type="text"
          icon={<RotateCcw size={13} />}
          onClick={() => navigate(browsePath)}
        >
          {t("codingMode.openDirRefresh")}
        </Button>
        <Button
          size="small"
          type={showHidden ? "primary" : "text"}
          icon={showHidden ? <Eye size={13} /> : <EyeOff size={13} />}
          onClick={() => setShowHidden((v) => !v)}
        >
          {t("codingMode.openDirHiddenFolders")}
        </Button>
      </div>

      {/* Breadcrumb */}
      {data && (
        <div className={styles.browseBreadcrumb}>
          <span
            className={styles.breadcrumbSeg}
            onClick={() => navigate("/")}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                navigate("/");
              }
            }}
          >
            /
          </span>
          {breadcrumbParts.map((seg, i) => {
            const segPath = "/" + breadcrumbParts.slice(0, i + 1).join("/");
            const isLast = i === breadcrumbParts.length - 1;
            return (
              <span key={segPath} className={styles.breadcrumbItem}>
                <ChevronRight size={11} className={styles.breadcrumbSep} />
                <span
                  className={`${styles.breadcrumbSeg} ${
                    isLast ? styles.breadcrumbCurrent : ""
                  }`}
                  onClick={() => !isLast && navigate(segPath)}
                  role={isLast ? undefined : "button"}
                  tabIndex={isLast ? undefined : 0}
                  onKeyDown={(e) => {
                    if (!isLast && (e.key === "Enter" || e.key === " ")) {
                      e.preventDefault();
                      navigate(segPath);
                    }
                  }}
                >
                  {seg}
                </span>
              </span>
            );
          })}
        </div>
      )}

      {/* Directory listing */}
      <div className={styles.browseList} ref={listRef}>
        {loading && (
          <div className={styles.browseEmpty}>
            {t("codingMode.openDirLoading")}
          </div>
        )}
        {error && (
          <Alert
            type="error"
            message={error}
            showIcon
            className={styles.alert}
          />
        )}
        {!loading && !error && data && (
          <>
            {data.parent && (
              <div
                className={styles.browseItem}
                onClick={() => navigate(data.parent!)}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    navigate(data.parent!);
                  }
                }}
              >
                <Folder size={15} className={styles.browseItemIcon} />
                <span className={styles.browseItemName}>..</span>
              </div>
            )}
            {data.dirs.length === 0 && !data.parent && (
              <div className={styles.browseEmpty}>
                {t("codingMode.openDirEmpty")}
              </div>
            )}
            {data.dirs.map((dir) => (
              <div
                key={dir.path}
                className={styles.browseItem}
                onClick={() => navigate(dir.path)}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    navigate(dir.path);
                  }
                }}
              >
                <Folder size={15} className={styles.browseItemIcon} />
                <span className={styles.browseItemName}>{dir.name}</span>
                <ChevronRight size={13} className={styles.browseItemChevron} />
              </div>
            ))}
          </>
        )}
      </div>

      {/* Confirm button */}
      {data && !loading && data.selectable !== false && (
        <Button
          type="primary"
          onClick={() => onSelect(data.current)}
          className={styles.actionBtn}
        >
          {t("codingMode.openDirBtn")}
        </Button>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Tab: New Project
// ---------------------------------------------------------------------------

function NewProjectTab({ onDone }: { onDone: (path: string) => void }) {
  const { t } = useTranslation();
  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleCreate = async () => {
    if (!name.trim()) return;
    setLoading(true);
    setError(null);
    try {
      const res = await projectDirectoryApi.create(name.trim());
      onDone(res.path);
    } catch (err: unknown) {
      const detail =
        err instanceof Error ? err.message : "Failed to create project";
      setError(detail);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.tabContent}>
      <label className={styles.fieldLabel}>{t("codingMode.newName")}</label>
      <Input
        placeholder={t("codingMode.newNamePlaceholder")}
        value={name}
        onChange={(e) => setName(e.target.value)}
        className={styles.input}
      />
      {error && (
        <Alert type="error" message={error} className={styles.alert} showIcon />
      )}
      <Button
        type="primary"
        onClick={() => void handleCreate()}
        loading={loading}
        disabled={!name.trim()}
        className={styles.actionBtn}
      >
        {t("codingMode.createBtn")}
      </Button>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Recent Projects list (shown below tabs)
// ---------------------------------------------------------------------------

function RecentProjects({
  projects,
  onSelect,
}: {
  projects: ProjectListItem[];
  onSelect: (path: string) => void;
}) {
  if (projects.length === 0) return null;
  return (
    <div className={styles.recentWrap}>
      <div className={styles.recentTitle}>Recent</div>
      <List
        size="small"
        dataSource={projects}
        renderItem={(item) => (
          <List.Item
            className={`${styles.recentItem} ${
              item.is_active ? styles.recentItemActive : ""
            }`}
            onClick={() => onSelect(item.path)}
          >
            <GitBranch size={13} className={styles.recentIcon} />
            <span className={styles.recentName}>{item.name}</span>
            <span className={styles.recentPath}>{item.path}</span>
          </List.Item>
        )}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main Modal
// ---------------------------------------------------------------------------

export default function ProjectSelectModal({
  open,
  onClose,
  onConfirm,
}: ProjectSelectModalProps) {
  const { t } = useTranslation();
  const { setProjectDir } = useProjectDir();
  const [projects, setProjects] = useState<ProjectListItem[]>([]);
  const [activeTab, setActiveTab] = useState("workspace");
  // The agent's default workspace directory (fetched from backend)
  const [workspaceDir, setWorkspaceDir] = useState<string | null>(null);

  const handleOpen = () => {
    projectDirectoryApi
      .list()
      .then(setProjects)
      .catch(() => undefined);
    // GET returns workspace_dir field alongside the active project
    projectDirectoryApi
      .get()
      .then((info) => {
        if (info.workspace_dir) setWorkspaceDir(info.workspace_dir);
      })
      .catch(() => undefined);
  };

  const handleConfirm = async (path: string | null) => {
    if (path !== undefined) {
      // For workspace default (path === null), explicitly reset on backend too
      if (path === null) {
        try {
          await projectDirectoryApi.set(null);
        } catch {
          // ignore – best effort
        }
      }
      setProjectDir(path);
      onConfirm(path);
    }
  };

  const handlePathSelected = async (path: string) => {
    try {
      await projectDirectoryApi.set(path);
    } catch {
      // best effort
    }
    setProjectDir(path);
    onConfirm(path);
  };

  const handleCloneDone = async (path: string) => {
    // After clone, the server already set the active project; update store.
    setProjectDir(path);
    onConfirm(path);
  };

  const handleLocalDone = (path: string) => {
    setProjectDir(path);
    onConfirm(path);
  };

  const handleNewDone = (path: string) => {
    setProjectDir(path);
    onConfirm(path);
  };

  const tabItems = [
    {
      key: "workspace",
      label: (
        <span className={styles.tabLabel}>
          <HardDrive size={13} />
          {t("codingMode.tabWorkspace")}
        </span>
      ),
      children: (
        <WorkspaceTab
          workspaceDir={workspaceDir}
          onSelect={() => void handleConfirm(null)}
        />
      ),
    },
    {
      key: "clone",
      label: (
        <span className={styles.tabLabel}>
          <GitBranch size={13} />
          {t("codingMode.tabClone")}
        </span>
      ),
      children: <CloneTab onDone={(p) => void handleCloneDone(p)} />,
    },
    {
      key: "opendir",
      label: (
        <span className={styles.tabLabel}>
          <FolderSymlink size={13} />
          {t("codingMode.tabOpenDir")}
        </span>
      ),
      children: <OpenDirTab onSelect={(p) => void handlePathSelected(p)} />,
    },
    {
      key: "local",
      label: (
        <span className={styles.tabLabel}>
          <FolderOpen size={13} />
          {t("codingMode.tabLocal")}
        </span>
      ),
      children: <LocalPathTab onSelect={handleLocalDone} />,
    },
    {
      key: "new",
      label: (
        <span className={styles.tabLabel}>
          <PlusCircle size={13} />
          {t("codingMode.tabNew")}
        </span>
      ),
      children: <NewProjectTab onDone={handleNewDone} />,
    },
  ];

  return (
    <Modal
      open={open}
      title={t("codingMode.selectProject")}
      onCancel={onClose}
      footer={null}
      width={560}
      afterOpenChange={(isOpen) => isOpen && handleOpen()}
      className={styles.modal}
    >
      <p className={styles.desc}>{t("codingMode.selectProjectDesc")}</p>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="small"
      />
      <RecentProjects
        projects={projects}
        onSelect={(p) => void handlePathSelected(p)}
      />
    </Modal>
  );
}