File size: 36,876 Bytes
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92316a
 
eafc3f5
b1b7091
 
b92316a
 
eafc3f5
 
 
 
 
126f77a
 
 
 
 
 
 
 
 
b1b7091
 
 
 
b92316a
 
 
 
 
b1b7091
 
 
b92316a
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
b1b7091
 
 
b92316a
 
 
 
126f77a
 
 
eafc3f5
b92316a
eafc3f5
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
 
 
 
 
 
 
 
b92316a
 
126f77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
b92316a
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
 
 
b92316a
b1b7091
 
 
b92316a
b1b7091
 
 
eafc3f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92316a
126f77a
 
 
b92316a
126f77a
 
 
 
b92316a
b1b7091
 
 
 
126f77a
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
b92316a
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
126f77a
b1b7091
b92316a
b1b7091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
b92316a
 
 
 
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
 
b92316a
 
b1b7091
 
eafc3f5
b92316a
 
 
eafc3f5
b92316a
 
 
eafc3f5
b1b7091
b92316a
 
 
 
 
b1b7091
b92316a
 
 
 
b1b7091
b92316a
 
 
 
126f77a
b92316a
 
b1b7091
b92316a
126f77a
b92316a
 
 
 
 
 
 
 
126f77a
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
b92316a
 
b1b7091
b92316a
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
eafc3f5
b92316a
 
 
 
 
b1b7091
 
 
b92316a
b1b7091
 
 
 
eafc3f5
 
 
b92316a
eafc3f5
 
 
b92316a
eafc3f5
 
126f77a
b1b7091
 
 
 
 
b92316a
 
 
 
eafc3f5
 
 
 
 
 
 
 
 
b1b7091
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
eafc3f5
 
 
 
b1b7091
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1b7091
 
 
 
 
 
 
 
 
 
 
126f77a
 
 
 
 
b1b7091
 
126f77a
 
 
 
 
 
 
 
b1b7091
 
 
 
b92316a
 
b1b7091
 
 
 
 
 
 
 
 
 
126f77a
b1b7091
b92316a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126f77a
 
b1b7091
 
eafc3f5
 
 
 
b1b7091
eafc3f5
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
'use strict'

// ── SVG icon map ─────────────────────────────────────────────────────────────
const ICONS = {
  expo:     `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,
  android:  `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 16.5v2a1 1 0 002 0v-2M17 16.5v2a1 1 0 002 0v-2"/><rect x="5" y="8" width="14" height="11" rx="3"/><circle cx="9" cy="14" r="1" fill="currentColor" stroke="none"/><circle cx="15" cy="14" r="1" fill="currentColor" stroke="none"/><line x1="8.5" y1="8" x2="6" y2="4"/><line x1="15.5" y1="8" x2="18" y2="4"/></svg>`,
  adb:      `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 9 10 15 4 21"/><line x1="13" y1="21" x2="21" y2="21"/></svg>`,
  electron: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,
  nextjs:   `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L22 21H2L12 2z"/></svg>`,
  vite:     `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,
  scripts:  `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>`,
  npm:      `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,
}

// ── Page navigation ─────────────────────────────────────────────────────────
function showPage(name) {
  document.getElementById('page-home').classList.toggle('active', name === 'home')
  document.getElementById('page-run').classList.toggle('active',  name === 'run')
  const pageR2 = document.getElementById('page-r2')
  if (pageR2) pageR2.classList.toggle('active', name === 'r2')
  document.getElementById('page-support').classList.toggle('active', name === 'support')
  document.getElementById('tab-home').classList.toggle('active',  name === 'home')
  document.getElementById('tab-run').classList.toggle('active',   name === 'run')
  const tabR2 = document.getElementById('tab-r2')
  if (tabR2) tabR2.classList.toggle('active', name === 'r2')
  document.getElementById('support-btn').classList.toggle('active', name === 'support')

  if (name === 'run') {
    ensureTerminalInitialized()
  }

  if (name === 'run' && term && fitAddon) {
    requestAnimationFrame(() => {
      setTimeout(() => {
        fitAddon.fit()
        notifyPtyResize()
      }, 20)
    })
  }
}

// iframe pages call these parent functions
window.showView = showPage
window.r2OpenConfig = () => {}
window.r2OpenUpload = () => {}
window.r2OpenCloudflare = () => {}
window.r2GetStatus = async () => ({ ok: false, error: 'R2 moved to chahuadev-R2 app' })
window.r2Logout = async () => ({ ok: true })

