File size: 44,152 Bytes
7bdc638
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>P-H3-Image Studio</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet" />
<style>
  :root {
    --bg: #120b1b; --panel: #171021; --panel2: #1d1429; --raised: #251b34;
    --border: rgba(74,57,98,0.75); --hairline: rgba(255,255,255,0.08);
    --text: #fafafa; --muted: #a3a3a3; --dim: #71717a;
    --accent: #9334e9; --accent2: #8f35ff; --accent-soft: rgba(147,52,233,0.14);
    --lavender: #d8b4fe; --link: #bf8bff;
    --glow: radial-gradient(ellipse 60% 35% at 50% -5%, rgba(147,52,233,0.18), transparent 55%);
    --stage-base: #0e0a16; --stage-square: #171221; --thumb-bg: #120c1c;
    --radius: 10px;
  }
  body.light {
    --bg: #f6f3fa; --panel: #ffffff; --panel2: #f6f3fa; --raised: #f3eef8;
    --border: rgba(126,34,206,0.16); --hairline: rgba(24,24,27,0.08);
    --text: #18181b; --muted: #71717a; --dim: #a1a1aa;
    --accent: #9334e9; --accent2: #7c22ce; --accent-soft: rgba(147,52,233,0.10);
    --lavender: #7e22ce; --link: #6d28d9;
    --glow: radial-gradient(ellipse 60% 35% at 50% -5%, rgba(147,52,233,0.10), transparent 55%);
    --stage-base: #e9e4f2; --stage-square: #f8f5fc; --thumb-bg: #f3eef8;
  }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  [hidden] { display: none !important; }
  body {
    font-family: "Inter", ui-sans-serif, system-ui, sans-serif;
    background: var(--bg); background-image: var(--glow); background-repeat: no-repeat;
    background-attachment: fixed;
    color: var(--text); height: 100vh;
    display: flex; flex-direction: column; overflow: hidden;
    font-size: 13px; -webkit-font-smoothing: antialiased;
  }
  .topbar {
    display: flex; align-items: center; gap: 14px; padding: 8px 16px;
    background: var(--panel); border-bottom: 1px solid var(--hairline); flex-shrink: 0;
  }
  .brand { font-weight: 700; font-size: 0.95rem; white-space: nowrap; letter-spacing: -0.02em; display: flex; align-items: center; }
  .brand img { height: 26px; margin-right: 10px; }
  .studio-badge {
    font-size: 0.6rem; font-weight: 650; letter-spacing: 0.12em; text-transform: uppercase;
    color: var(--lavender); border: 1px solid var(--border); border-radius: 999px;
    padding: 2px 8px; margin-left: 10px; background: var(--accent-soft);
  }
  .mode-tabs { display: flex; gap: 2px; background: var(--panel2); border: 1px solid var(--border); border-radius: 9px; padding: 3px; }
  .mode-tabs button {
    border: none; border-radius: 7px; padding: 6px 16px; font-weight: 550; font-size: 0.82rem;
    background: transparent; color: var(--muted); cursor: pointer; transition: color 0.15s, background 0.15s;
    font-family: inherit;
  }
  .mode-tabs button:hover { color: var(--text); }
  .mode-tabs button.active { background: var(--raised); color: var(--text); box-shadow: 0 1px 3px rgba(0,0,0,0.45); }
  body.light .mode-tabs button.active { box-shadow: 0 1px 3px rgba(88,28,135,0.15); }
  .spacer { flex: 1; }
  .ml-badge { color: var(--muted); text-decoration: none; font-size: 0.8rem; font-weight: 500; transition: color 0.15s; white-space: nowrap; }
  .ml-badge:hover { color: var(--text); }
  .ml-badge-img { display: inline-flex; align-items: center; }
  .ml-badge-img img { height: 20px; display: block; }
  .ml-badge-img:hover { opacity: 0.85; }
  .ml-cta {
    color: var(--lavender); text-decoration: none; font-size: 0.8rem; font-weight: 600;
    padding: 5px 13px; border: 1px solid var(--accent); border-radius: 999px;
    background: var(--accent-soft); transition: filter 0.15s; white-space: nowrap;
  }
  .ml-cta:hover { filter: brightness(1.2); }
  .theme-toggle {
    width: 34px; height: 34px; border: 1px solid var(--border); border-radius: 9px;
    background: transparent; color: var(--muted); cursor: pointer; flex-shrink: 0;
    display: inline-flex; align-items: center; justify-content: center;
    transition: color 0.15s, background 0.15s;
  }
  .theme-toggle:hover { color: var(--text); background: var(--panel2); }
  .theme-toggle svg { width: 17px; height: 17px; }
  .theme-toggle .theme-icon-moon { display: none; }
  .theme-toggle[data-mode="light"] .theme-icon-sun { display: none; }
  .theme-toggle[data-mode="light"] .theme-icon-moon { display: block; }
  .main { display: flex; flex: 1; min-height: 0; }
  .rail {
    width: 52px; flex-shrink: 0; display: flex; flex-direction: column; align-items: center;
    gap: 6px; padding: 10px 0; background: var(--panel); border-right: 1px solid var(--hairline);
  }
  .rail button {
    width: 38px; height: 38px; border: 1px solid transparent; border-radius: 8px;
    background: transparent; color: var(--muted); cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    transition: color 0.15s, background 0.15s;
  }
  .rail button:hover { background: var(--panel2); color: var(--text); }
  .rail button.active { color: var(--accent2); background: var(--accent-soft); }
  .viewport { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: auto; position: relative; }
  .workflow-view { position: absolute; inset: 0; padding: 12px; }
  .workflow-view iframe { width: 100%; height: 100%; border: none; border-radius: 10px; background: var(--stage-base); }
  .doc-grid { flex: 1; min-height: 0; display: flex; gap: 16px; width: 100%; align-items: stretch; justify-content: center; padding: 20px 20px 10px; }
  .doc {
    flex: 1; min-width: 0; max-width: 640px; display: flex; flex-direction: column;
    background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden;
  }
  .doc figcaption {
    padding: 8px 12px; font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em;
    color: var(--dim); border-bottom: 1px solid var(--hairline); text-transform: uppercase;
    display: flex; align-items: center;
  }
  .doc .stage {
    position: relative; flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center;
    overflow: hidden; background-color: var(--stage-base);
    background-image:
      linear-gradient(45deg, var(--stage-square) 25%, transparent 25%),
      linear-gradient(-45deg, var(--stage-square) 25%, transparent 25%),
      linear-gradient(45deg, transparent 75%, var(--stage-square) 75%),
      linear-gradient(-45deg, transparent 75%, var(--stage-square) 75%);
    background-size: 20px 20px;
    background-position: 0 0, 0 10px, 10px -10px, -10px 0;
  }
  .doc img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
  .doc img.zoomed { max-width: none; max-height: none; }
  .doc .stage.scrollable { overflow: auto; justify-content: flex-start; align-items: flex-start; }
  .drop-hint { color: var(--dim); font-size: 0.85rem; text-align: center; padding: 20px; }
  .drop-hint b { color: var(--muted); display: block; margin-bottom: 6px; }
  .zoom-btn {
    margin-left: auto; border: 1px solid var(--border); background: transparent; color: var(--muted);
    border-radius: 5px; font-size: 0.62rem; padding: 2px 8px; cursor: pointer; letter-spacing: 0.08em;
    font-family: inherit;
  }
  .zoom-btn:hover { color: var(--text); border-color: var(--accent); }
  .doc-bar {
    display: flex; align-items: center; gap: 10px; padding: 6px 12px;
    border-top: 1px solid var(--hairline); background: var(--panel);
    font-size: 0.72rem; color: var(--muted); flex-shrink: 0;
  }
  .doc-bar button {
    border: 1px solid var(--border); background: transparent; color: var(--muted);
    border-radius: 5px; padding: 3px 10px; font-size: 0.68rem; cursor: pointer; letter-spacing: 0.06em;
    font-family: inherit;
  }
  .doc-bar button:hover, .doc-bar button.active { color: var(--text); border-color: var(--accent); }
  .doc-bar button.active { background: var(--accent-soft); color: var(--lavender); }
  .split-wrap { position: absolute; inset: 0; overflow: hidden; }
  .split-wrap img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
  .split-divider {
    position: absolute; top: 0; bottom: 0; width: 3px; background: var(--accent);
    cursor: ew-resize; z-index: 5; box-shadow: 0 0 8px rgba(147,52,233,0.6);
  }
  .split-divider::after {
    content: "◂ ▸"; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
    background: var(--accent); color: white; border-radius: 999px; padding: 4px 7px;
    font-size: 0.6rem; white-space: nowrap;
  }
  .history-strip {
    display: flex; gap: 8px; padding: 8px 12px; overflow-x: auto; flex-shrink: 0;
    background: var(--panel); border-top: 1px solid var(--hairline); align-items: center;
  }
  .history-strip .hlabel { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.14em; color: var(--dim); text-transform: uppercase; white-space: nowrap; }
  .history-chip {
    width: 52px; height: 52px; border-radius: 6px; border: 1px solid var(--border);
    overflow: hidden; cursor: pointer; flex-shrink: 0; position: relative;
  }
  .history-chip:hover { border-color: var(--accent); }
  .history-chip img { width: 100%; height: 100%; object-fit: cover; }
  .history-chip .hseed {
    position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.65);
    color: #ddd; font-size: 0.52rem; padding: 1px 3px; text-align: center;
  }
  body.light .history-chip .hseed { background: rgba(255,255,255,0.78); color: #3f3f46; }
  .panels {
    width: 320px; flex-shrink: 0; display: flex; flex-direction: column; gap: 10px;
    padding: 12px; overflow-y: auto; background: var(--panel); border-left: 1px solid var(--hairline);
  }
  .panel { background: var(--panel2); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px; }
  .panel-title { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em; color: var(--dim); text-transform: uppercase; margin-bottom: 10px; cursor: pointer; user-select: none; display: flex; align-items: center; justify-content: space-between; }
  .panel .panel-title::after { content: "▾"; font-size: 0.7rem; color: var(--dim); }
  .panel.collapsed .panel-title::after { content: "▸"; }
  .panel.collapsed .panel-body { display: none; }
  .panel label { display: block; font-size: 0.72rem; font-weight: 550; color: var(--muted); margin: 10px 0 4px; }
  .panel label:first-of-type { margin-top: 0; }
  textarea, input[type="text"], input[type="number"], select {
    width: 100%; background: var(--raised); color: var(--text); border: 1px solid var(--border);
    border-radius: 7px; padding: 8px 10px; font-family: inherit; font-size: 0.83rem; resize: vertical;
    transition: border-color 0.15s, box-shadow 0.15s;
  }
  select { appearance: none; background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%); background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%; background-size: 5px 5px; background-repeat: no-repeat; }
  textarea:focus, input:focus, select:focus { outline: none; border-color: var(--accent2); box-shadow: 0 0 0 3px var(--accent-soft); }
  textarea.code { font-family: "IBM Plex Mono", ui-monospace, monospace; font-size: 0.72rem; }
  textarea[readonly] { color: var(--muted); }
  .row { display: flex; gap: 8px; align-items: center; }
  .row > * { flex: 1; }
  .switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
  .switch input { display: none; }
  .switch .sw {
    display: inline-block;
    width: 34px; height: 20px; border-radius: 999px; background: var(--raised);
    border: 1px solid var(--border); position: relative; flex-shrink: 0; transition: background 0.18s, border-color 0.18s;
  }
  .switch .sw::after {
    content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px;
    border-radius: 50%; background: var(--muted); transition: transform 0.18s, background 0.18s;
  }
  .switch input:checked + .sw { background: var(--accent); border-color: var(--accent); }
  .switch input:checked + .sw::after { transform: translateX(14px); background: #fff; }
  .switch .sw-label { font-size: 0.75rem; color: var(--muted); }
  .layer-row {
    display: flex; align-items: center; gap: 10px; padding: 6px 8px;
    border: 1px solid var(--border); border-radius: 6px; margin-top: 6px;
    background: var(--raised);
  }
  .layer-row .thumb {
    width: 40px; height: 40px; border-radius: 4px; object-fit: cover; flex-shrink: 0;
    background: var(--thumb-bg); border: 1px solid var(--border);
    display: flex; align-items: center; justify-content: center;
    color: var(--dim); font-size: 0.65rem; text-align: center;
  }
  .layer-row .thumb img { width: 100%; height: 100%; object-fit: cover; border-radius: 3px; }
  .layer-row .lname { flex: 1; font-size: 0.78rem; color: var(--text); }
  .layer-row .lsub { font-size: 0.62rem; color: var(--dim); display: block; }
  .ref-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
  .ref-slot {
    height: 64px; border: 1px dashed var(--border); border-radius: 6px;
    display: flex; align-items: center; justify-content: center; cursor: pointer; overflow: hidden;
    color: var(--dim); font-size: 0.68rem; background: var(--raised); text-align: center;
  }
  .ref-slot:hover { border-color: var(--accent); }
  .ref-slot img { width: 100%; height: 100%; object-fit: cover; }
  .hint { font-size: 0.68rem; color: var(--dim); margin-top: 8px; line-height: 1.4; }
  #examples { display: flex; flex-direction: column; gap: 6px; max-height: 260px; overflow-y: auto; }
  .ex-chip {
    border: 1px solid var(--border); border-radius: 8px; cursor: pointer; flex-shrink: 0;
    background: var(--raised); padding: 7px 10px; text-align: left;
    display: flex; align-items: center; justify-content: space-between; gap: 8px;
    transition: border-color 0.15s; font-family: inherit;
  }
  .ex-chip:hover { border-color: var(--accent); }
  .ex-chip .ex-label { font-size: 0.75rem; color: var(--text); font-weight: 550; }
  .ex-chip .ex-aspect { font-size: 0.62rem; color: var(--lavender); font-family: "IBM Plex Mono", ui-monospace, monospace; }
  #run-btn {
    margin-top: 4px; padding: 12px; border: 1px solid rgba(147,52,233,0.7); border-radius: 8px; cursor: pointer;
    background: var(--accent); color: white; box-shadow: inset 0 1px rgba(255,255,255,0.2);
    font-weight: 600; font-size: 0.9rem; letter-spacing: 0.01em; font-family: inherit;
    transition: filter 0.15s, transform 0.05s;
  }
  #run-btn:hover { filter: brightness(1.12); }
  #run-btn:active { transform: translateY(1px); }
  #run-btn:disabled { opacity: 0.5; cursor: wait; }
  .statusbar {
    display: flex; align-items: center; gap: 16px; padding: 7px 16px; flex-shrink: 0;
    background: var(--panel); border-top: 1px solid var(--hairline);
    font-size: 0.75rem; color: var(--muted);
  }
  .statusbar .pulse { width: 8px; height: 8px; border-radius: 50%; background: #4fd1a5; }
  .statusbar.busy .pulse { background: var(--accent2); animation: pulse 1s infinite alternate; }
  @keyframes pulse { from { opacity: 0.4; } to { opacity: 1; } }
  .foot-links { display: flex; gap: 12px; align-items: center; }
  .foot-links a { color: var(--dim); text-decoration: none; font-size: 0.72rem; font-weight: 500; }
  .foot-links a:hover { color: var(--lavender); }
  #file-input { display: none; }
  @media (max-width: 860px) {
    html, body { height: auto !important; overflow: visible !important; }
    body { display: block; }
    .topbar { flex-wrap: wrap; gap: 8px; padding: 8px 12px; }
    .brand { font-size: 0.88rem; }
    .topbar .ml-badge, .topbar .ml-badge-img { display: none; }
    .main { display: block; height: auto; min-height: 0; }
    .rail {
      flex-direction: row; width: 100%; justify-content: center; gap: 10px;
      padding: 6px 10px; border-right: none; border-bottom: 1px solid var(--hairline);
    }
    .rail button { width: 44px; height: 44px; }
    .viewport { display: block; padding: 10px; overflow: visible; }
    .workflow-view { position: static; height: 78vh; padding: 0 0 10px; }
    .doc-grid { flex-direction: column; align-items: stretch; height: auto; }
    .doc { max-width: 100%; width: 100%; }
    .doc .stage { min-height: 220px; }
    .panels {
      width: 100%; border-left: none; border-top: 1px solid var(--hairline);
      padding: 10px 12px; overflow-y: visible;
    }
    .mode-tabs button { padding: 6px 13px; font-size: 0.8rem; }
    .foot-links { display: none; }
    .statusbar { position: sticky; bottom: 0; }
  }
</style>
</head>
<body>
  <header class="topbar">
    <div class="brand"><img src="https://huggingface.co/spaces/PrunaAI/P-H3-Image/resolve/main/pruna-logo.png" alt="Pruna" />P-H3-Image<span class="studio-badge">Studio</span></div>
    <div class="mode-tabs">
      <button id="mode-generate" class="active">Generate</button>
      <button id="mode-edit">Edit</button>
      <button id="mode-workflow">Workflow</button>
    </div>
    <div class="spacer"></div>
    <a class="ml-badge-img" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">
      <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-md.svg" alt="Built with ML Intern" />
    </a>
    <a class="ml-cta" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">Build your own app here →</a>
    <a class="ml-badge" href="https://huggingface.co/PrunaAI/P-H3-Image" target="_blank" rel="noopener">Model card</a>
    <a class="ml-badge" href="https://www.pruna.ai/" target="_blank" rel="noopener">pruna.ai</a>
    <button type="button" class="theme-toggle" id="theme-toggle" data-mode="dark" aria-label="Switch to light mode" title="Switch to light mode">
      <svg class="theme-icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4"></circle>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"></path>
      </svg>
      <svg class="theme-icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <path d="M21 14.5A8.5 8.5 0 1 1 9.5 3 7 7 0 0 0 21 14.5z"></path>
      </svg>
    </button>
  </header>

  <div class="main">
    <div class="rail">
      <button id="tool-upload" title="Upload an image to edit"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg></button>
      <button id="tool-clear-doc" title="Clear document"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
    </div>

    <div class="viewport">
      <div class="workflow-view" id="workflow-view" hidden>
        <iframe src="/workflow/?ui=canvas" title="Workflow canvas"></iframe>
      </div>
      <div class="doc-grid">
        <figure class="doc" id="doc-before">
          <figcaption id="before-caption">Source</figcaption>
          <div class="stage" id="before-stage">
            <img id="source-img" alt="" hidden />
            <div class="drop-hint" id="source-hint"><b>No source image</b>Use the upload tool or drop a file here</div>
          </div>
        </figure>
        <figure class="doc" id="doc-after">
          <figcaption id="after-caption">Result</figcaption>
          <div class="stage" id="after-stage">
            <img id="result-img" alt="" hidden />
            <div class="split-wrap" id="split-wrap" hidden>
              <img id="split-source" alt="" style="clip-path: inset(0 50% 0 0)" />
              <div class="split-divider" id="split-divider" style="left:50%"></div>
            </div>
            <div class="drop-hint" id="result-hint"><b>Nothing yet</b>Run to see the result</div>
          </div>
          <div class="doc-bar">
            <span id="result-meta">—</span>
            <div class="spacer"></div>
            <button id="split-toggle" hidden>SPLIT</button>
          </div>
        </figure>
      </div>
      <div class="history-strip" id="history-strip"><span class="hlabel">History</span></div>
    </div>

    <aside class="panels">
      <section class="panel">
        <div class="panel-title">Examples</div>
        <div id="examples"></div>
      </section>
      <section class="panel">
        <div class="panel-title">Prompt</div>
        <textarea id="prompt" rows="6" placeholder="Describe the image…"></textarea>
      </section>
      <section class="panel">
        <div class="panel-title">Composition</div>
        <div id="aspect-row">
          <label for="aspect">Aspect ratio</label>
          <select id="aspect">
            <option>1:1</option>
            <option selected>4:3</option>
            <option>3:4</option>
            <option>3:2</option>
            <option>2:3</option>
            <option>16:9</option>
            <option>9:16</option>
          </select>
        </div>
        <label for="resolution">Resolution</label>
        <select id="resolution"></select>
        <div class="row" style="margin-top:10px">
          <label class="switch"><input type="checkbox" id="upsample" checked /><span class="sw"></span><span class="sw-label">Prompt upsampling</span></label>
        </div>
      </section>
      <section class="panel" id="layers-panel" hidden>
        <div class="panel-title">Layers</div>
        <div class="layer-row" id="layer-source">
          <div class="thumb" id="layer-source-thumb">BG</div>
          <div class="lname">Background<span class="lsub">source image — this one is edited</span></div>
        </div>
        <div class="ref-grid">
          <div class="ref-slot" data-ref="2">+ Ref 2</div>
          <div class="ref-slot" data-ref="3">+ Ref 3</div>
          <div class="ref-slot" data-ref="4">+ Ref 4</div>
          <div class="ref-slot" data-ref="5">+ Ref 5</div>
          <div class="ref-slot" data-ref="6">+ Ref 6</div>
          <div class="ref-slot" data-ref="7">+ Ref 7</div>
          <div class="ref-slot" data-ref="8">+ Ref 8</div>
        </div>
        <div class="hint">Reference extra images in the prompt as &lt;Picture 2&gt; … &lt;Picture 8&gt; (e.g. "put the fox from &lt;Picture 2&gt; on the bench").</div>
      </section>
      <section class="panel">
        <div class="panel-title">Advanced</div>
        <div class="row">
          <div><label for="seed">Seed</label><input type="number" id="seed" value="42" min="0" /></div>
          <label class="switch"><input type="checkbox" id="randomize" checked /><span class="sw"></span><span class="sw-label">Randomize</span></label>
        </div>
      </section>
      <section class="panel">
        <div class="panel-title">Upsampled prompt</div>
        <textarea id="upsampled" class="code" rows="5" readonly placeholder="Filled in after a run with prompt upsampling on."></textarea>
      </section>
      <button id="run-btn">Generate</button>
    </aside>
  </div>

  <footer class="statusbar" id="statusbar">
    <div class="pulse"></div>
    <span id="status">Idle</span>
    <div class="spacer"></div>
    <span class="foot-links">
      <a href="https://github.com/PrunaAI/pruna" target="_blank" rel="noopener">GitHub</a>
      <a href="https://discord.gg/JFQmtFKCjd" target="_blank" rel="noopener">Discord</a>
      <a href="https://x.com/PrunaAI" target="_blank" rel="noopener">X</a>
    </span>
    <span id="seed-out"></span>
  </footer>

  <input type="file" id="file-input" accept="image/*" />

<script type="module">
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";

  const $ = (id) => document.getElementById(id);
  const state = { mode: "generate", sourcePath: null, refPaths: {}, app: null };
  for (let i = 2; i <= 8; i++) state.refPaths[i] = null;
  const docState = { source: null, result: null, history: [] };

  const EXAMPLES = [
    { label: "Negotiation in orbit", aspect: "16:9",
      prompt: "Medium wide shot from a low angle across a long table, on a 35mm lens, with the window and far wall behind the figures. Five people sit in tense negotiation, leaning toward each other. Two humans in worn grey wool suits face three alien delegates. The first alien is tall and thin-limbed, with grey skin, long folded fingers and a robe of coarse woven fiber. The second is squat and heavy, its back plated with pale ridged shell, gripping a stylus in three thick fingers. The third has a dark mantle of fine filaments and wears a harness of dented brass clips. A cracked ceramic jug, scuffed data slates and curled paper printouts sit on the table. Earth fills the large curved window, a band of blue cloud over dark ocean. Ribbed steel girders frame the foreground. Cold sunlight rakes across the table while one amber lamp hangs overhead, casting soft shadows under the chins. Fine dust drifts in the light. Palette of slate, bone, rust and deep teal, natural film color, fine grain, shadows deep with detail kept." },
    { label: "Astronaut in a flooded jungle", aspect: "16:9",
      prompt: "A frame from a feature film: a wide establishing shot from a low angle, with a small astronaut standing waist-deep in a flooded jungle clearing, captured on a large-format digital cinema camera with a 35mm lens.\n\nThe astronaut wears a worn white spacesuit with grey mud on the knees, scuffed gloves, and a cracked visor that reflects the canopy. One hand grips a rusted machete while the other rests on a broken comms pack. The helmet is tilted toward a sound in the trees, caught mid-step as if listening for danger.\n\nBehind the figure, tangled roots and fallen trunks rise out of black water. A pale strangler fig wraps around a torn fragment of a landing hull. Farther back, ferns and mist-shrouded trunks fade into layers of blue-grey haze.\n\nThe light is a low, overcast sky above the canopy, a cold top light with a faint blue-white bounce off the water. A single battery lantern clipped to the pack casts a small warm pool across the suit.\n\nDrifting mist hangs between the trunks, and fine rain dimples the water surface. The palette is restrained: slate blue, steel grey, muted sage green and pale ivory, with film-like color and fine grain." },
    { label: "Knight in a frozen forest", aspect: "3:2",
      prompt: "A photograph by an experienced landscape photographer, shot at eye level from a low position with a 35mm lens at f/2.8, the knight placed in the middle distance on a narrow forest path.\n\nThe knight is a weathered man in his forties, his beard rimmed with frost and his brow tight as he scans the trees. His dented steel plate is dulled with grey scratches, a wool cloak hangs heavy and damp at his shoulders, and his right hand rests loosely on a sword hilt wrapped in worn leather. His breath drifts visibly in the cold air as he walks mid-stride, one boot sinking into the snow.\n\nBehind him, birch and pine trunks are coated in white frost, and fallen branches lie half-buried under drifts. Moonlight comes from high upper left, pale and cool, lifting the frost on the bark and the rim of his pauldron, while the forest floor falls into deep blue shadow where texture remains visible. The palette stays restrained: slate blue, grey-white snow, muted brown leather and tarnished steel, with neutral white balance and fine film grain." },
    { label: "Anime sword duel", aspect: "16:9",
      prompt: "A frame from a Japanese anime television series, hand-drawn cel animation over a painted background, widescreen composition. On a rocky mountaintop in a thunderstorm, a swordsman in a torn dark coat swings a massive broadsword that glows pale blue, its blade mid-arc and his teeth clenched. Opposite him, a slender fighter in a white scarf blurs into motion, leaving streaks of afterimage and a ring of cracked stone. Lightning forks across the sky behind them, rain slants through the frame, and bright white highlights gleam on wet rock." },
    { label: "1970s sci-fi comic", aspect: "3:2",
      prompt: "A gouache and ink illustration in the style of a 1970s European science-fiction comic, filling the whole picture edge to edge. A lone space traveler in a bulky white suit stands on a rocky ledge, helmet visor catching the faint light, gazing up at towering mushroom trees with broad caps and thick pale stalks. A dim violet sky stretches above, with a few pale spores drifting through the air. Flat violet and ochre color with visible brush texture and inked contour lines, shown in a wide landscape view from a low angle." },
    { label: "Linen lookbook", aspect: "2:3",
      prompt: "A lookbook photograph by an experienced fashion photographer: a woman in her late twenties stands full length in a pale sandy-linen dress, a loose sleeveless A-line with a square neckline, a gathered waist and a hem that falls just below the calf. The natural linen creases softly at the hips and lifts slightly as she shifts her weight onto one foot in a light breeze. Her chestnut hair is loosely tied back, she wears simple leather sandals and small gold hoops, and her expression is calm as she looks just past the camera. The location is a whitewashed plaster wall beside a weathered wooden door, with the shadow of a palm frond falling across the plaster. Late-afternoon sunlight from the left gives warm directional light with visible detail in the shadows. Shot at 85mm from a few steps back at standing eye height, shallow depth of field, true white balance, fine grain, restrained palette of cream, sand and sage. No text, no other objects." },
    { label: "Risograph cyclist", aspect: "3:4",
      prompt: "A two-color risograph print on cream paper, the artwork running edge to edge with no border or margin. A cyclist in a hooded jacket and helmet leans into a turn on a bicycle down a wide city avenue, seen from a low side angle. Behind them rise tall apartment blocks with rows of windows, a tram line curving into the distance, and a few parked cars. Only the cyclist, the buildings and the road are shown. The image uses fluorescent pink and deep blue inks, which overprint to a dark purple where they overlap. Visible halftone dots, grainy ink coverage, and slight misregistration between the two passes run across the whole sheet." },
    { label: "Byzantine mosaic", aspect: "3:4",
      prompt: "A Byzantine gold-ground mosaic panel, small glass and stone tesserae set in lime mortar, with the gold tiles catching light unevenly. A lighthouse keeper in a dark blue tunic and short cloak stands at the base of a tall white tower, one hand raised to shield his eyes as he looks out to sea. Behind him a lantern glows with a red-gold flame, and the water below is built in bands of teal and deep blue tesserae, with a small ship on the horizon. The gold ground fills the background, the figures are outlined in dark grey-brown tesserae, and the grout lines are slightly uneven. The mosaic fills the whole image edge to edge, with no frame or border." },
    { label: "Kirchner street at night", aspect: "3:4",
      prompt: "A German Expressionist oil painting on canvas in the manner of Ernst Ludwig Kirchner's Berlin street scenes. A narrow city street at night tilts sharply toward the viewer, its buildings leaning into angular, flattened planes. Gaunt figures in dark coats hurry past a gas lamp whose light is a thick yellow smear dragged across the wet paving. Heavy impasto brushstrokes and visible palette-knife edges, with raw cadmium yellow, cobalt blue and vermilion patches in the lit windows. The paint covers the canvas edge to edge, with no frame or border." },
  ];

  async function getApp() {
    if (!state.app) state.app = await client(location.origin);
    return state.app;
  }

  async function uploadFile(file) {
    const form = new FormData();
    form.append("files", file);
    const resp = await fetch("/gradio_api/upload", { method: "POST", body: form });
    if (!resp.ok) throw new Error(`Upload failed (${resp.status})`);
    const paths = await resp.json();
    return Array.isArray(paths) ? paths[0] : paths;
  }

  function setStatus(text, busy = false) {
    $("status").textContent = text;
    $("statusbar").classList.toggle("busy", busy);
    $("run-btn").disabled = busy;
  }

  // ---------- theme ----------
  const themeBtn = $("theme-toggle");
  function applyTheme(mode) {
    document.body.classList.toggle("light", mode === "light");
    themeBtn.dataset.mode = mode;
    const label = mode === "dark" ? "Switch to light mode" : "Switch to dark mode";
    themeBtn.setAttribute("aria-label", label);
    themeBtn.setAttribute("title", label);
    try { localStorage.setItem("pruna-theme", mode); } catch (e) {}
  }
  themeBtn.onclick = () => applyTheme(document.body.classList.contains("light") ? "dark" : "light");
  (function initTheme() {
    let mode = "dark";
    try { if (localStorage.getItem("pruna-theme") === "light") mode = "light"; } catch (e) {}
    applyTheme(mode);
  })();

  function setResolutions(list) {
    const sel = $("resolution");
    const prev = sel.value;
    sel.innerHTML = "";
    for (const r of list) {
      const opt = document.createElement("option");
      opt.value = r;
      opt.textContent = r;
      sel.appendChild(opt);
    }
    sel.value = list.includes(prev) ? prev : "8 MP";
  }

  function setMode(mode) {
    state.mode = mode;
    for (const m of ["generate", "edit", "workflow"]) $(`mode-${m}`).classList.toggle("active", mode === m);
    const workflow = mode === "workflow";
    $("workflow-view").hidden = !workflow;
    document.querySelector(".doc-grid").style.display = workflow ? "none" : "";
    document.querySelector(".rail").style.display = workflow ? "none" : "";
    document.querySelector(".panels").style.display = workflow ? "none" : "";
    $("history-strip").style.display = workflow ? "none" : "";
    if (!workflow) {
      const edit = mode === "edit";
      $("doc-before").style.display = edit ? "" : "none";
      $("layers-panel").hidden = !edit;
      $("aspect-row").style.display = edit ? "none" : "";
      setResolutions(edit ? ["4 MP", "8 MP"] : ["4 MP", "8 MP", "16 MP"]);
      $("run-btn").textContent = edit ? "Generate Edit" : "Generate";
      $("prompt").placeholder = edit ? "e.g. put the fox from <Picture 2> on the bench" : "Describe the image…";
    }
  }
  $("mode-generate").onclick = () => setMode("generate");
  $("mode-edit").onclick = () => setMode("edit");
  $("mode-workflow").onclick = () => setMode("workflow");

  // ---------- uploads ----------
  let uploadTarget = "source";
  function pickFile(target) {
    uploadTarget = target;
    $("file-input").click();
  }
  $("tool-upload").onclick = () => { setMode("edit"); pickFile("source"); };
  document.querySelectorAll(".ref-slot").forEach((slot) => {
    slot.onclick = () => pickFile(slot.dataset.ref);
  });
  $("file-input").onchange = async (e) => {
    const file = e.target.files[0];
    e.target.value = "";
    if (!file) return;
    setStatus("Uploading…", true);
    try {
      const path = await uploadFile(file);
      if (uploadTarget === "source") {
        state.sourcePath = path;
        showSource(file);
      } else {
        state.refPaths[uploadTarget] = path;
        const slot = document.querySelector(`.ref-slot[data-ref="${uploadTarget}"]`);
        slot.innerHTML = "";
        const img = document.createElement("img");
        img.src = URL.createObjectURL(file);
        slot.appendChild(img);
      }
      setStatus("Idle");
    } catch (err) {
      setStatus(String(err));
    }
  };
  $("before-stage").addEventListener("dragover", (e) => e.preventDefault());
  $("before-stage").addEventListener("drop", async (e) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (!file) return;
    setStatus("Uploading…", true);
    try {
      state.sourcePath = await uploadFile(file);
      showSource(file);
      setStatus("Idle");
    } catch (err) {
      setStatus(String(err));
    }
  });

  function showSource(file) {
    const img = $("source-img");
    img.src = URL.createObjectURL(file);
    img.hidden = false;
    $("source-hint").style.display = "none";
    docState.source = img.src;
    const st = $("layer-source-thumb");
    st.innerHTML = "";
    const stImg = document.createElement("img");
    stImg.src = img.src;
    st.appendChild(stImg);
    setMode("edit");
  }

  $("tool-clear-doc").onclick = () => {
    state.sourcePath = null;
    for (let i = 2; i <= 8; i++) state.refPaths[i] = null;
    docState.source = null;
    docState.result = null;
    $("source-img").hidden = true;
    $("source-hint").style.display = "";
    $("result-img").hidden = true;
    $("result-hint").style.display = "";
    $("result-meta").textContent = "—";
    $("seed-out").textContent = "";
    $("upsampled").value = "";
    $("split-toggle").hidden = true;
    $("split-wrap").hidden = true;
    $("layer-source-thumb").textContent = "BG";
    document.querySelectorAll(".ref-slot").forEach((slot) => {
      slot.textContent = `+ Ref ${slot.dataset.ref}`;
    });
  };

  // ---------- history ----------
  function renderHistory() {
    const strip = $("history-strip");
    strip.innerHTML = '<span class="hlabel">History</span>';
    docState.history.forEach((h) => {
      const chip = document.createElement("div");
      chip.className = "history-chip";
      chip.title = h.prompt || "";
      const img = document.createElement("img");
      img.src = h.uri;
      const tag = document.createElement("div");
      tag.className = "hseed";
      tag.textContent = h.seed ?? "";
      chip.appendChild(img);
      chip.appendChild(tag);
      chip.onclick = () => {
        setMode(h.mode || "generate");
        $("prompt").value = h.prompt;
        $("seed").value = h.seed ?? 42;
        $("randomize").checked = false;
        docState.result = h.uri;
        $("result-img").src = h.uri;
        $("result-img").hidden = false;
        $("result-hint").style.display = "none";
        $("split-toggle").hidden = !(h.mode === "edit" && !$("source-img").hidden);
      };
      strip.appendChild(chip);
    });
  }
  function pushHistory(uri, seed, prompt, mode) {
    docState.history.unshift({ uri, seed, prompt, mode });
    if (docState.history.length > 8) docState.history.pop();
    renderHistory();
  }

  // ---------- before/after split view ----------
  let splitOn = false;
  $("split-toggle").onclick = () => {
    if ($("result-img").hidden) return;
    splitOn = !splitOn;
    $("split-toggle").classList.toggle("active", splitOn);
    $("split-wrap").hidden = !splitOn;
    if (splitOn && !$("source-img").hidden) $("split-source").src = $("source-img").src;
  };
  (function () {
    const divider = $("split-divider");
    let dragging = false;
    divider.addEventListener("pointerdown", (e) => { dragging = true; e.preventDefault(); });
    window.addEventListener("pointermove", (e) => {
      if (!dragging) return;
      const stage = $("after-stage").getBoundingClientRect();
      const pct = Math.min(97, Math.max(3, ((e.clientX - stage.left) / stage.width) * 100));
      divider.style.left = pct + "%";
      $("split-source").style.clipPath = `inset(0 ${100 - pct}% 0 0)`;
    });
    window.addEventListener("pointerup", () => { dragging = false; });
  })();

  // ---------- zoom ----------
  document.querySelectorAll(".doc figcaption").forEach((caption) => {
    const btn = document.createElement("button");
    btn.className = "zoom-btn";
    btn.textContent = "FIT";
    btn.onclick = () => {
      const img = caption.parentElement.querySelector("img");
      const stage = caption.parentElement.querySelector(".stage");
      const zoomed = img.classList.toggle("zoomed");
      stage.classList.toggle("scrollable", zoomed);
      btn.textContent = zoomed ? "1:1" : "FIT";
    };
    caption.appendChild(btn);
  });

  // ---------- collapsible panels ----------
  document.querySelectorAll(".panel .panel-title").forEach((title) => {
    const body = document.createElement("div");
    body.className = "panel-body";
    [...title.parentElement.children].forEach((child) => {
      if (child !== title) body.appendChild(child);
    });
    title.parentElement.appendChild(body);
    title.onclick = () => title.parentElement.classList.toggle("collapsed");
  });

  // ---------- examples ----------
  const exRow = $("examples");
  EXAMPLES.forEach((ex) => {
    const chip = document.createElement("button");
    chip.className = "ex-chip";
    const label = document.createElement("span");
    label.className = "ex-label";
    label.textContent = ex.label;
    const aspect = document.createElement("span");
    aspect.className = "ex-aspect";
    aspect.textContent = ex.aspect;
    chip.appendChild(label);
    chip.appendChild(aspect);
    chip.onclick = () => {
      setMode("generate");
      $("prompt").value = ex.prompt;
      $("aspect").value = ex.aspect;
      setStatus("Example loaded — hit Generate");
    };
    exRow.appendChild(chip);
  });

  // ---------- result handling ----------
  function unwrap(result) {
    const data = Array.isArray(result?.data) ? result.data[0] : result?.data;
    return data ?? {};
  }
  function showResult(result) {
    const payload = unwrap(result);
    const url = typeof payload.image_data === "string" ? payload.image_data : null;
    if (!url) { setStatus("Run finished but no image came back (see console)."); return false; }
    const img = $("result-img");
    img.src = url;
    img.hidden = false;
    $("result-hint").style.display = "none";
    docState.result = url;
    if (payload.seed != null) $("seed-out").textContent = "seed " + payload.seed;
    if (payload.prompt) $("upsampled").value = payload.prompt;
    $("result-meta").textContent = payload.info || "Done";
    $("split-toggle").hidden = !(state.mode === "edit" && !$("source-img").hidden);
    pushHistory(url, payload.seed, $("prompt").value.trim(), state.mode);
    return true;
  }

  $("run-btn").onclick = async () => {
    const app = await getApp();
    const prompt = $("prompt").value.trim();
    const seed = parseInt($("seed").value, 10) || 0;
    const randomize = $("randomize").checked;
    const upsample = $("upsample").checked;
    const resolution = $("resolution").value;
    try {
      let result;
      if (state.mode === "edit") {
        if (!state.sourcePath) { setStatus("Upload a source image first."); return; }
        if (!prompt) { setStatus("Describe the edit first."); return; }
        setStatus("Editing…", true);
        result = await app.predict("/edit", {
          source: state.sourcePath,
          instruction: prompt,
          ref2: state.refPaths[2],
          ref3: state.refPaths[3],
          ref4: state.refPaths[4],
          ref5: state.refPaths[5],
          ref6: state.refPaths[6],
          ref7: state.refPaths[7],
          ref8: state.refPaths[8],
          resolution, upsample, seed, randomize,
        });
      } else {
        if (!prompt) { setStatus("Write a prompt first."); return; }
        setStatus(upsample ? "Upsampling the prompt, then rendering…" : "Rendering…", true);
        result = await app.predict("/generate", {
          prompt,
          aspect: $("aspect").value,
          resolution, upsample, seed, randomize,
        });
      }
      if (showResult(result)) setStatus("Done");
    } catch (err) {
      setStatus(err?.message || String(err));
    }
  };

  setMode("generate");
</script>
</body>
</html>