File size: 43,332 Bytes
29c3be9
 
 
 
 
 
 
 
 
607c4f0
29c3be9
ca4ec99
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c4f0
 
 
 
 
 
29c3be9
 
607c4f0
29c3be9
 
 
 
 
 
 
607c4f0
29c3be9
 
 
607c4f0
29c3be9
 
 
 
 
 
 
 
 
 
607c4f0
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c4f0
 
29c3be9
 
 
 
 
 
 
ca4ec99
29c3be9
 
607c4f0
 
 
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c4f0
 
 
29c3be9
607c4f0
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca4ec99
607c4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca4ec99
607c4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca4ec99
607c4f0
 
 
 
 
29c3be9
 
 
 
 
 
607c4f0
 
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607c4f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29c3be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict";

// Browser frontend: no CDN, external telemetry, or cloud API calls.
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const BASE = "/api/v1";
const STORAGE = "absolution_omega_current_project_v02";
const state = {
  projectId: null, projectName: "", asset: null, analysis: null,
  stems: {}, report: null, separation: null, bass: null, noise: null, virtualbass: null, virtualReady: false,
  model: "hpss", models: [], busy: false, playing: "original",
  view: "arrangement",
};
let toastTimer = null;
let maxUploadBytes = 1024 * 1024 * 1024;
const audio = $("#player");

