File size: 28,834 Bytes
acdbd95
 
9ceefcc
 
acdbd95
 
 
 
afa34e6
acdbd95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115dd65
9ceefcc
115dd65
 
 
 
 
 
 
 
 
 
 
 
9ceefcc
 
 
 
115dd65
ea04223
115dd65
9ceefcc
115dd65
 
 
 
 
 
 
acdbd95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afa34e6
acdbd95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// STUDIUS P7: Dev-Baukasten (Stratum-Port), Repo-Vorschau (RepoSpace-API), Admin, 2B-Vorlagen (Musik), Veloura-Stile (Bild)
import { STUDIOS } from './widgets.js?v=50';
import { MODULES, esc, setS, keep, result, badge } from './real.js?v=136';
import { ALL, CATS, PRESETS, DEFAULT, ME, getConfig, applyTheme, visibleFor } from './registry.js?v=136';
const $ = (el, s) => el.querySelector(s);
const post = async (u, f) => { const fd = new FormData(); Object.entries(f).forEach(([k, v]) => fd.append(k, v)); const r = await fetch(u, { method: 'POST', body: fd, credentials: 'include' }); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.detail || 'HTTP ' + r.status); return j; };
export const llm = (prompt, system = '', max_tokens = 1200) => post('/api/llm', { prompt, system, max_tokens });
// unified studio shell: header row (badge+status) · actions · output · hand-off bar is added by workspace on result
const shell = (body, b = 'REAL') => `<div class="row sh"><span class="badge real">${b}</span><span class="stat"></span></div>${body}`;