// ── State ─────────────────────────────────────────────────────────────────────
let runningBtn = null
let mainRunning = false
let currentMainCmdKey = null
const popupRunningByCmd = new Map()
const cmdButtonByKey = new Map()
const GROUP_COLOR_CLASS = {
  expo: 'group-color-expo',
  android: 'group-color-android',
  adb: 'group-color-adb',
  electron: 'group-color-electron',
  nextjs: 'group-color-nextjs',
  vite: 'group-color-vite',
  scripts: 'group-color-scripts',
  npm: 'group-color-npm',
}

// ── Elements ──────────────────────────────────────────────────────────────────
const elGroups   = document.getElementById('cmd-groups')
const elOutput   = document.getElementById('term-output')
const elName     = document.getElementById('project-name')
const elPath     = document.getElementById('project-path')
const elBadge    = document.getElementById('type-badge')
const elKill     = document.getElementById('btn-kill')
const elClear    = document.getElementById('btn-clear')
const elStreamMode = document.getElementById('stream-mode')
const elDot      = document.getElementById('status-dot')
const elStatus   = document.getElementById('status-text')
const elRunning  = document.getElementById('running-label')
const elDevQuickPanel = document.getElementById('dev-quick-panel')
const elDevMainTools = document.getElementById('btn-dev-main-tools')
const elDevPopupTools = document.getElementById('btn-dev-popup-tools')
const elDevSecurityStatus = document.getElementById('btn-dev-security-status')
let term = null
let fitAddon = null
let resizeObserver = null
let terminalInitialized = false
let currentAppIsDev = false

function ensureTerminalInitialized() {
  if (terminalInitialized) return
  initTerminal()
  installTerminalShortcuts()
  terminalInitialized = true
}

function isTermNearBottom() {
  if (!term || !term.buffer || !term.buffer.active) return true
  const b = term.buffer.active
  return b.viewportY >= b.baseY
}

function initTerminal() {
  if (!elOutput || !window.Terminal) return

  const FitAddonCtor = (window.FitAddon && window.FitAddon.FitAddon) ? window.FitAddon.FitAddon : null
  term = new window.Terminal({
    cursorBlink: false,
    disableStdin: true,
    // Keep raw stream untouched and let xterm handle EOL visually.
    convertEol: true,
    scrollback: 100000,
    fontFamily: 'Cascadia Code, Consolas, monospace',
    fontSize: 12,
    theme: {
      background: '#080812',
      foreground: '#e6e8ff',
      red: '#ff6b6b',
      green: '#37d67a',
      yellow: '#ffd166',
      blue: '#6ea8ff',
      magenta: '#d291ff',
      cyan: '#5fe3ff',
      white: '#f4f6ff',
      brightRed: '#ff8a8a',
      brightGreen: '#69f0a6',
      brightYellow: '#ffe08a',
      brightBlue: '#9fc0ff',
      brightMagenta: '#e3b7ff',
      brightCyan: '#99f0ff'
    }
  })

  if (FitAddonCtor) {
    fitAddon = new FitAddonCtor()
    term.loadAddon(fitAddon)
  }

  term.open(elOutput)
  if (fitAddon) fitAddon.fit()
  notifyPtyResize()

  if (typeof ResizeObserver !== 'undefined') {
    resizeObserver = new ResizeObserver(() => {
      if (fitAddon) fitAddon.fit()
      notifyPtyResize()
    })
    resizeObserver.observe(elOutput)
  } else {
    window.addEventListener('resize', () => {
      if (fitAddon) fitAddon.fit()
      notifyPtyResize()
    })
  }
}

function notifyPtyResize() {
  if (!term || !api || typeof api.resizeProcPty !== 'function') return
  const cols = Number(term.cols || 0)
  const rows = Number(term.rows || 0)
  if (!cols || !rows) return
  api.resizeProcPty({ cols, rows })
}

async function copyTermSelection() {
  if (!term) return false
  const selected = term.getSelection()
  if (!selected) return false
  try {
    if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
      await navigator.clipboard.writeText(selected)
      return true
    }
    const ta = document.createElement('textarea')
    ta.value = selected
    ta.setAttribute('readonly', 'readonly')
    ta.style.position = 'fixed'
    ta.style.opacity = '0'
    document.body.appendChild(ta)
    ta.focus()
    ta.select()
    const ok = document.execCommand('copy')
    document.body.removeChild(ta)
    if (!ok) return false
    return true
  } catch {
    return false
  }
}