function safeStore(value) {
  try { if (value) localStorage.setItem(STORAGE, value); else localStorage.removeItem(STORAGE); } catch (_) {}
}
function storedProject() {
  try { return localStorage.getItem(STORAGE); } catch (_) { return null; }
}
async function api(path, options={}) {
  let response;
  try { response = await fetch(path, options); }
  catch (_) { throw new Error("Der lokale Audio-Server ist nicht erreichbar. Starte die Anwendung auf localhost:8000."); }
  const contentType = response.headers.get("content-type") || "";
  const data = contentType.includes("application/json") ? await response.json() : null;
  if (!response.ok) {
    let reason = data?.detail || `HTTP ${response.status}`;
    if (Array.isArray(reason)) reason = reason.map(item => item.msg).join("; ");
    throw new Error(String(reason));
  }
  return data;
}
function toast(message, error=false) {
  const target = $("#toast");
  target.textContent = message;
  target.classList.toggle("error", error);
  target.hidden = false;
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => {target.hidden = true;}, error ? 12000 : 7000);
}
function timeText(seconds) {
  const s = Math.floor(Math.max(0, Number(seconds) || 0));
  return `${String(Math.floor(s / 60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;
}
function dbText(value) { return Number.isFinite(Number(value)) ? `${Number(value).toFixed(1)} dBFS` : "—"; }
function scientific(value) {return Number.isFinite(Number(value)) ? Number(value).toExponential(3) : "—"; }
function el(tag, className="", text="") {
  const node = document.createElement(tag);
  if (className) node.className = className;
  if (text !== "") node.textContent = text;
  return node;
}
function setBusy(value) {
  state.busy = Boolean(value);
  $("#fileInput").disabled = value;
  $("#browse").disabled = value;
  $("#demoBtn").disabled = value;
  $("#newProject").disabled = value;
  $("#dropzone").setAttribute("aria-disabled", String(value));
  $("#run").disabled = value || !state.projectId || !state.models.find(m => m.id === state.model && m.ready);
  $("#bassRun").disabled = value || !state.asset;
  $("#bassExport").disabled = value || !state.bass;
  $("#virtualRun").disabled = value || !state.asset || state.analysis?.channels !== 2 || !state.virtualReady;
  $("#noiseScan").disabled = value || !state.asset;
  $("#noiseExport").disabled = value || !state.noise?.repair;
  $("#noiseRepair").disabled = value || !state.noise?.scan || !document.querySelector("#noiseCandidates input:checked");
}
function navigate(view) {
  if (!["studio","arrangement","bass","noise","stems","quality","guide"].includes(view)) return;
  state.view = view;
  $$(".view").forEach(node => node.classList.toggle("active", node.id === `view-${view}`));
  $$(".nav-link").forEach(node => {
    const active = node.dataset.view === view;
    node.classList.toggle("active", active);
    if (active) node.setAttribute("aria-current", "page"); else node.removeAttribute("aria-current");
  });
  const names = {studio:"STUDIO",arrangement:"ARRANGEMENT",bass:"BASS-CORE",noise:"NOISE-CORE",stems:"MEINE STEMS",quality:"FORENSIK-BERICHT",guide:"HILFE & TECHNIK"};
  $("#crumbCurrent").textContent = names[view];
  document.title = `ABSOLUTION Ω — ${names[view]}`;
  closeMenu();
  if(view==="arrangement" && window.omegaArrangementDraw)window.omegaArrangementDraw();
  window.scrollTo({top:0,behavior:"instant"});
}
function closeMenu() {
  $("#sidebar").classList.remove("open");
  $("#mobileScrim").hidden = true;
  $("#menuToggle").setAttribute("aria-expanded","false");
}
function resetUi() {
  state.projectId = null; state.projectName = "";
  state.analysis = null; state.asset = null;
  state.stems = {}; state.report = null; state.separation = null; state.bass = null; state.noise = null; state.virtualbass = null;
  audio.pause(); audio.removeAttribute("src"); audio.load();
  state.playing = "original";
  $("#nowPlaying").textContent = "Kein Audio geladen";
  $("#nowPlayingSub").textContent = "Importiere eine Datei";
  $("#playButton").textContent = "▶"; $("#playButton").disabled = true;
  $("#back10").disabled = true; $("#forward10").disabled = true;
  $("#seekBar").disabled = true; $("#seekBar").value = 0;
  $("#playTime").textContent = "00:00"; $("#playDuration").textContent = "00:00";
  $("#tracklabel").textContent = "KEINE DATEI";
  $("#uploadHeading").textContent = "Ziehe deine Audiodatei hierher";
  $("#uploadSub").textContent = "Oder wähle eine Datei aus. Deine Musik bleibt auf deinem Gerät und deinem lokalen Server.";
  $("#sidebarProject").textContent = "Noch kein Audio";
  $("#sidebarProjectInfo").textContent = "Importiere eine Datei";
  $("#duration").textContent = "—"; $("#samplerate").textContent = "—";
  $("#peak").textContent = "—"; $("#rms").textContent = "—";
  $("#end-time").textContent = "00:00";
  $("#currentWaveTime").textContent = "00:00";
  $("#stepAnalyze").classList.remove("active");$("#stepExtract").classList.remove("active");
  $("#jobprogress").hidden = true;
  $("#goStems").disabled = true;$("#export").disabled = true;
  $("#stem-count").textContent = "0";
  $("#provProject").textContent = "—"; $("#provFile").textContent = "—";
  $("#provHash").textContent = "—"; $("#provMethod").textContent = "—";
  $("#provDate").textContent = "—"; $("#provAudio").textContent = "—";
  $("#clipFrames").textContent = "—"; $("#centroid").textContent = "—";
  $("#reportHeadline").textContent = "Noch keine Prüfung erfolgt";
  $("#reportExplanation").textContent = "Nach einer Separation berechnen wir, wie genau alle Stems inklusive Residual den internen Eingangsmix rekonstruieren.";
  $("#reportMark").textContent = "◇";
  $("#err").textContent = "—"; $("#rmsErr").textContent = "—";
  renderStems(); drawWave(); renderBass(); renderNoise(); renderVirtual();
  if(window.omegaArrangementReset) window.omegaArrangementReset();
  setBusy(false);
}
function loadManifest(project) {
  state.projectId = project.id;
  state.projectName = project.name || "Unbenannt";
  state.asset = project.asset;
  state.analysis = project.analysis;
  state.stems = project.unified?.mix_consistent ? project.unified.stems : (project.stems || {});
  state.report = project.report;
  state.separation = project.separation;
  state.bass = project.bass || null;
  state.noise = project.noise || null;
  state.virtualbass = project.virtualbass || null;
  safeStore(project.id);
  $("#sidebarProject").textContent = project.name || project.asset?.filename || "Projekt";
  $("#sidebarProjectInfo").textContent = project.analysis ? `${timeText(project.analysis.duration_seconds)} · ${project.analysis.channels} Kanal/Kanäle` : "Projekt ohne Datei";
  if (project.asset && project.analysis) {
    const a = project.analysis;
    $("#tracklabel").textContent = project.asset.filename;
    $("#uploadHeading").textContent = project.asset.filename;
    $("#uploadSub").textContent = "Datei erfolgreich importiert. Du kannst jetzt ein Verfahren wählen und die Separation starten.";
    $("#duration").textContent = timeText(a.duration_seconds);
    $("#samplerate").textContent = `${(a.sample_rate/1000).toFixed(1)} kHz`;
    $("#peak").textContent = dbText(a.peak_dbfs);
    $("#rms").textContent = dbText(a.rms_dbfs);
    $("#end-time").textContent = timeText(a.duration_seconds);
    $("#stepAnalyze").classList.add("active");
    setSource("original",false);
  }
  renderStems();
  renderReport();
  renderBass();
  renderNoise();
  renderVirtual();
  drawWave();
  if(window.omegaArrangementLoad) window.omegaArrangementLoad(project);
  setBusy(false);
}
async function uploadFile(file) {
  if (!file || state.busy) return;
  if (file.size > maxUploadBytes) return toast(`Die Datei überschreitet das Upload-Limit von ${Math.round(maxUploadBytes/1048576)} MiB.`,true);
  setBusy(true);
  $("#uploadHeading").textContent = "Import läuft …";
  $("#uploadSub").textContent = `${file.name} wird lokal geprüft und analysiert.`;
  try {
    const name = file.name.slice(0,80) || "Neues Audioprojekt";
    const project = await api(`${BASE}/projects`,{
      method:"POST", headers:{"content-type":"application/json"}, body:JSON.stringify({name})
    });
    const form = new FormData();
    form.append("project_id",project.id);
    form.append("file",file,file.name);
    const result = await api(`${BASE}/assets`,{method:"POST",body:form});
    loadManifest({...project, asset:result.asset, analysis:result.analysis});
    navigate("studio");
    toast("Import erfolgreich! Deine Originaldatei wurde unverändert gespeichert.");
  } catch(error) {
    $("#uploadHeading").textContent = state.asset?.filename || "Ziehe deine Audiodatei hierher";
    $("#uploadSub").textContent = "Datei auswählen oder Demo ausprobieren.";
    toast(`Import fehlgeschlagen: ${error.message}`,true);
  } finally {setBusy(false);}
}
async function loadDemo() {
  if (state.busy) return;
  try {
    $("#demoBtn").disabled = true;
    const response = await fetch(`${BASE}/demo`,{cache:"no-store"});
    if(!response.ok) throw new Error(`Demo-Audio nicht verfügbar (HTTP ${response.status}).`);
    const blob=await response.blob();
    await uploadFile(new File([blob],"absolution_demo.wav",{type:"audio/wav"}));
  } catch(error) {
    toast(`Demo konnte nicht geladen werden: ${error.message}`,true);
  } finally {$("#demoBtn").disabled=state.busy;}
}
function sourceUrl(stem="original",preview=true) {
  return `${BASE}/projects/${state.projectId}/audio/${encodeURIComponent(stem)}${preview?"?preview=true":""}`;
}
function setSource(stem,autoPlay=true) {
  if (!state.projectId || !state.asset) return;
  state.playing=stem;
  const oldStem = audio.dataset.stem;
  if(oldStem!==stem || !audio.getAttribute("src")) {
    audio.pause();
    audio.src = sourceUrl(stem);
    audio.dataset.stem=stem;
    audio.load();
    $("#playButton").textContent="▶";
    $("#seekBar").value=0;$("#playTime").textContent="00:00";
  }
  const names={original:"Original",harmonic:"Harmonisch",percussive:"Perkussiv",residual:"Residual",vocals:"Gesang",drums:"Schlagzeug",bass:"Bass",other:"Instrumente / Other"};
  $("#nowPlaying").textContent=names[stem]||stem;
  $("#nowPlayingSub").textContent=state.asset.filename;
  $("#playButton").disabled=false;$("#back10").disabled=false;$("#forward10").disabled=false;
  $("#seekBar").disabled=false;
  $("#playDuration").textContent=timeText(state.analysis?.duration_seconds);
  if(autoPlay) audio.play().catch(()=>toast("Audio konnte nicht abgespielt werden.",true));
}
function drawWave() {
  const canvas=$("#waveform");
  const ratio=Math.min(window.devicePixelRatio||1,2);
  const w=Math.max(1,Math.round(canvas.clientWidth));
  const h=Math.max(1,Math.round(canvas.clientHeight));
  canvas.width=Math.round(w*ratio);canvas.height=Math.round(h*ratio);
  const ctx=canvas.getContext("2d");
  ctx.scale(ratio,ratio);
  ctx.strokeStyle="#2b5361";ctx.lineWidth=1;
  ctx.beginPath();ctx.moveTo(0,h/2);ctx.lineTo(w,h/2);ctx.stroke();
  const values=state.analysis?.waveform||[];
  $("#waveEmpty").hidden=values.length>0;
  if(!values.length) return;
  const max=Math.max(...values,0.000001);
  ctx.strokeStyle="#80ebd4";ctx.lineWidth=Math.max(1,Math.min(2.6,w/values.length*.67));
  for(let i=0;i<values.length;i++){
    const x=(i+.5)*w/values.length;
    const amplitude=Math.max(1,values[i]/max*h*.41);
    ctx.beginPath();ctx.moveTo(x,h/2-amplitude);ctx.lineTo(x,h/2+amplitude);ctx.stroke();
  }
  const duration=state.analysis?.duration_seconds||0;
  const current=audio.currentTime||0;
  if(duration>0 && current>=0){
    const x=Math.max(0,Math.min(w,current/duration*w));
    ctx.strokeStyle="#ffffff";ctx.lineWidth=1.2;
    ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,h);ctx.stroke();
    ctx.fillStyle="#b5ffe8";ctx.fillRect(Math.max(0,x-3),0,6,5);
  }
}
function renderStems() {
  const stems=Object.entries(state.stems);
  $("#stemsPreview").replaceChildren();
  $("#stemsFull").replaceChildren();
  $("#stem-count").textContent=String(stems.length);
  $("#goStems").disabled=stems.length===0;
  $("#export").disabled=stems.length===0;
  $("#stepExtract").classList.toggle("active",stems.length>0);
  if(stems.length===0){
    for(const [container, title, text] of [
      [$("#stemsPreview"),"Noch keine Stems vorhanden","Importiere einen Track und starte die Separation. Deine Ergebnisse erscheinen genau hier."],
      [$("#stemsFull"),"Deine Stem-Library ist noch leer","Verarbeite zuerst eine Datei im Studio."]
    ]){
      const empty=el("div","empty-state");
      empty.append(el("div","empty-icon","≋"),el("h3","",title),el("p","",text));
      container.append(empty);
    }
    return;
  }
  stems.forEach(([name,info])=>{
    $("#stemsPreview").append(makeStemCard(name,info));
    $("#stemsFull").append(makeStemCard(name,info));
  });
}
function makeStemCard(name,info) {
  const labels={harmonic:"Harmonisch",percussive:"Perkussiv",residual:"Residual",vocals:"Gesang",drums:"Drums",bass:"Bass",other:"Other"};
  const glyphs={harmonic:"∿",percussive:"✳",residual:"◇",vocals:"♫",drums:"✳",bass:"≋",other:"◈"};
  const card=el("article","stem-card");
  const head=el("div","stem-card-top");
  const icon=el("div","stem-emblem",glyphs[name]||"◌");
  const group=el("div");
  group.append(el("h3","",labels[name]||name),el("p","",`${timeText(info.duration_seconds)} · ${dbText(info.peak_dbfs)}`));
  head.append(icon,group);
  const meter=el("div","stem-meter");
  meter.setAttribute("aria-label",`Spitzenpegel ${dbText(info.peak_dbfs)}`);
  const track=el("div","level-track");
  track.style.width="100%";track.style.height="9px";track.style.background="#2b4250";track.style.borderRadius="8px";track.style.overflow="hidden";
  const fill=el("div");
  const fraction=Math.min(100,Math.max(0,100*Math.pow(10, Number(info.peak_dbfs)/20)));
  fill.style.width=`${fraction.toFixed(2)}%`;
  fill.style.background="linear-gradient(90deg,#5ac9bd,#aeffdb)";
  fill.style.height="100%";
  track.append(fill);meter.append(track);
  const actions=el("div","stem-actions");
  const play=el("button","","▶ Anhören");
  play.type="button";play.setAttribute("aria-label",`${labels[name]||name} anhören`);
  play.addEventListener("click",()=>setSource(name,true));
  const download=el("a","","↓ WAV Export");
  download.href=sourceUrl(name,false);
  download.download=`${name}.wav`;
  download.setAttribute("aria-label",`${labels[name]||name} als Master-WAV herunterladen`);
  actions.append(play,download);
  card.append(head,meter,actions);
  return card;
}
function renderReport() {
  const a=state.analysis, report=state.report, sep=state.separation;
  $("#provProject").textContent=state.projectName||"—";
  $("#provFile").textContent=state.asset?.filename||"—";
  $("#provHash").textContent=state.asset?.sha256||"—";
  $("#clipFrames").textContent=a?String(a.clipped_frames):"—";
  $("#centroid").textContent=a?`${a.spectral_centroid_hz} Hz`:"—";
  $("#provAudio").textContent=a?`${a.channels} Kanal/Kanäle · ${a.sample_rate} Hz · ${a.frames} Samples`:"—";
  $("#provMethod").textContent=sep ? `${sep.method==="hpss"?"HPSS (DSP)":"Demucs (neural)"} · ${sep.architecture}`:"—";
  $("#provDate").textContent=sep?.completed_at?new Date(sep.completed_at).toLocaleString("de-DE"):"—";
  $("#err").textContent=report?scientific(report.max_abs_reconstruction_error):"—";
  $("#rmsErr").textContent=report?scientific(report.rms_reconstruction_error):"—";
  $("#reportHeadline").textContent=!report?"Noch keine Prüfung erfolgt":report.consistent?"Rekonstruktion im Toleranzbereich":"Abweichung außerhalb der Toleranz";
  $("#reportExplanation").textContent=!report
    ?"Nach einer Separation berechnen wir, wie genau alle Stems inklusive Residual den internen Eingangsmix rekonstruieren."
    :`Gemessener Maximalfehler: ${scientific(report.max_abs_reconstruction_error)} bei Toleranz ${scientific(report.tolerance)}. Die Prüfung betrifft den internen Mix, nicht den WAV-Rundungsfehler.`;
  $("#reportMark").textContent=!report?"◇":report.consistent?"✓":"!";
}
async function refreshModels() {
  const response=await api(`${BASE}/models`);
  state.models=response.models||[];
  const demucs=state.models.find(item=>item.id==="demucs");
  const ready=Boolean(demucs?.ready);
  const input=$("#demucs input");
  input.disabled=!ready;
  $("#demucs").classList.toggle("disabled",!ready);
  $("#demucsStatus").textContent=ready?"KONFIGURIERT":"GEWICHTE FEHLEN";
  if(!ready && state.model==="demucs"){state.model="hpss";$("#demucs input").checked=false;$(".method[data-model='hpss'] input").checked=true;}
  selectMethod(state.model);
}
function selectMethod(model) {
  const selected=state.models.find(m=>m.id===model);
  if(!selected?.ready) return;
  state.model=model;
  $$(".method").forEach(m=>m.classList.toggle("selected",m.dataset.model===model));
  $(`.method[data-model="${model}"] input`).checked=true;
  $("#modelNote").textContent=model==="hpss"
    ?"HPSS trennt Klanganteile nach ihrer Signalstruktur, nicht nach Instrumentennamen. Das Verfahren ist DSP, keine KI."
    :"Demucs kann Gesang, Schlagzeug, Bass und übrige Klänge schätzen. Das Modell ist konfiguriert, wurde hier aber nicht mit echten Gewichten geprüft.";
  setBusy(state.busy);
}
async function runSeparation() {
  if(!state.projectId||!state.asset||state.busy) return;
  setBusy(true);
  $("#jobprogress").hidden=false;
  $("#progressfill").style.width="0%";
  $("#progressNum").textContent="0 %";
  $("#jobtext").textContent="Vorbereitung …";
  try{
    const job=await api(`${BASE}/jobs/separate`,{
      method:"POST",headers:{"content-type":"application/json"},
      body:JSON.stringify({project_id:state.projectId,model:state.model})
    });
    let done=false;
    // Keep polling while the job exists: long files can take significantly longer.
    while(!done){
      await new Promise(resolve=>setTimeout(resolve,600));
      const current=await api(`${BASE}/jobs/${job.id}`);
      const pct=Math.min(100,Math.max(0,Number(current.progress)||0));
      $("#progressfill").style.width=`${pct}%`;$("#progressNum").textContent=`${pct} %`;
      $("#jobtext").textContent=current.status==="queued"?"Wartet auf freien Worker …":current.status==="running"?"Audio wird verarbeitet …":current.status==="done"?"Abgeschlossen":"Fehlgeschlagen";
      if(current.status==="failed") throw new Error(current.error||"Unbekannter Fehler.");
      done=current.status==="done";
    }
    const manifest=await api(`${BASE}/projects/${state.projectId}`);
    loadManifest(manifest);
    $("#jobprogress").hidden=false; $("#progressfill").style.width="100%"; $("#progressNum").textContent="100 %"; $("#jobtext").textContent="Separation abgeschlossen";
    toast("Fertig! Höre die Stems an und prüfe den Forensik-Bericht.");
  } catch(error) {
    $("#jobtext").textContent="Verarbeitung fehlgeschlagen";
    toast(`Separation fehlgeschlagen: ${error.message}`,true);
  } finally {setBusy(false);}
}
// BASS-CORE Ω: user-controlled, non-destructive DSP stage.
const bassPresets = {
  transparent: {bassCrossover:220,bassFocus:75,bassKick:0,bassLine:0,bassSub:0,bassHarm:0,bassLowcut:10,bassMono:0,bassWet:100,bassCeiling:-1},
  club: {bassCrossover:200,bassFocus:85,bassKick:3,bassLine:1.5,bassSub:2,bassHarm:35,bassLowcut:22,bassMono:110,bassWet:90,bassCeiling:-1},
  warm: {bassCrossover:240,bassFocus:50,bassKick:0.5,bassLine:2,bassSub:2,bassHarm:45,bassLowcut:20,bassMono:90,bassWet:85,bassCeiling:-1},
  translate: {bassCrossover:180,bassFocus:65,bassKick:1,bassLine:0,bassSub:-1,bassHarm:80,bassLowcut:26,bassMono:110,bassWet:100,bassCeiling:-1},
};
const bassSliderIds = ["bassCrossover","bassFocus","bassKick","bassLine","bassSub","bassHarm","bassLowcut","bassMono","bassWet","bassCeiling"];
function bassNumber(id) {return Number($("#"+id).value);}
function updateBassValues() {
  const values={
    bassCrossoverValue:`${bassNumber("bassCrossover")} Hz`,
    bassFocusValue:`${bassNumber("bassFocus")} %`,
    bassKickValue:`${bassNumber("bassKick")>=0?"+":""}${bassNumber("bassKick").toFixed(1)} dB`,
    bassLineValue:`${bassNumber("bassLine")>=0?"+":""}${bassNumber("bassLine").toFixed(1)} dB`,
    bassSubValue:`${bassNumber("bassSub")>=0?"+":""}${bassNumber("bassSub").toFixed(1)} dB`,
    bassHarmValue:`${bassNumber("bassHarm")} %`,
    bassLowcutValue:`${bassNumber("bassLowcut")} Hz`,
    bassMonoValue:`${bassNumber("bassMono")} Hz`,
    bassWetValue:`${bassNumber("bassWet")} %`,
    bassCeilingValue:`${bassNumber("bassCeiling").toFixed(1)} dBFS`,
  };
  Object.entries(values).forEach(([id,label])=>$("#"+id).textContent=label);
}
function applyBassPreset(name) {
  const p=bassPresets[name]; if(!p)return;
  Object.entries(p).forEach(([id,val])=>{ $("#"+id).value=String(val);});
  updateBassValues();
  $$(".bass-preset").forEach(el=>el.classList.toggle("active",el.dataset.bassPreset===name));
}
function bassSourceUrl(track,preview=true) {
  return `${BASE}/projects/${state.projectId}/bass/audio/${encodeURIComponent(track)}${preview?"?preview=true":""}`;
}
function playBassTrack(name) {
  if(!state.bass || !state.projectId)return;
  audio.pause();
  audio.src=bassSourceUrl(name,true);
  audio.dataset.stem="bass:"+name;
  audio.load();
  $("#playButton").disabled=false;
  $("#back10").disabled=false;
  $("#forward10").disabled=false;
  $("#seekBar").disabled=false;
  $("#nowPlaying").textContent=state.bass.stems[name]?.label||name;
  $("#nowPlayingSub").textContent=`BASS-CORE · ${state.asset?.filename||""}`;
  $("#playDuration").textContent=timeText(state.analysis?.duration_seconds);
  audio.play().catch(()=>toast("Bass-Audio konnte nicht abgespielt werden.",true));
}
function renderBass() {
  const content=$("#bassResults");
  content.replaceChildren();
  const data=state.bass;
  $("#bassReady").textContent=!state.asset?"DATEI IMPORTIEREN":data?"VERARBEITET":"BEREIT";
  $("#bassSourceUsed").textContent=data?.mode?.toUpperCase()||"—";
  $("#bassMixPeak").textContent=data?dbText(data.report.output_peak_dbfs):"—";
  $("#bassPeakGain").textContent=data?`${data.report.output_ceiling_gain_db.toFixed(2)} dB`:"—";
  $("#bassRecon").textContent=data?(data.report.reconstruction_check.consistent?"OK":"PRÜFEN"):"—";
  if(!data) {
    const empty=el("div","empty-state");
    empty.append(el("h3","","Noch keine Bass-Bearbeitung"),el("p","","Importiere eine Audiodatei im Studio und starte BASS-CORE."));
    content.append(empty);
    $("#bassFrequency").replaceChildren(el("div","bass-frequency-empty","Noch kein Spektralvergleich vorhanden."));
    $("#bassExport").disabled=true;
    return;
  }
  $("#bassExport").disabled=state.busy;
  for(const [name,meta] of Object.entries(data.stems)) {
    const block=el("article","bass-result");
    const labels={
      bass_band:"Bassband · vorher",kick_estimate:"Kick · Schätzung",
      bassline_estimate:"Bassline · Schätzung",other_unprocessed:"Rest ohne Bassband",
      harmonics_added:"Neue Obertöne · Synthese",bass_optimized:"Bassband · optimiert",
      mix_optimized:"Voller Mix · nachher"
    };
    block.append(el("h3","",labels[name]||name),el("p","",meta.label||""));
    const actions=el("div","stem-actions");
    const play=el("button","","▶ Anhören");
    play.type="button"; play.addEventListener("click",()=>playBassTrack(name));
    const download=el("a","","↓ WAV 32-bit");
    download.href=bassSourceUrl(name,false);
    download.download=name+".wav";
    actions.append(play,download);block.append(actions);content.append(block);
  }
  const freq=$("#bassFrequency");freq.replaceChildren();
  const before=data.report.first_chunk_spectrum?.before||[];
  const after=data.report.first_chunk_spectrum?.after||[];
  for(let i=0;i<Math.min(before.length,after.length);i++){
    const a=before[i].estimated_rms_dbfs, b=after[i].estimated_rms_dbfs;
    const range=before[i].range_hz;
    const scaled=v=>Math.max(0,Math.min(100,(v+95)/95*100));
    const row=el("div","bass-freq-item");
    const band=el("span","",`${range[0]}–${range[1]} Hz`);
    const rail=el("div","bass-freq-rail");
    const old=el("div","bass-before"), newer=el("div","bass-after");
    old.style.width=scaled(a)+"%";newer.style.width=scaled(b)+"%";
    rail.append(old,newer);
    const info=el("span","bass-freq-key",`${(b-a)>=0?"+":""}${(b-a).toFixed(1)} dB`);
    row.append(band,rail,info);freq.append(row);
  }
}
function bassPayload() {
  return {
    project_id:state.projectId,source_mode:$("#bassMode").value,
    crossover_hz:bassNumber("bassCrossover"),kick_focus:bassNumber("bassFocus")/100,
    kick_gain_db:bassNumber("bassKick"),bass_gain_db:bassNumber("bassLine"),
    sub_gain_db:bassNumber("bassSub"),harmonics:bassNumber("bassHarm")/100,
    lowcut_hz:bassNumber("bassLowcut"),mono_below_hz:bassNumber("bassMono"),
    wet:bassNumber("bassWet")/100,ceiling_dbfs:bassNumber("bassCeiling")
  };
}
async function runBass() {
  if(state.busy||!state.asset)return;
  setBusy(true);
  $("#bassProgress").hidden=false;
  $("#bassProgressFill").style.width="0%";$("#bassProgressNum").textContent="0 %";
  $("#bassJobLabel").textContent="Analyse und Bass-Bearbeitung starten …";
  try {
    const job=await api(`${BASE}/jobs/bass`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(bassPayload())});
    while(true){
      await new Promise(resolve=>setTimeout(resolve,650));
      const now=await api(`${BASE}/jobs/${job.id}`);
      const pct=Math.min(100,Math.max(0,Number(now.progress)||0));
      $("#bassProgressFill").style.width=`${pct}%`;
      $("#bassProgressNum").textContent=`${pct} %`;
      $("#bassJobLabel").textContent=now.status==="queued"?"Wartet auf freien Worker …":now.status==="running"?"Tieffrequenzen werden verarbeitet …":now.status==="done"?"Bass-Bearbeitung abgeschlossen":"Fehlgeschlagen";
      if(now.status==="failed")throw new Error(now.error||"Fehler beim Bass-Processing.");
      if(now.status==="done")break;
    }
    const project=await api(`${BASE}/projects/${state.projectId}`);
    loadManifest(project);
    renderBass();
    toast("BASS-CORE abgeschlossen! Vergleiche Bassband vorher/nachher mit deinem Gehör.");
  } catch(error){
    $("#bassJobLabel").textContent="Verarbeitung fehlgeschlagen";
    toast(`BASS-CORE: ${error.message}`,true);
  } finally {setBusy(false);}
}

function renderVirtual() {
  const res=state.virtualbass;
  $("#virtualRun").disabled=state.busy||!state.asset||state.analysis?.channels!==2||!state.virtualReady;
  $("#virtualReady").textContent=!state.virtualReady?"FFMPEG-FILTER FEHLT":!state.asset?"STEREO IMPORTIEREN":res?"2.1 EXPORT BEREIT":"BEREIT";
  $("#virtualDownload").hidden=!res;
  if(res) {
    $("#virtualDownload").href=`${BASE}/projects/${encodeURIComponent(state.projectId)}/virtualbass/audio`;
    $("#virtualDownload").download="ABSOLUTION_VIRTUAL_BASS_2_1.wav";
    $("#virtualSummary").textContent=`3 Kanäle (L/R + LFE) · LFE Peak: ${res.report.lfe_peak_dbfs} dBFS · Stereo-Differenz: ${res.report.left_right_max_abs_difference.toExponential(2)}. Nicht automatisch als Stereo-Mix verwenden.`;
  } else $("#virtualSummary").textContent="Benötigt Stereo + FFmpeg mit virtualbass. Exportiert einen 2.1-Master, ohne die Stereo-Originaldatei zu ändern.";
}
async function runVirtual() {
  if(state.busy||!state.virtualReady||!state.asset)return;
  setBusy(true);
  try {
    const payload={
      project_id:state.projectId,
      cutoff_hz:Number($("#virtualCutoff").value),
      strength:Number($("#virtualStrength").value)
    };
    const job=await api(`${BASE}/jobs/bass/virtual`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(payload)});
    toast("Virtual Bass 2.1 wird lokal erzeugt …");
    while(true){
      await new Promise(resolve=>setTimeout(resolve,600));
      const current=await api(`${BASE}/jobs/${job.id}`);
      if(current.status==="failed")throw new Error(current.error||"Virtual Bass konnte nicht erzeugt werden.");
      if(current.status==="done")break;
    }
    state.virtualbass=(await api(`${BASE}/projects/${state.projectId}/virtualbass`)).virtualbass;
    toast("2.1-Virtual-Bass-Datei erstellt. Links/Rechts-Kanäle bleiben getrennt vom synthetischen LFE.");
  }catch(error){toast(`Virtual Bass: ${error.message}`,true)}
  finally{setBusy(false);renderVirtual();}
}
// NOISE-CORE: all changes require individually selected scan samples.
function noiseAudioUrl(name,preview=true) {
  return `${BASE}/projects/${encodeURIComponent(state.projectId)}/noise/audio/${encodeURIComponent(name)}${preview?"?preview=true":""}`;
}
function playNoiseTrack(name) {
  if(!state.noise?.repair)return;
  audio.pause();
  audio.src=noiseAudioUrl(name,true);
  audio.dataset.stem="noise:"+name;
  audio.load();
  $("#playButton").disabled=false;
  $("#back10").disabled=false;
  $("#forward10").disabled=false;
  $("#seekBar").disabled=false;
  $("#nowPlaying").textContent=name==="clean"?"Manuell repariertes Signal":"DIFFERENZ: tatsächlich verändertes Musiksignal";
  $("#nowPlayingSub").textContent=`NOISE-CORE · ${state.asset?.filename||""}`;
  $("#playDuration").textContent=timeText(state.analysis?.duration_seconds);
  audio.play().catch(()=>toast("Audio konnte nicht wiedergegeben werden.",true));
}
function renderNoise() {
  const scan=state.noise?.scan;
  const repair=state.noise?.repair;
  $("#noiseReady").textContent=!state.asset?"DATEI IMPORTIEREN":scan?"SCAN VORHANDEN":"BEREIT";
  $("#noiseScan").disabled=state.busy||!state.asset;
  $("#noiseScanMeta").textContent=scan?`${scan.event_count} Kandidaten · keine automatische Veränderung`:"Noch kein Scan";
  $("#noiseCount").textContent=scan?`${scan.event_count} Kandidaten`:"0 Kandidaten";
  const candidates=$("#noiseCandidates");
  candidates.replaceChildren();
  if(!scan) {
    const placeholder=el("div","empty-state");
    placeholder.append(el("h3","","Noch keine Kandidaten"),el("p","","Lade eine Audiodatei und starte den Scan."));
    candidates.append(placeholder);
  } else if (!scan.events.length) {
    candidates.append(el("p","bass-note","Keine auffälligen Einzel-Sample-Impulse gefunden. Das beweist nicht die Abwesenheit von Störungen."));
  } else {
    for(const event of scan.events) {
      const row=el("div","noise-candidate");
      const cb=el("input");
      cb.type="checkbox";cb.value=String(event.sample);cb.id=`noiseEvent_${event.sample}`;
      cb.addEventListener("change",()=>{$("#noiseRepair").disabled=state.busy||!document.querySelector("#noiseCandidates input:checked")});
      const label=el("label");
      label.htmlFor=cb.id;
      label.append(el("strong","",`${event.time_seconds.toFixed(4)} s · Kandidat #${event.sample}`));
      label.append(el("small","","Unsicherer Einzelimpuls · kein Nachweis für einen Defekt"));
      const button=el("button","","▶ Umfeld anhören");
      button.type="button";
      button.addEventListener("click",()=>{
        setSource("original",false);
        audio.currentTime=Math.max(0,event.time_seconds-.3);
        audio.play().catch(()=>toast("Original konnte nicht abgespielt werden.",true));
      });
      row.append(cb,label,button);
      candidates.append(row);
    }
  }
  $("#noiseRepair").disabled=state.busy||!scan||!document.querySelector("#noiseCandidates input:checked");
  const results=$("#noiseTracks");
  results.replaceChildren();
  if(repair) {
    for(const name of ["clean","difference"]) {
      const track=el("div","noise-track");
      track.append(el("h3","",name==="clean"?"Reparatur · nachher":"Differenzspur · entnommenes Signal"));
      track.append(el("p","",name==="clean"?"Bearbeiteter Mix aus explizit bestätigten Korrekturen.":"WICHTIG: Enthält möglicherweise echte Musikanteile. Immer abhören!"));
      const actions=el("div","stem-actions");
      const play=el("button","","▶ Anhören");
      play.addEventListener("click",()=>playNoiseTrack(name));
      const download=el("a","","↓ WAV Float32");
      download.href=noiseAudioUrl(name,false);download.download=`noise_${name}.wav`;
      actions.append(play,download);
      track.append(actions);results.append(track);
    }
  } else {
    const blank=el("div","empty-state");
    blank.append(el("h3","","Noch keine Bearbeitung"),el("p","","Das unveränderte Original ist weiterhin verfügbar."));
    results.append(blank);
  }
  $("#noiseExport").disabled=state.busy||!repair;
  const details=$("#noiseDiagnostics");details.replaceChildren();
  if(scan) {
    const tonal=scan.tonal_indicators||[];
    details.append(el("div","noise-line",tonal.length ?
      `Mögliche schmale Spektralspitzen (keine sichere Störung): ${tonal.map(t=>`${t.frequency_hz} Hz · +${t.peak_to_local_median_db} dB`).join(" | ")}. Keine automatischen Notches.`
      :"Keine auffällige 50-/60-Hz-Spektralspitze festgestellt. Kein automatisches Breitband-Entrauschen."));
    if(scan.event_limit_reached) details.append(el("div","noise-line","Anzeigegrenze für Klickkandidaten erreicht; vollständige Zählung siehe Bericht."));
  }
  if(repair) {
    const report=repair.report;
    details.append(el("div","noise-line",
      `${report.changed_sample_frames} explizit bestätigte Einzel-Samples verändert · Max. absolute Änderung ${report.peak_absolute_change.toExponential(3)} · Rekonstruktionsfehler ${report.reconstruction_max_absolute_error.toExponential(3)}. Die Differenzspur kann musikalische Anteile enthalten.`));
  }
}
async function pollNoiseJob(jobId,caption) {
  while(true) {
    await new Promise(resolve=>setTimeout(resolve,650));
    const status=await api(`${BASE}/jobs/${jobId}`);
    const pct=Math.min(100,Math.max(0,Number(status.progress)||0));
    $("#noiseProgressFill").style.width=`${pct}%`;
    $("#noiseProgressNum").textContent=`${pct} %`;
    $("#noiseJobLabel").textContent=status.status==="queued"?"Wartet auf Worker …":status.status==="running"?caption:status.status==="done"?"Fertig":"Fehlgeschlagen";
    if(status.status==="failed") throw new Error(status.error||"NOISE-CORE Job fehlgeschlagen.");
    if(status.status==="done")break;
  }
}
async function startNoiseScan() {
  if(state.busy||!state.asset)return;
  setBusy(true);
  $("#noiseProgress").hidden=false;$("#noiseProgressFill").style.width="0%";
  try{
    const job=await api(`${BASE}/jobs/noise/scan`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({project_id:state.projectId})});
    await pollNoiseJob(job.id,"Musikalische Impulse werden vorsichtig untersucht …");
    const response=await api(`${BASE}/projects/${state.projectId}/noise`);
    state.noise=response.noise;renderNoise();
    loadManifest(await api(`${BASE}/projects/${state.projectId}`));
    toast("Scan beendet. Nichts wurde verändert. Bitte jeden Kandidaten einzeln prüfen.");
  }catch(error){toast(`NOISE-CORE: ${error.message}`,true)}
  finally{setBusy(false);renderNoise();}
}
async function startNoiseRepair() {
  if(state.busy||!state.noise?.scan)return;
  const selected=$$("#noiseCandidates input:checked").map(x=>Number(x.value));
  if(!selected.length)return toast("Wähle eine geprüfte Klickstelle aus.",true);
  if(!window.confirm(`Du hast ${selected.length} Stelle(n) ausgewählt. Diese Samples werden interpoliert. Die Differenzspur kann echte Musikanteile enthalten. Fortfahren?`))return;
  setBusy(true);
  $("#noiseProgress").hidden=false;$("#noiseProgressFill").style.width="0%";
  try{
    const job=await api(`${BASE}/jobs/noise/repair`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({
      project_id:state.projectId,approved_samples:selected,
      strength:Number($("#noiseStrength").value)/100
    })});
    await pollNoiseJob(job.id,"Nur freigegebene Einzelstellen werden behutsam bearbeitet …");
    const response=await api(`${BASE}/projects/${state.projectId}/noise`);
    state.noise=response.noise;renderNoise();
    loadManifest(await api(`${BASE}/projects/${state.projectId}`));
    toast("Reparatur gerendert. Bitte die Differenzspur anhören.");
  }catch(error){toast(`NOISE-CORE: ${error.message}`,true)}
  finally{setBusy(false);renderNoise();}
}