/* ---------- 1 DEV-BAUKASTEN (Stratum-Port: Prompt → HTML · Preview · Zeichenwerkzeuge → Follow-up) ---------- */
const DEVT = { Landingpage: 'Moderne Landingpage für ein Produkt, Hero, 3 Features, Call-to-Action', Dashboard: 'Dashboard mit 4 Kennzahl-Karten, einem Balkendiagramm (Canvas) und Tabelle', 'Mini-Spiel': 'Kleines Browser-Spiel mit Canvas, Punktestand und Neustart-Knopf', Formular: 'Kontaktformular mit Validierung und Danke-Meldung', Portfolio: 'Portfolio-Seite mit Raster aus Projekten und Filter' };
const SYS = 'Du bist ein Senior-Frontend-Entwickler. Antworte NUR mit einer vollständigen, eigenständigen index.html (inline CSS+JS, keine externen Ressourcen außer Google Fonts optional). Kein Markdown, keine Erklärung.';
const cleanHtml = (t) => { t = String(t || '').replace(/^[\s\S]*?```(?:html)?\s*/i, m => m.includes('```') ? '' : m).replace(/```[\s\S]*$/, ''); const i = t.search(/<!doctype|<html/i); return (i > 0 ? t.slice(i) : t).trim(); };
STUDIOS.push({ id: 'dev', icon: '🧱', name: 'Dev-Baukasten', like: 'Prompt → Web-App + Zeichnen', real: 'API', accepts: ['text', 'image'], build(el) {
  el.innerHTML = shell(`<div class="row"><select class="tpl" aria-label="Vorlage">${Object.keys(DEVT).map(k => `<option>${k}</option>`).join('')}</select><button class="btn alt use">Vorlage übernehmen</button></div>
  <textarea class="pr" rows="3" aria-label="Was soll gebaut werden?" placeholder="Beschreibe die App…">${DEVT.Landingpage}, schwarz-gold, deutsch</textarea>
  <div class="row"><button class="btn go">Bauen</button><button class="btn alt dl" disabled>⬇ HTML</button><button class="btn alt src">Quelltext</button></div>
  <div class="devstage"><iframe class="pv" sandbox="allow-scripts" title="Vorschau"></iframe><canvas class="ann"></canvas></div>
  <div class="row tools" role="toolbar" aria-label="Zeichenwerkzeuge"><button class="btn alt pen on" title="Stift">✎ Markieren</button>${['#ff4d57', '#f2c94c', '#58a6ff', '#ffffff'].map((c, i) => `<button class="sw${i ? '' : ' on'}" data-c="${c}" style="background:${c}" aria-label="Farbe ${c}"></button>`).join('')}<button class="btn alt undo" title="Rückgängig">↶</button><button class="btn alt clr" title="Alles löschen">⌫</button></div>
  <div class="row"><input class="note" aria-label="Änderungswunsch" placeholder="Was soll an den Markierungen anders sein? (z. B. größer, andere Farbe)"><button class="btn fix" disabled>Änderung anwenden</button></div>
  <pre class="code" hidden></pre><div class="credit">Baukasten-Prinzip aus 2Btainment/Stratum (Annotation-Layer) · LLM via HF Inference (angemeldet) oder Llama 3.2 3B</div>`);
  keep(el); let html = '', strokes = [], cur = null, color = '#ff4d57', drawOn = true;
  const pv = $(el, '.pv'), cv = $(el, '.ann'), x = cv.getContext('2d');
  const fit = () => { const r = cv.getBoundingClientRect(); cv.width = r.width; cv.height = r.height; paint(); };
  const paint = () => { x.clearRect(0, 0, cv.width, cv.height); x.lineWidth = 3; x.lineCap = 'round'; strokes.forEach(s => { x.strokeStyle = s.c; x.beginPath(); s.p.forEach(([a, b], i) => i ? x.lineTo(a * cv.width, b * cv.height) : x.moveTo(a * cv.width, b * cv.height)); x.stroke(); }); };
  const pt = (e) => { const r = cv.getBoundingClientRect(); return [(e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height]; };
  cv.onpointerdown = e => { if (!drawOn) return; cv.setPointerCapture(e.pointerId); cur = { c: color, p: [pt(e)] }; strokes.push(cur); };
  cv.onpointermove = e => { if (cur) { cur.p.push(pt(e)); paint(); } };
  cv.onpointerup = () => { cur = null; $(el, '.fix').disabled = !html; };
  $(el, '.pen').onclick = e => { drawOn = !drawOn; e.target.classList.toggle('on', drawOn); cv.style.pointerEvents = drawOn ? 'auto' : 'none'; };
  el.querySelectorAll('.sw').forEach(b => b.onclick = () => { color = b.dataset.c; el.querySelectorAll('.sw').forEach(o => o.classList.toggle('on', o === b)); });
  $(el, '.undo').onclick = () => { strokes.pop(); paint(); }; $(el, '.clr').onclick = () => { strokes = []; paint(); };
  $(el, '.use').onclick = () => { $(el, '.pr').value = DEVT[$(el, '.tpl').value] + ', schwarz-gold, deutsch'; };
  $(el, '.src').onclick = () => { const c = $(el, '.code'); c.hidden = !c.hidden; c.textContent = html; };
  const regions = () => strokes.map((s, i) => { const xs = s.p.map(p => p[0]), ys = s.p.map(p => p[1]); const f = v => Math.round(v * 100); return `Markierung ${i + 1}: Bereich x ${f(Math.min(...xs))}–${f(Math.max(...xs))} %, y ${f(Math.min(...ys))}–${f(Math.max(...ys))} % des sichtbaren Viewports`; }).join('\n');
  const show = (h, how) => { html = h; pv.srcdoc = h; $(el, '.dl').disabled = false; $(el, '.fix').disabled = false; strokes = []; paint(); $(el, '.code').textContent = h;
    result($(el, '.devstage'), { kind: 'text', mime: 'text/html', text: h, name: 'dev-' + Date.now() + '.html', studio: 'dev', prompt: $(el, '.pr').value }); setS(el, '✔ ' + how); };
  const ask = async (btn, prompt) => { btn.disabled = true; setS(el, 'Baue…'); try { const r = await llm(prompt, SYS, 3500); const h = cleanHtml(r.text); if (!/<\w/.test(h)) throw new Error('keine HTML-Antwort'); show(h, (r.model || '').split('/').pop()); badge(el, 'REAL'); } catch (e) { setS(el, '⚠ ' + e.message, true); } finally { btn.disabled = false; } };
  $(el, '.go').onclick = e => ask(e.target, $(el, '.pr').value);
  $(el, '.fix').onclick = e => { const n = $(el, '.note').value.trim(); if (!strokes.length && !n) return setS(el, '⚠ Erst markieren oder Wunsch eingeben', true);
    ask(e.target, `Aktuelle index.html:\n${html}\n\nÄnderungswunsch: ${n || 'Verbessere die markierten Bereiche'}\n${regions()}\nGib die komplette geänderte index.html zurück.`); };
  $(el, '.dl').onclick = () => { const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([html], { type: 'text/html' })); a.download = 'studius-app.html'; a.click(); };
  requestAnimationFrame(fit); addEventListener('resize', fit, { once: true });
} });
MODULES.dev = { id: 'dev', name: 'Dev-Baukasten', backend: 'HF Inference', inputs: [{ name: 'prompt', type: 'text' }], outputs: [{ kind: 'text' }],
  actions: { build: { desc: 'Baut aus einer Beschreibung eine eigenständige HTML-Web-App', params: { prompt: 'string' }, run: async ({ prompt }) => { const r = await llm(prompt, SYS, 3500); return { kind: 'text', mime: 'text/html', text: cleanHtml(r.text), name: 'dev-' + Date.now() + '.html' }; } } } };

/* ---------- 2 REPO-VORSCHAU (RepoSpace-API) ---------- */
STUDIOS.push({ id: 'repo', icon: '🚀', name: 'Repo-Vorschau', like: 'GitHub-Repo live testen', real: 'API', build(el) {
  el.innerHTML = shell(`<div class="row"><input class="u" aria-label="GitHub-URL" value="https://github.com/mdn/beginner-html-site-styled"><button class="btn go">Starten</button></div>
  <div class="row"><a class="btn alt op" hidden target="_blank" rel="noopener">↗ In neuem Tab</a></div><iframe class="rv" hidden title="Repo-Vorschau" sandbox="allow-scripts allow-same-origin allow-forms"></iframe><pre class="code lg" hidden></pre>
  <div class="credit">via 2Btainment/repospace · statische Seiten, Vite-Builds, kleine Flask/FastAPI-Apps · Auto-Stopp nach 15 min</div>`);
  keep(el); let t = null;
  $(el, '.go').onclick = async (e) => { e.target.disabled = true; clearInterval(t); setS(el, 'Klone & baue…');
    try { const s = await post('/api/repo/session', { repo_url: $(el, '.u').value.trim() }); const poll = async () => { if (!el.isConnected) return clearInterval(t);
        const r = await (await fetch('/api/repo/session/' + s.id)).json(); setS(el, 'Status: ' + r.status); const lg = $(el, '.lg'); lg.hidden = !r.logs; lg.textContent = r.logs || '';
        if (r.preview_url) { clearInterval(t); const u = r.base + r.preview_url; const f = $(el, '.rv'); f.src = u; f.hidden = false; const a = $(el, '.op'); a.href = u; a.hidden = false; setS(el, '✔ läuft'); e.target.disabled = false; result(f, { kind: 'text', mime: 'text/uri-list', text: u, name: 'repo-preview.url', studio: 'repo' }); }
        else if (r.status === 'failed' || r.status === 'stopped') { clearInterval(t); setS(el, '⚠ ' + r.status + (r.error ? ': ' + r.error : ''), true); e.target.disabled = false; } };
      t = setInterval(poll, 2500); poll();
    } catch (er) { setS(el, '⚠ ' + er.message, true); e.target.disabled = false; } };
} });

/* ---------- SPACE-PAKET (SpaceForge-API über /api/forge): Space → Widget/PWA/APK/AppImage/PKGBUILD/MCP ---------- */
const SF = 'https://2btainment-spaceforge.hf.space/api'; // Direktweg (CORS erlaubt), falls der Proxy vom HF-Limit gebremst wird
const FT = [['pwa', 'PWA'], ['html_widget', 'Widget'], ['android', 'APK'], ['linux_appimage', 'AppImage'], ['arch_pkgbuild', 'PKGBUILD'], ['mcp', 'MCP']];
STUDIOS.push({ id: 'forge', icon: '📦', name: 'Space-Paket', like: 'Space → PWA · APK · MCP', real: 'API', build(el) {
  el.innerHTML = shell(`<div class="row"><select class="sp" aria-label="Space wählen"><option value="">Lade Spaces…</option></select></div>
  <div class="row"><input class="u" aria-label="oder Space-URL" placeholder="oder URL: https://huggingface.co/spaces/owner/name"></div>
  <div class="row ft">${FT.map(([v, l], i) => `<label class="chip"><input type="checkbox" value="${v}"${i ? '' : ' checked'}> ${l}</label>`).join('')}</div>
  <div class="row"><button class="btn go">Paket bauen</button></div><div class="out"></div><pre class="code lg" hidden></pre>
  <div class="credit">via 2Btainment/spaceforge · Ergebnis 1 h abrufbar · APK als Capacitor-Wrapper (braucht die Live-Space-URL)</div>`);
  keep(el); let t = null; const sel = $(el, '.sp');
  fetch('/api/forge/spaces').then(r => r.json()).then(d => { sel.innerHTML = (d.spaces || []).map(s => `<option${s === '2Btainment/studius' ? ' selected' : ''}>${esc(s)}</option>`).join(''); }).catch(() => { sel.innerHTML = '<option value="">(Liste nicht erreichbar – URL eingeben)</option>'; });
  $(el, '.go').onclick = async (e) => { const space = $(el, '.u').value.trim() || sel.value, tg = [...el.querySelectorAll('.ft input:checked')].map(i => i.value);
    if (!space || !tg.length) return setS(el, '⚠ Space und mindestens ein Ziel wählen', true);
    e.target.disabled = true; clearInterval(t); $(el, '.out').innerHTML = ''; setS(el, 'Starte Build…');
    try { let b, D = false; try { b = await post('/api/forge/build', { space, targets: tg.join(',') }); } catch (er) { if (!/Limit|429|502/.test(er.message)) throw er; D = true; setS(el, 'Proxy ausgelastet – baue direkt über SpaceForge…');
        const m = space.match(/([\w.-]+)\/([\w.-]+)\/?$/); const r = await fetch(SF + '/build', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ url: `https://huggingface.co/spaces/${m[1]}/${m[2]}`, targets: tg, options: {} }) }); if (!r.ok) throw new Error('SpaceForge HTTP ' + r.status); b = await r.json(); }
      const st = async (id) => D ? { ...(await (await fetch(`${SF}/build/${id}`)).json()), logs: await (await fetch(`${SF}/build/${id}/logs`)).text().catch(() => '') } : (await fetch('/api/forge/build/' + id)).json(), dl = (id, k) => D ? `${SF}/build/${id}/download?target=${k}` : `/api/forge/build/${id}/download?target=${k}`; let fin = false; const poll = async () => { if (!el.isConnected || fin) return clearInterval(t);
        const r = await st(b.build_id); const lg = $(el, '.lg'); lg.hidden = !r.logs; lg.textContent = r.logs || ''; lg.scrollTop = 1e6;
        const n = Object.keys(r.artifacts || {}).length + Object.keys(r.errors || {}).length; setS(el, `Status: ${r.status} · ${n}/${tg.length} Ziele`);
        if (!fin && (r.status === 'done' || r.status === 'failed' || r.status === 'error')) { fin = true; clearInterval(t); e.target.disabled = false; const out = $(el, '.out');
          for (const [k, a] of Object.entries(r.artifacts || {})) { const row = document.createElement('div'); row.className = 'row'; row.innerHTML = `<span class="badge real">${esc(FT.find(f => f[0] === k)?.[1] || k)}</span> <b>${esc(a.filename)}</b> <small class="muted">${(a.size / 1024).toFixed(1)} KB · ${esc(a.notes || '')}</small>`; out.append(row);
            const blob = await (await fetch(dl(b.build_id, k))).blob(), u = URL.createObjectURL(blob); const d = document.createElement('a'); d.className = 'btn alt'; d.href = u; d.download = a.filename; d.textContent = '⬇ Download'; row.append(d);
            result(row, { kind: 'file', mime: a.media_type || 'application/zip', blob, url: u, name: a.filename, path: `projects/forge/${a.filename}`, studio: 'forge', prompt: space + ' → ' + k }); }
          for (const [k, m] of Object.entries(r.errors || {})) out.insertAdjacentHTML('beforeend', `<div class="row"><span class="badge">${esc(k)}</span> <small class="err">⚠ ${esc(String(m).slice(0, 200))}</small></div>`);
          setS(el, r.status === 'done' ? '✔ fertig' : '⚠ ' + r.status, r.status !== 'done'); } };
      t = setInterval(poll, 2500); poll();
    } catch (er) { setS(el, '⚠ ' + er.message, true); e.target.disabled = false; } };
} });