function installTerminalShortcuts() {
  if (elOutput) {
    const _onTermMousedown = () => {
      if (term && typeof term.focus === 'function') term.focus()
    }
    elOutput.addEventListener('mousedown', _onTermMousedown)
    window.addEventListener('beforeunload', () => {
      elOutput.removeEventListener('mousedown', _onTermMousedown)
    }, { once: true })
  }

  document.addEventListener('keydown', async (e) => {
    const isCtrlOrMeta = e.ctrlKey || e.metaKey
    if (!isCtrlOrMeta) return

    const key = String(e.key || '').toLowerCase()

    // Ctrl/Cmd + A => select all terminal output
    if (key === 'a') {
      if (!term) return
      e.preventDefault()
      term.selectAll()
      return
    }

    // Ctrl/Cmd + C (and Ctrl/Cmd + Shift + C) => copy selected terminal text
    if (key === 'c') {
      if (!term || !term.hasSelection()) return
      e.preventDefault()
      await copyTermSelection()
      term.clearSelection()
      return
    }

    // Ctrl/Cmd + L => clear terminal
    if (key === 'l') {
      if (!term) return
      e.preventDefault()
      term.reset()
    }
  })
}

const r2ConfigBackdrop = document.getElementById('r2-config-backdrop')
const r2UploadBackdrop = document.getElementById('r2-upload-backdrop')

function openModal(el) {
  if (!el) return
  el.classList.add('show')
}
function closeModal(el) {
  if (!el) return
  el.classList.remove('show')
}

function showSecurityBlockModal(payload = {}) {
  const backdrop = document.getElementById('security-block-backdrop')
  const msg = document.getElementById('security-block-message')
  const pathEl = document.getElementById('security-block-path')
  if (!backdrop || !msg || !pathEl) return

  const text = String(payload.message ||
    'SECURITY POLICY NOTICE\n\nThe selected folder is part of operating system directories.\nAccess is blocked to protect system integrity and user data.\n\nPlease select a project folder outside protected OS locations.')
  msg.textContent = text

  const selectedPath = String(payload.selectedPath || '')
  pathEl.textContent = selectedPath ? `Blocked path: ${selectedPath}` : ''
  openModal(backdrop)
}

function setTone(el, tone, text) {
  if (!el) return
  el.classList.remove('text-ok', 'text-warn', 'text-err', 'text-info')
  if (tone) el.classList.add(`text-${tone}`)
  if (typeof text === 'string') el.textContent = text
}

async function configureR2() {
  const status = await api.r2GetConfigStatus()
  const st = document.getElementById('r2-config-status')
  const accountHint = document.getElementById('r2-account-hint')
  const bucketHint = document.getElementById('r2-bucket-hint')
  const accessHint = document.getElementById('r2-access-hint')

  document.getElementById('r2-account-id').value = ''
  document.getElementById('r2-bucket').value = status.bucket || ''
  document.getElementById('r2-access-key').value = ''
  document.getElementById('r2-secret-key').value = ''

  if (!status.ok) {
    setTone(st, 'err', `Config unavailable: ${status.error}`)
  } else {
    setTone(st, 'info', status.hasConfig ? 'Config already exists. Fill all fields to update.' : 'No config found. Enter credentials to save.')
  }

  accountHint.textContent = status.accountIdMasked ? `Current: ${status.accountIdMasked}` : ''
  bucketHint.textContent = status.bucket ? `Current: ${status.bucket}` : ''
  accessHint.textContent = status.accessKeyMasked ? `Current: ${status.accessKeyMasked}` : ''

  openModal(r2ConfigBackdrop)
}

async function saveR2FromModal() {
  const accountId = document.getElementById('r2-account-id').value.trim()
  const bucket = document.getElementById('r2-bucket').value.trim()
  const accessKeyId = document.getElementById('r2-access-key').value.trim()
  const secretAccessKey = document.getElementById('r2-secret-key').value.trim()
  const st = document.getElementById('r2-config-status')

  if (!accountId || !bucket || !accessKeyId || !secretAccessKey) {
    setTone(st, 'err', 'All fields are required.')
    return
  }

  setTone(st, 'info', 'Validating credentials with R2...')
  const testRes = await api.r2TestConfig({ accountId, bucket, accessKeyId, secretAccessKey })
  if (!testRes.ok) {
    setTone(st, 'err', `Validation failed: ${testRes.error}`)
    return
  }

  const res = await api.r2SaveConfig({ accountId, bucket, accessKeyId, secretAccessKey })
  if (!res.ok) {
    setTone(st, 'err', `Save failed: ${res.error}`)
    return
  }

  closeModal(r2ConfigBackdrop)
}