async function init() {
  resetUi();
  audio.volume=.8;
  try{
    const health = await api(`${BASE}/health`);
    maxUploadBytes = Number(health.max_upload_bytes) || maxUploadBytes;
    state.virtualReady=Boolean(health.virtualbass_ready);
    renderVirtual();
    $("#uploadLimits").textContent = `WAV · FLAC · AIFF · MP3 · OGG  •  bis ${Math.round(maxUploadBytes/1048576)} MiB  •  keine feste Zeitgrenze`;
    $("#guideImportLimits").textContent = `Maximale Dateigröße: ${Math.round(maxUploadBytes/1048576)} MiB. Keine feste Zeitgrenze; Verarbeitungszeit hängt von Datei und Hardware ab.`;
    $("#apiIndicator").classList.add("online");$("#apiLabel").textContent="ENGINE ONLINE";
    await refreshModels();
    const oldId=storedProject();
    if(oldId){
      try{
        const old=await api(`${BASE}/projects/${encodeURIComponent(oldId)}`);
        loadManifest(old);
        toast("Dein letztes Projekt wurde wiederhergestellt.");
      }catch(_){safeStore(null);}
    }
  }catch(error) {
    $("#apiLabel").textContent="ENGINE OFFLINE";
    toast(error.message,true);
  }
}
$$("[data-view]").forEach(button=>button.addEventListener("click",()=>navigate(button.dataset.view)));
$$("[data-goto]").forEach(button=>button.addEventListener("click",()=>navigate(button.dataset.goto)));
$("#menuToggle").addEventListener("click",()=>{
  const open=!$("#sidebar").classList.contains("open");
  $("#sidebar").classList.toggle("open",open);
  $("#mobileScrim").hidden=!open;
  $("#menuToggle").setAttribute("aria-expanded",String(open));
});
$("#mobileScrim").addEventListener("click",closeMenu);
$("#newProject").addEventListener("click",()=>{
  if(state.busy)return;
  safeStore(null);resetUi();navigate("studio");
  toast("Neues Projekt bereit. Vorherige Dateien bleiben lokal gespeichert.");
});
$("#browse").addEventListener("click",event=>{event.stopPropagation();$("#fileInput").click();});
$("#dropzone").addEventListener("click",event=>{if(state.busy || event.target.closest("button"))return;$("#fileInput").click();});
$("#dropzone").addEventListener("keydown",event=>{if((event.key==="Enter"||event.key===" ")&&!state.busy && event.target===$("#dropzone")){event.preventDefault();$("#fileInput").click();}});
$("#fileInput").addEventListener("change",event=>{uploadFile(event.target.files?.[0]);event.target.value="";});
$("#demoBtn").addEventListener("click",loadDemo);
$("#dropzone").addEventListener("dragover",event=>{event.preventDefault();$("#dropzone").classList.add("dragging");});
$("#dropzone").addEventListener("dragleave",()=>$("#dropzone").classList.remove("dragging"));
$("#dropzone").addEventListener("drop",event=>{event.preventDefault();$("#dropzone").classList.remove("dragging");uploadFile(event.dataTransfer.files?.[0]);});
$$(".method input").forEach(input=>input.addEventListener("change",()=>selectMethod(input.value)));
bassSliderIds.forEach(id=>$("#"+id).addEventListener("input",()=>{
  updateBassValues();$$(".bass-preset").forEach(node=>node.classList.remove("active"));
}));
$$(".bass-preset").forEach(node=>node.addEventListener("click",()=>applyBassPreset(node.dataset.bassPreset)));
$("#virtualRun").addEventListener("click",runVirtual);
for(const id of ["virtualCutoff","virtualStrength"]) {
  $("#"+id).addEventListener("input",()=>{
    $("#virtualCutoffValue").textContent=$("#virtualCutoff").value+" Hz";
    $("#virtualStrengthValue").textContent=Number($("#virtualStrength").value).toFixed(1);
  });
}
$("#noiseScan").addEventListener("click",startNoiseScan);
$("#noiseRepair").addEventListener("click",startNoiseRepair);
$("#noiseStrength").addEventListener("input",event=>{
  $("#noiseStrengthValue").textContent=`${event.target.value} %`;
});
$("#noiseExport").addEventListener("click",()=>{
  if(state.projectId&&state.noise?.repair)window.location.href=`${BASE}/projects/${state.projectId}/noise/export`;
});
$("#bassRun").addEventListener("click",runBass);
$("#bassExport").addEventListener("click",()=>{
  if(state.projectId&&state.bass)window.location.href=`${BASE}/projects/${state.projectId}/bass/export`;
});
applyBassPreset("transparent");
$("#run").addEventListener("click",runSeparation);
$("#export").addEventListener("click",()=>{if(state.projectId && Object.keys(state.stems).length) window.location.href=`${BASE}/projects/${state.projectId}/export`;});
$("#waveform").addEventListener("click",event=>{
  if(!state.analysis||!state.projectId)return;
  const rect=event.currentTarget.getBoundingClientRect();
  const fraction=Math.max(0,Math.min(1,(event.clientX-rect.left)/rect.width));
  audio.currentTime=fraction*state.analysis.duration_seconds;
  drawWave();
});
$("#waveform").addEventListener("keydown",event=>{
  if(!state.analysis)return;
  if(event.key==="ArrowRight"||event.key==="ArrowLeft"){
    event.preventDefault(); audio.currentTime=Math.max(0,Math.min(state.analysis.duration_seconds,(audio.currentTime||0)+(event.key==="ArrowRight"?1:-1)));drawWave();
  }
});
$("#playButton").addEventListener("click",()=>{
  if(!audio.src)return;
  if(audio.paused)audio.play().catch(()=>toast("Audio konnte nicht abgespielt werden.",true));
  else audio.pause();
});
$("#back10").addEventListener("click",()=>audio.currentTime=Math.max(0,(audio.currentTime||0)-10));
$("#forward10").addEventListener("click",()=>audio.currentTime=Math.min(audio.duration||state.analysis?.duration_seconds||0,(audio.currentTime||0)+10));
$("#seekBar").addEventListener("input",event=>{
  if(!state.analysis)return;
  audio.currentTime=Number(event.target.value)/1000*(audio.duration||state.analysis.duration_seconds);
});
$("#volume").addEventListener("input",event=>{audio.volume=Number(event.target.value)/100;});
audio.addEventListener("play",()=>$("#playButton").textContent="Ⅱ");
audio.addEventListener("pause",()=>$("#playButton").textContent="▶");
audio.addEventListener("ended",()=>$("#playButton").textContent="▶");
audio.addEventListener("timeupdate",()=>{
  const duration=audio.duration||state.analysis?.duration_seconds||0;
  $("#playTime").textContent=timeText(audio.currentTime);
  $("#currentWaveTime").textContent=timeText(audio.currentTime);
  if(duration>0)$("#seekBar").value=String(Math.round(Math.min(1,audio.currentTime/duration)*1000));
  drawWave();
});
audio.addEventListener("error",()=>{
  if(state.projectId && audio.currentSrc)toast("Audiovorschau konnte nicht geladen werden.",true);
});
window.addEventListener("resize",drawWave);
init();