/* ---------- 3 2B-STUDIO-VORLAGEN im Musik-Studio · VELOURA-Stile im Bild-Studio (Ports, keine Inseln) ---------- */
let TPL = null; const tpls = async () => TPL ||= (await fetch('assets/music-templates.json?v=1')).json();
const VELOURA = { Kein: '', Cinematic: 'cinematic composition, natural skin texture, detailed lighting, 35mm film, subtle film grain, shallow depth of field', Editorial: 'high-end editorial photography, controlled studio lighting, precise composition, realistic detail', 'Moody Night': 'moody night photography, practical lights, cinematic shadows, subtle color contrast, atmospheric depth', 'Natural Portrait': 'natural portrait photography, soft window light, realistic texture, gentle depth of field' };
addEventListener('studius-opened', async ({ detail: { id, el } }) => {
  if (id === 'music') { const inp = el.querySelector('input'); if (!inp) return; const T = await tpls(); const box = document.createElement('div'); box.className = 'chips';
    const G = { usecase: 'Einsatz', genre: 'Genre', fx: 'FX' }; box.innerHTML = `<select aria-label="Vorlage (2B-Studio)"><option value="">Vorlage wählen (30 aus 2B-Studio)…</option>${Object.entries(G).map(([c, n]) => `<optgroup label="${n}">${T.filter(t => t.c === c).map(t => `<option value="${t.id}">${t.i} ${esc(t.n)}</option>`).join('')}</optgroup>`).join('')}</select>`;
    inp.before(box); box.querySelector('select').onchange = (e) => { const t = T.find(x => x.id === e.target.value); if (t) inp.value = `${t.s}, ${t.ins}, ${t.m}, ${t.bpm} BPM, ${t.k}, ${t.p}${t.v ? '' : ', instrumental'}`; }; }
  if (id === 'image') { const host = el.querySelector('.tp'); if (!host) return; const add = () => { const inp = host.querySelector('input[aria-label="Bild-Prompt"]'); if (!inp || host.querySelector('.vel')) return; const s = document.createElement('select'); s.className = 'vel'; s.setAttribute('aria-label', 'Stil (Veloura Muse)');
      s.innerHTML = Object.keys(VELOURA).map(k => `<option>${k === 'Kein' ? 'Stil: keiner' : 'Stil: ' + k}</option>`).join(''); inp.after(s); let base = inp.value;
      s.onchange = () => { const k = Object.keys(VELOURA)[s.selectedIndex]; base = inp.value.split(', cinematic composition')[0].split(', high-end editorial')[0].split(', moody night')[0].split(', natural portrait')[0]; inp.value = VELOURA[k] ? base + ', ' + VELOURA[k] : base; }; };
    add(); new MutationObserver(add).observe(host, { childList: true }); }
});