async function clearSavedR2Config() {
  const st = document.getElementById('r2-config-status')
  const ok = window.confirm('Clear saved R2 credentials on this machine?')
  if (!ok) return

  const res = await api.r2ClearConfig()
  if (!res.ok) {
    setTone(st, 'err', `Clear failed: ${res.error}`)
    return
  }

  document.getElementById('r2-account-id').value = ''
  document.getElementById('r2-bucket').value = ''
  document.getElementById('r2-access-key').value = ''
  document.getElementById('r2-secret-key').value = ''
  document.getElementById('r2-account-hint').textContent = ''
  document.getElementById('r2-bucket-hint').textContent = ''
  document.getElementById('r2-access-hint').textContent = ''

  setTone(st, 'info', 'Saved config cleared.')
}

async function uploadDistToR2() {
  showPage('run')
  const st = document.getElementById('r2-upload-status')
  const list = document.getElementById('r2-target-list')
  const input = document.getElementById('r2-target-folder')
  const note = document.getElementById('r2-upload-note')

  st.textContent = ''
  list.innerHTML = ''

  const suggest = await api.r2SuggestTarget()
  if (!suggest.ok) {
    setTone(st, 'err', `Upload unavailable: ${suggest.error}`)
    openModal(r2UploadBackdrop)
    return
  }

  note.textContent = `Bucket: ${suggest.bucket}`
  input.value = suggest.target || suggest.appBase || ''
  setTone(st, 'info', 'Review target folder and start upload.')

  ;(suggest.folders || []).forEach(name => {
    const chip = document.createElement('button')
    chip.className = 'target-chip'
    chip.type = 'button'
    chip.textContent = name
    chip.addEventListener('click', () => { input.value = name })
    list.appendChild(chip)
  })

  openModal(r2UploadBackdrop)
}

async function runR2UploadFromModal() {
  const target = document.getElementById('r2-target-folder').value.trim()
  const st = document.getElementById('r2-upload-status')
  if (!target) {
    setTone(st, 'err', 'Target folder is required.')
    return
  }

  closeModal(r2UploadBackdrop)
  elKill.disabled = false
  elDot.className = 'running'
  elStatus.textContent = 'Uploading R2'
  elRunning.textContent = `dist -> ${target}`
  const res = await api.r2UploadDist({ target })
}

// ── ANSI → HTML ───────────────────────────────────────────────────────────────
// ── Terminal output ───────────────────────────────────────────────────────────
function appendOutput(text) {
  if (typeof text !== 'string' || text.length === 0) return

  if (term) {
    const shouldFollow = isTermNearBottom()
    term.write(text)
    if (shouldFollow) term.scrollToBottom()
    return
  }

  elOutput.appendChild(document.createTextNode(text))
  elOutput.scrollTop = elOutput.scrollHeight
}

function termHeader(label) {
  appendOutput('\n▶ ' + label + '\n' + '─'.repeat(60) + '\n')
}

function getSelectedStreamMode() {
  const mode = String(elStreamMode?.value || 'realtime').toLowerCase()
  return mode === 'stable' ? 'stable' : 'realtime'
}

function isBuildLikeCommandRenderer(cmdDef) {
  const cmd = String(cmdDef?.cmd || '').toLowerCase()
  const args = (cmdDef?.args || []).map(x => String(x || '').toLowerCase())
  const joined = [cmd, ...args].join(' ')
  if (/electron-builder|gradlew/.test(cmd)) return true
  if (/\b(build|dist|pack|release|assemble|bundle|nsis|msi|portable|appimage)\b/.test(joined)) return true
  return false
}

function isNpmRunDevRenderer(cmdDef) {
  const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()
  const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())
  return (cmd === 'npm' || cmd === 'npm.cmd') && args.length === 2 && args[0] === 'run' && args[1] === 'dev'
}

function clearR2UiValues() {
  const ids = ['r2-account-id', 'r2-bucket', 'r2-access-key', 'r2-secret-key', 'r2-target-folder']
  ids.forEach(id => {
    const el = document.getElementById(id)
    if (el) el.value = ''
  })

  const texts = ['r2-account-hint', 'r2-bucket-hint', 'r2-access-hint', 'r2-config-status', 'r2-upload-status', 'r2-upload-note']
  texts.forEach(id => {
    const el = document.getElementById(id)
    if (el) el.textContent = ''
  })

  const list = document.getElementById('r2-target-list')
  if (list) list.innerHTML = ''
}

function appendSecurityStatusLines(status) {
  const lines = []
  lines.push('\n[DEV SECURITY STATUS]')
  lines.push(`mode=${status.appMode}`)
  lines.push(`requestGuardInstalled=${status.requestGuardInstalled}`)
  lines.push(`externalRequestBlockActive=${status.externalRequestBlockActive}`)
  lines.push(`shortcutDevtoolsBlockedInProduction=${status.shortcutDevtoolsBlockedInProduction}`)
  lines.push(`mainWindowDevtoolsCapable=${status.mainWindowDevtoolsCapable}`)
  lines.push(`popupWindowDevtoolsCapable=${status.popupWindowDevtoolsCapable}`)
  lines.push(`popupCspInlineStyleAllowed=${status.popupCspInlineStyleAllowed}`)
  lines.push(`popupRunCount=${status.popupRunCount}`)
  lines.push(`note=${status.securityNote}`)
  appendOutput(lines.join('\n') + '\n')
}

function commandButtonKey(cmdDef) {
  const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()
  const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())
  const cwd = String(cmdDef && cmdDef.cwd ? cmdDef.cwd : '').trim().toLowerCase()
  return `${cmd}${args.join('␟')}${cwd}`
}

function buildCommandHint(cmdDef, group, typeInfo) {
  const label = String(cmdDef?.label || '').toLowerCase()
  const cmdLine = [cmdDef.cmd, ...(cmdDef.args || [])].join(' ')
  const projectType = String(typeInfo?.label || 'Project').trim()
  const projectTypeLower = projectType.toLowerCase()

  const lines = []

  if (/expo start/.test(label)) {
    lines.push('Step 1: Start Expo development server.')
    lines.push('Use this first for local mobile development.')
  } else if (/expo run:android/.test(label)) {
    lines.push('Step 2: Build and run the app on Android device/emulator.')
    lines.push('Use after Expo server is ready.')
  } else if (/expo prebuild/.test(label)) {
    lines.push('Prepare native Android project files from Expo config.')
    lines.push('Use when native config changed or Android folder is missing.')
  } else if (/installdebug/.test(label)) {
    lines.push('Install debug APK to connected Android device/emulator.')
    lines.push('Recommended after clean build or code changes.')
  } else if (/assemblerelease|build[-\s]?exe|build[-\s]?win|build[-\s]?msi|build[-\s]?nsis|build[-\s]?linux|dist|pack/.test(label)) {
    lines.push('Create a production build artifact.')
    lines.push('Use when you want distributable output files.')
  } else if (/assembledebug/.test(label)) {
    lines.push('Compile a debug build without installing it.')
  } else if (/clean\s*\+\s*install/.test(label)) {
    lines.push('Step 1+2: Clean old build files, then install fresh debug app.')
    lines.push('Good first fix when build output is inconsistent.')
  } else if (/^clean$/.test(label)) {
    lines.push('Step 1: Remove cached build artifacts.')
    lines.push('Run before rebuild if Gradle behaves unexpectedly.')
  } else if (/adb devices/.test(label)) {
    lines.push('Check if Android devices/emulators are connected.')
    lines.push('Run this before install commands.')
  } else if (/adb logcat/.test(label)) {
    lines.push('Open real-time Android logs for debugging.')
  } else if (/adb reverse/.test(label)) {
    lines.push('Forward Metro port to device (8081 -> 8081).')
    lines.push('Use when device cannot reach local dev server.')
  } else if (/npm install\s*--legacy-peer-deps/.test(label)) {
    lines.push('Install dependencies with legacy peer dependency resolution.')
    lines.push('Use only when normal install fails due to peer conflicts.')
  } else if (/npm install/.test(label)) {
    lines.push('Step 1: Install project dependencies.')
  } else if (/npm ci/.test(label)) {
    lines.push('Install dependencies from lockfile for clean reproducible setup.')
  } else if (/npm run dev/.test(label)) {
    lines.push('Start development mode (hot reload/watch if supported).')
  } else if (/npm run start/.test(label)) {
    lines.push('Start app in normal run mode.')
  } else if (/npm run android/.test(label)) {
    lines.push('Run Android target from package scripts.')
  } else if (/npm run ios/.test(label)) {
    lines.push('Run iOS target from package scripts.')
  } else if (/npm run web/.test(label)) {
    lines.push('Run web target from package scripts.')
  } else if (/npm run build/.test(label)) {
    lines.push('Build production assets for this project.')
  } else if (/npm run preview/.test(label)) {
    lines.push('Preview the production build locally.')
  } else if (/npm run lint/.test(label)) {
    lines.push('Run lint checks to catch code issues.')
  } else if (/npm run test/.test(label)) {
    lines.push('Run test suite for this project.')
  } else {
    lines.push('Run this command for the current project.')
  }

  let flow = ''
  if (projectTypeLower.includes('expo') || projectTypeLower.includes('react native')) {
    flow = 'Recommended order: npm install -> expo start -> expo run:android (or installDebug).'
  } else if (projectTypeLower.includes('electron')) {
    flow = 'Recommended order: npm install -> npm run dev (or start) -> npm run build-exe/build-win for release.'
  } else if (projectTypeLower.includes('next.js') || projectTypeLower.includes('next')) {
    flow = 'Recommended order: npm install -> npm run dev -> npm run build -> npm run start.'
  } else if (projectTypeLower.includes('vite')) {
    flow = 'Recommended order: npm install -> npm run dev -> npm run build -> npm run preview.'
  } else {
    flow = 'Recommended order: npm install -> npm run dev/start -> npm run build (when ready to release).'
  }

  lines.push(`Project type: ${projectType}.`)
  lines.push(flow)
  lines.push(`Group: ${group.label}.`)
  lines.push(`Command: ${cmdLine}.`)
  return lines.join('\n')
}