/* ---------- 4 ADMIN (Owner) ---------- */
const NL_SYS = 'Du übersetzt deutsche Admin-Befehle für eine Studio-App in JSON. Antworte NUR mit JSON: {"studios":{"<id>":{"on":true|false,"vis":"all"|"auth"|"owner"}},"theme":{"gold":"#rrggbb","bright":0.6-1.4},"world":{"quality":"low"|"high"|"auto"},"preset":"Einfach"|"Creator"|"Pro"}. Nur geänderte Felder. Studio-IDs: ';
const merge = (a, b) => { const o = JSON.parse(JSON.stringify(a)); for (const [k, v] of Object.entries(b || {})) o[k] = v && typeof v === 'object' && !Array.isArray(v) ? merge(o[k] || {}, v) : v; return o; };
const shade = (hex, f) => { const n = parseInt(hex.slice(1), 16); const c = [n >> 16, n >> 8 & 255, n & 255].map(v => Math.max(0, Math.min(255, Math.round(f > 0 ? v + (255 - v) * f : v * (1 + f))))); return '#' + c.map(v => v.toString(16).padStart(2, '0')).join(''); };
// rule parser first (instant, offline), LLM only for what rules do not understand
function rules(txt, cfg) { const t = txt.toLowerCase(), d = {}; const ids = [...ALL.values()];
  const syn = { video: ['videogen', 'videoedit'], musik: ['music'], bild: ['image'], chat: ['chat'], shop: ['shop'], radio: ['radio'], telefon: ['phone'], docs: ['docs'], whiteboard: ['board'], avatar: ['avatar'], agenten: ['agent'], dev: ['dev', 'repo', 'code', 'sandbox'], social: ['social'], marke: ['brand'], branding: ['brand'], mastering: ['master'], stems: ['stems'], canvas: ['canvas'], automation: ['auto'], workspace: ['workspace'], community: ['community'], repo: ['repo'], baukasten: ['dev'], sandbox: ['sandbox'], code: ['code'] };
  for (const part of t.split(/\bund\b|,|;|\./)) { const off = /\b(aus|ausschalten|deaktiv|verstecken|weg|entfern)/.test(part), on = /\b(an|ein|einschalten|aktiv|zeigen|anzeigen)\b/.test(part); const vis = /nur (für )?(mich|owner|admin)/.test(part) ? 'owner' : /angemeldet|eingeloggt/.test(part) ? 'auth' : /alle\b|öffentlich/.test(part) ? 'all' : null;
    const hit = new Set(); for (const [w, l] of Object.entries(syn)) if (part.includes(w)) l.forEach(i => hit.add(i)); ids.forEach(s => { if (part.includes(s.name.toLowerCase())) hit.add(s.id); }); for (const c of CATS) if (part.includes(c.toLowerCase())) ids.filter(s => s.cat === c).forEach(s => hit.add(s.id));
    hit.forEach(id => { if (id === 'admin') return; d.studios ||= {}; d.studios[id] = { ...(d.studios[id] || {}) }; if (off || on) d.studios[id].on = !off; if (vis) d.studios[id].vis = vis; });
    const g = (cfg.theme || {}).gold || '#f2c94c'; if (/gold/.test(part) && /heller|leuchtend|hell\b/.test(part)) (d.theme ||= {}).gold = shade(g, .25); if (/gold/.test(part) && /dunkler|satter/.test(part)) (d.theme ||= {}).gold = shade(g, -.2);
    if (/welt|3d|grafik|qualität/.test(part)) { if (/niedrig|leicht|schnell|low|aus/.test(part)) (d.world ||= {}).quality = 'low'; else if (/hoch|schön|high|max/.test(part)) (d.world ||= {}).quality = 'high'; else if (/auto/.test(part)) (d.world ||= {}).quality = 'auto'; }
    if (/(alles )?heller\b/.test(part) && !/gold/.test(part)) (d.theme ||= {}).bright = Math.min(1.4, ((cfg.theme || {}).bright ?? 1) + .15); if (/(alles )?dunkler\b/.test(part) && !/gold/.test(part)) (d.theme ||= {}).bright = Math.max(.6, ((cfg.theme || {}).bright ?? 1) - .15);
    for (const p of Object.keys(PRESETS)) if (part.includes(p.toLowerCase())) d.preset = p; }
  if (d.preset) d.studios = merge(presetDiff(d.preset), d.studios || {}); return d; }