// ── Render command groups ─────────────────────────────────────────────────────
function renderGroups(groups, typeInfo) {
  elGroups.innerHTML = ''
  cmdButtonByKey.clear()
  groups.forEach(group => {
    const div = document.createElement('div')
    div.className = 'cmd-group'

    const lbl = document.createElement('div')
    lbl.className = 'cmd-group-label'
    const colorClass = GROUP_COLOR_CLASS[group.icon] || 'group-color-default'
    const iconHtml = ICONS[group.icon]
      ? `<span class="cmd-group-icon ${colorClass}">${ICONS[group.icon]}</span>`
      : ''
    lbl.innerHTML = `${iconHtml}<span class="${colorClass}">${group.label}</span>`
    div.appendChild(lbl)

    group.cmds.forEach(cmdDef => {
      const btn = document.createElement('button')
      btn.className = 'cmd-btn'
      btn.textContent = cmdDef.label
      const hint = buildCommandHint(cmdDef, group, typeInfo)
      btn.title = hint
      btn.setAttribute('aria-label', hint)
      const cmdKey = commandButtonKey(cmdDef)
      cmdButtonByKey.set(cmdKey, btn)
      if (popupRunningByCmd.has(cmdKey)) {
        btn.classList.add('running-popup')
      }
      if (mainRunning && currentMainCmdKey === cmdKey) {
        btn.classList.add('running')
        runningBtn = btn
      }
      btn.addEventListener('click', () => runCommand(btn, cmdDef))
      div.appendChild(btn)
    })

    elGroups.appendChild(div)
  })
}

// ── Run a command ─────────────────────────────────────────────────────────────
async function runCommand(btn, cmdDef) {
  showPage('run')

  if (currentAppIsDev && isNpmRunDevRenderer(cmdDef) && api && typeof api.openDevToolsForCommand === 'function') {
    await api.openDevToolsForCommand({ cmd: cmdDef.cmd, args: cmdDef.args || [] })
  }

  ensureTerminalInitialized()
  const cmdKey = commandButtonKey(cmdDef)
  const streamMode = getSelectedStreamMode()
  const preferPopup = isBuildLikeCommandRenderer(cmdDef)

  if (!preferPopup && (!mainRunning || currentMainCmdKey === cmdKey)) {
    if (runningBtn && runningBtn !== btn) {
      runningBtn.classList.remove('running')
    }

    btn.classList.remove('done-ok', 'done-err', 'running-popup')
    btn.classList.add('running')
    runningBtn = btn
    mainRunning = true
    currentMainCmdKey = cmdKey

    elKill.disabled = false
    elDot.className = 'running'
    elStatus.textContent = 'Running'
    elRunning.textContent = `${btn.textContent} [${streamMode}]`

    // Wait a moment for the Run page layout to settle before fitting and running.
    setTimeout(async () => {
      if (fitAddon) fitAddon.fit()
      notifyPtyResize()

      const _termCols = term ? (term.cols || 120) : 120
      const _termRows = term ? (term.rows || 30) : 30

      if (term) term.reset()

      const res = await api.runCmd({
        cmd: cmdDef.cmd,
        args: cmdDef.args,
        cwd: cmdDef.cwd,
        streamMode,
        cols: _termCols,
        rows: _termRows,
      })

      if (!res || !res.ok) {
        mainRunning = false
        currentMainCmdKey = null
        elKill.disabled = true
      }
    }, 50)
    return
  }

  if (preferPopup) {
    appendOutput(`\n[POPUP] Build-like command routed to Sandbox Terminal: ${btn.textContent}\n`)
  }

  btn.classList.remove('done-ok', 'done-err')
  btn.classList.add('running-popup')
  popupRunningByCmd.set(cmdKey, true)

  const realCols = term ? (term.cols || 120) : 120
  const realRows = term ? (term.rows || 30) : 30
  const popupRes = await api.runCmdPopup({
    cmd: cmdDef.cmd,
    args: cmdDef.args,
    cwd: cmdDef.cwd,
    label: btn.textContent,
    streamMode,
    cols: realCols,
    rows: realRows,
  })

  if (!popupRes || !popupRes.ok) {
    popupRunningByCmd.delete(cmdKey)
    btn.classList.remove('running-popup')
    btn.classList.add('done-err')
    appendOutput(`\n[POPUP ERROR] ${popupRes && popupRes.error ? popupRes.error : 'Failed to start popup'}\n`)
    return
  }

  appendOutput(`\n[POPUP] ${popupRes.restarted ? 'Restarted' : 'Started'}: ${btn.textContent}\n`)
}