function presetDiff(p) { const on = new Set(PRESETS[p]); const o = {}; ALL.forEach(s => { if (s.id !== 'admin') o[s.id] = { on: on.has(s.id) }; }); return o; }
function diffLines(a, b) { const out = []; ALL.forEach(s => { const x = (a.studios || {})[s.id] || {}, y = (b.studios || {})[s.id] || {}; const xo = x.on !== false, yo = y.on !== false; if (xo !== yo) out.push(`${yo ? '🟢' : '⚫'} ${s.name}: ${yo ? 'an' : 'aus'}`); if ((x.vis || 'all') !== (y.vis || 'all')) out.push(`👁 ${s.name}: ${{ all: 'alle', auth: 'angemeldete', owner: 'nur ich' }[y.vis || 'all']}`); });
  const ta = a.theme || {}, tb = b.theme || {}; if (ta.gold !== tb.gold) out.push(`🎨 Gold: ${ta.gold} → ${tb.gold}`); if ((ta.bright ?? 1) !== (tb.bright ?? 1)) out.push(`☀ Helligkeit: ${ta.bright ?? 1} → ${tb.bright}`); if ((a.world || {}).quality !== (b.world || {}).quality) out.push(`🌍 Welt-Qualität: ${(b.world || {}).quality}`); if (a.preset !== b.preset) out.push(`📦 Preset: ${b.preset}`); return out; }
STUDIOS.push({ id: 'admin', icon: '⚙', name: 'Admin', like: 'Alles steuern – kinderleicht', real: 'LOKAL', build(el) {
  let cfg = merge(DEFAULT, getConfig()), draft = null; const hist = JSON.parse(sessionStorage.getItem('studius-admin-hist') || '[]');
  const owner = ME.isOwner || location.search.includes('admin=demo');
  el.innerHTML = shell(`${owner ? '' : '<p class="err">🔒 Nur für den Owner (2Btainment). Anmelden über Workspace → HF-Login. Du siehst eine Vorschau, Speichern ist gesperrt.</p>'}
  <div class="say"><label>💬 Sag's einfach</label><div class="row"><input class="nl" placeholder="z. B. „Schalte Video aus und mach Gold heller“"><button class="btn ask">Vorschau</button></div><div class="diff" aria-live="polite"></div><div class="row"><button class="btn ok" disabled>✔ Übernehmen</button><button class="btn alt no" disabled>Verwerfen</button><button class="btn alt undo" ${hist.length ? '' : 'disabled'}>↶ Rückgängig</button></div></div>
  <div class="adm-sec"><label>📦 Preset</label><div class="row presets">${Object.keys(PRESETS).map(p => `<button class="btn alt pre" data-p="${p}">${p}<small>${PRESETS[p].length} Studios</small></button>`).join('')}</div></div>
  <div class="adm-sec"><label>🧩 Studios <small>Klick = an/aus · 👁 = wer sieht es</small></label><div class="tiles"></div></div>
  <div class="adm-sec"><label>🎨 Look <small>Live-Vorschau</small></label><div class="row"><input type="color" class="gold" aria-label="Gold-Ton"><input type="range" class="br" min=".6" max="1.4" step=".05" aria-label="Helligkeit"><select class="wq" aria-label="Welt-Qualität"><option value="auto">Welt: Auto (nach FPS)</option><option value="low">Welt: leicht</option><option value="high">Welt: schön</option></select></div></div>
  <div class="adm-sec"><label>📊 Überblick</label><div class="ov">Lade…</div></div>
  <div class="adm-sec"><label>💾 Config</label><div class="row"><input class="bk" placeholder="Bucket (z. B. 2Btainment/studius-ws)" value="${esc(ME.bucket || window.__ws?.bucket || '')}"><button class="btn alt exp">⬇ Export</button><label class="btn alt imp">⬆ Import<input type="file" accept=".json" hidden></label></div></div>`, owner ? 'OWNER' : 'VORSCHAU');
  keep(el);
  const propose = (next, why) => { draft = next; const l = diffLines(cfg, next); $(el, '.diff').innerHTML = l.length ? `<b>${esc(why)}</b><ul>${l.map(x => `<li>${esc(x)}</li>`).join('')}</ul>` : '<i>Keine Änderung erkannt.</i>'; $(el, '.ok').disabled = !l.length || !owner; $(el, '.no').disabled = !l.length; applyTheme(next.theme); };
  const commit = async (next, undo) => { if (!undo) hist.push(cfg); sessionStorage.setItem('studius-admin-hist', JSON.stringify(hist.slice(-30))); cfg = next; draft = null; localStorage.setItem('studius-config', JSON.stringify(cfg)); applyTheme(cfg.theme); window.__studiusQ?.(cfg.world?.quality || 'auto'); draw();
    $(el, '.diff').innerHTML = ''; $(el, '.ok').disabled = $(el, '.no').disabled = true; $(el, '.undo').disabled = !hist.length;
    try { const r = await post('/api/config', { config: JSON.stringify(cfg), bucket: $(el, '.bk').value.trim() }); setS(el, '✔ Gespeichert' + (r.saved ? ' → ' + r.saved : ' (Server)') + ' · Studios-Liste gilt nach Neuladen'); } catch (e) { setS(el, '⚠ Nur lokal gespeichert: ' + e.message, true); } };
  const draw = () => { $(el, '.tiles').innerHTML = CATS.map(c => `<div class="tg"><h5>${c}</h5>${[...ALL.values()].filter(s => s.cat === c && s.id !== 'admin').map(s => { const o = (cfg.studios || {})[s.id] || {}; const on = o.on !== false; const v = o.vis || 'all'; return `<div class="tile ${on ? 'on' : ''}" data-id="${s.id}"><button class="tg-on" aria-pressed="${on}" title="an/aus">${s.icon} ${esc(s.name)}</button><button class="tg-vis" title="Sichtbarkeit">${{ all: '👁 alle', auth: '🔑 angemeldet', owner: '🔒 nur ich' }[v]}</button></div>`; }).join('')}</div>`).join('');
    el.querySelectorAll('.pre').forEach(b => b.classList.toggle('on', b.dataset.p === cfg.preset)); $(el, '.gold').value = cfg.theme?.gold || '#f2c94c'; $(el, '.br').value = cfg.theme?.bright ?? 1; $(el, '.wq').value = cfg.world?.quality || 'auto'; };
  draw();
  $(el, '.tiles').onclick = (e) => { const t = e.target.closest('.tile'); if (!t) return; const id = t.dataset.id, o = (cfg.studios || {})[id] || {};
    if (e.target.closest('.tg-on')) propose(merge(cfg, { studios: { [id]: { on: o.on === false } } }), ALL.get(id).name + ' umschalten');
    else if (e.target.closest('.tg-vis')) { const n = { all: 'auth', auth: 'owner', owner: 'all' }[o.vis || 'all']; propose(merge(cfg, { studios: { [id]: { vis: n } } }), 'Sichtbarkeit ändern'); } };
  el.querySelectorAll('.pre').forEach(b => b.onclick = () => propose(merge(cfg, { preset: b.dataset.p, studios: presetDiff(b.dataset.p) }), 'Preset ' + b.dataset.p));
  $(el, '.gold').oninput = e => propose(merge(cfg, { theme: { gold: e.target.value } }), 'Gold-Ton'); $(el, '.br').oninput = e => propose(merge(cfg, { theme: { bright: +e.target.value } }), 'Helligkeit');
  $(el, '.wq').onchange = e => propose(merge(cfg, { world: { quality: e.target.value } }), 'Welt-Qualität');
  $(el, '.ok').onclick = () => draft && commit(draft); $(el, '.no').onclick = () => { draft = null; $(el, '.diff').innerHTML = ''; applyTheme(cfg.theme); draw(); $(el, '.ok').disabled = $(el, '.no').disabled = true; };
  $(el, '.undo').onclick = () => { const prev = hist.pop(); if (prev && owner) commit(prev, true); };
  const ask = async () => { const txt = $(el, '.nl').value.trim(); if (!txt) return; let d = rules(txt, cfg); let how = 'Verstanden (sofort)';
    if (!Object.keys(d).length) { setS(el, 'Frage KI…'); try { const r = await llm(txt, NL_SYS + [...ALL.keys()].join(', '), 400); const m = r.text.match(/\{[\s\S]*\}/); d = m ? JSON.parse(m[0]) : {}; if (d.preset && PRESETS[d.preset]) d.studios = merge(presetDiff(d.preset), d.studios || {}); how = 'Verstanden (KI)'; } catch (e) { setS(el, '⚠ ' + e.message, true); } }
    propose(merge(cfg, d), how + ': „' + txt + '“'); setS(el, ''); };
  $(el, '.ask').onclick = ask; $(el, '.nl').onkeydown = e => { e.stopPropagation(); if (e.key === 'Enter') ask(); };
  $(el, '.exp').onclick = () => { const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([JSON.stringify(cfg, null, 1)], { type: 'application/json' })); a.download = 'studius-config.json'; a.click(); };
  $(el, '.imp input').onchange = async e => { try { propose(merge(DEFAULT, JSON.parse(await e.target.files[0].text())), 'Import'); } catch (er) { setS(el, '⚠ ' + er.message, true); } };
  (async () => { const ov = $(el, '.ov'); const card = (k, v) => `<div class="kpi"><b>${v}</b><span>${k}</span></div>`; let h = '';
    const on = [...ALL.values()].filter(s => visibleFor(s.id, cfg)).length; h += card('Studios aktiv', on + '/' + ALL.size);
    try { const z = await (await fetch('/healthz')).json(); h += card('Server', z.ok ? '🟢 ok' : '🔴'); h += card('Login', z.oauth ? 'HF-OAuth' : 'aus'); } catch (e) { h += card('Server', '🔴'); }
    try { const q = await (await fetch('/api/quota', { credentials: 'include' })).json(); h += card('GPU-Quota', q.ok ? Math.round(q.remaining) + ' s' : '–'); } catch (e) {}
    const ws = window.__ws; h += card('Bucket', ws?.bucket ? esc(ws.bucket) : '–'); h += card('Angemeldet', ME.signedIn ? (ME.isOwner ? 'Owner' : 'ja') : 'nein');
    ov.innerHTML = `<div class="kpis">${h}</div><div class="row"><button class="btn alt gows">Jobs & Freigaben → Workspace</button><button class="btn alt goag">Agenten & Rechte →</button></div>`;
    $(el, '.gows').onclick = () => document.getElementById('wsbtn')?.click(); $(el, '.goag').onclick = () => document.getElementById('beebtn')?.click(); })();
} });