function bootstrapProjectInBackground() {
  // Wait until first paint so users can interact with Home immediately.
  requestAnimationFrame(() => {
    setTimeout(() => {
      loadProject().catch((e) => {
        elName.textContent = 'Failed to load project'
        elPath.textContent = e && e.message ? e.message : String(e || 'Unknown error')
      })
    }, 0)
  })
}

// ── Load project ──────────────────────────────────────────────────────────────
async function loadProject() {
  elName.textContent  = 'Loading…'
  elBadge.textContent = ''
  elPath.textContent  = ''
  elGroups.innerHTML  = ''

  const data = await api.getProject()
  currentAppIsDev = !!data?.isDev

  const tabR2  = document.getElementById('tab-r2')
  const pageR2 = document.getElementById('page-r2')
  if (!currentAppIsDev) {
    if (tabR2)  tabR2.style.display  = 'none'
    if (pageR2) pageR2.style.display = 'none'
    if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'
  } else {
    if (tabR2)  tabR2.style.display  = ''
    if (pageR2) pageR2.style.display = ''
    if (elDevQuickPanel) elDevQuickPanel.style.display = ''
  }

  if (!data.ok) {
    const blocked = !!data.blocked || /protected OS location/i.test(String(data.error || ''))
    elName.textContent = blocked ? 'Security policy blocked this location' : 'No package.json found'
    elPath.textContent = data.projectRoot
    if (blocked) {
      elGroups.innerHTML = `<div id="error-msg">

        Project root is blocked by security policy:<br><b>${data.projectRoot}</b><br><br>

        Use <b>Select Project</b> to choose a safe project folder outside OS protected paths.

      </div>`
    } else {
      elGroups.innerHTML = `<div id="error-msg">

        No <code>package.json</code> found in:<br><b>${data.projectRoot}</b><br><br>

        Place the launcher inside your project folder and restart.

      </div>`
    }
    return
  }

  const { projectRoot, projectName, typeInfo, groups, isDev } = data
  currentAppIsDev = !!isDev

  const osLabel = data && data.runtimeOs && data.runtimeOs.label
    ? String(data.runtimeOs.label)
    : 'Unknown OS'

  elName.textContent  = projectName || 'Unnamed Project'
  elPath.textContent  = projectRoot
  elBadge.textContent = `${typeInfo.label}${osLabel}`
  elBadge.className   = `type-badge ${typeInfo.badgeClass}`

  document.title = `Dev Launcher — ${projectName || projectRoot}`

  if (!isDev) {
    if (tabR2)  tabR2.style.display  = 'none'
    if (pageR2) pageR2.style.display = 'none'
    if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'
  } else {
    if (tabR2)  tabR2.style.display  = ''
    if (pageR2) pageR2.style.display = ''
    if (elDevQuickPanel) elDevQuickPanel.style.display = ''
  }

  renderGroups(groups, typeInfo)
}

// ── Events ────────────────────────────────────────────────────────────────────
document.getElementById('tab-home').addEventListener('click', () => showPage('home'))
document.getElementById('tab-run').addEventListener('click', () => showPage('run'))
const tabR2Btn = document.getElementById('tab-r2')
if (tabR2Btn) {
  tabR2Btn.addEventListener('click', () => showPage('r2'))
}
document.getElementById('support-btn').addEventListener('click', () => {
  showPage('support')
})
document.getElementById('btn-select-project').addEventListener('click', async () => {
  await api.selectProjectFolder('full-project')
})
document.getElementById('btn-use-launcher-project').addEventListener('click', async () => {
  await api.useLauncherProject()
})

const btnR2ConfigClose = document.getElementById('btn-r2-config-close')
if (btnR2ConfigClose) btnR2ConfigClose.addEventListener('click', () => closeModal(r2ConfigBackdrop))
const btnR2ConfigCancel = document.getElementById('btn-r2-config-cancel')
if (btnR2ConfigCancel) btnR2ConfigCancel.addEventListener('click', () => closeModal(r2ConfigBackdrop))
const btnR2ConfigClear = document.getElementById('btn-r2-config-clear')
if (btnR2ConfigClear) btnR2ConfigClear.addEventListener('click', clearSavedR2Config)
const btnR2ConfigSave = document.getElementById('btn-r2-config-save')
if (btnR2ConfigSave) btnR2ConfigSave.addEventListener('click', saveR2FromModal)
const btnR2UploadClose = document.getElementById('btn-r2-upload-close')
if (btnR2UploadClose) btnR2UploadClose.addEventListener('click', () => closeModal(r2UploadBackdrop))
const btnR2UploadCancel = document.getElementById('btn-r2-upload-cancel')
if (btnR2UploadCancel) btnR2UploadCancel.addEventListener('click', () => closeModal(r2UploadBackdrop))
const btnR2UploadRun = document.getElementById('btn-r2-upload-run')
if (btnR2UploadRun) btnR2UploadRun.addEventListener('click', runR2UploadFromModal)
document.getElementById('security-block-close').addEventListener('click', () => {
  const backdrop = document.getElementById('security-block-backdrop')
  if (backdrop) closeModal(backdrop)
})

if (elDevMainTools) {
  elDevMainTools.addEventListener('click', async () => {
    const res = await api.openMainDevTools()
    if (!res || !res.ok) {
      appendOutput(`\n[DEV] Main DevTools: ${res && res.error ? res.error : 'failed'}\n`)
    }
  })
}

if (elDevPopupTools) {
  elDevPopupTools.addEventListener('click', async () => {
    const res = await api.openPopupDevTools()
    if (!res || !res.ok) {
      appendOutput(`\n[DEV] Popup DevTools: ${res && res.error ? res.error : 'failed'}\n`)
      return
    }
    appendOutput(`\n[DEV] Popup DevTools opened (runId=${res.runId || 'unknown'})\n`)
  })
}

if (elDevSecurityStatus) {
  elDevSecurityStatus.addEventListener('click', async () => {
    const status = await api.getDevSecurityStatus()
    if (!status || !status.ok) {
      appendOutput(`\n[DEV] Security status unavailable\n`)
      return
    }
    appendSecurityStatusLines(status)
  })
}

document.addEventListener('keydown', (e) => {
  if (e.key !== 'Escape') return
  closeModal(r2ConfigBackdrop)
  closeModal(r2UploadBackdrop)
})

elKill.addEventListener('click', async () => {
  await api.killProc()
})

elClear.addEventListener('click', () => {
  if (term) {
    term.reset()
  } else {
    elOutput.innerHTML = ''
  }
})

if (elStreamMode) {
  const saved = String(localStorage.getItem('streamMode') || '').toLowerCase()
  elStreamMode.value = saved === 'stable' ? 'stable' : 'realtime'
  elStreamMode.addEventListener('change', () => {
    localStorage.setItem('streamMode', getSelectedStreamMode())
  })
}

// ── IPC listeners ─────────────────────────────────────────────────────────────
api.onOutput((data) => appendOutput(data))

api.onDone((code) => {
  mainRunning = false
  currentMainCmdKey = null
  elKill.disabled = true
  elDot.className = code === 0 ? '' : 'error'
  elStatus.textContent = code === 0 ? 'Done ✓' : `Exited (${code})`
  elRunning.textContent = ''

  if (runningBtn) {
    runningBtn.classList.remove('running')
    runningBtn.classList.add(code === 0 ? 'done-ok' : 'done-err')
    runningBtn = null
  }
})

api.onPopupRunState((state) => {
  if (!state || !state.cmdKey) return
  const btn = cmdButtonByKey.get(state.cmdKey)
  const status = String(state.status || '')

  if (status === 'started' || status === 'restarted') {
    popupRunningByCmd.set(state.cmdKey, true)
    if (btn) {
      btn.classList.remove('done-ok', 'done-err')
      btn.classList.add('running-popup')
    }
    return
  }

  if (status === 'done' || status === 'closed' || status === 'closed-restart') {
    popupRunningByCmd.delete(state.cmdKey)
    if (btn) {
      btn.classList.remove('running-popup')
      if (status === 'done') {
        btn.classList.add(Number(state.exitCode) === 0 ? 'done-ok' : 'done-err')
      }
    }
  }
})

api.onProjectChanged(() => {
  loadProject()
})

api.onProjectSelectionBlocked((payload) => {
  showSecurityBlockModal(payload)
})

// ── Init ──────────────────────────────────────────────────────────────────────
bootstrapProjectInBackground()