File size: 28,221 Bytes
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3437bb4
 
 
 
 
8af7605
 
 
3437bb4
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3437bb4
8af7605
3437bb4
 
8af7605
 
 
 
 
 
 
 
 
 
 
3437bb4
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3437bb4
 
8af7605
 
 
 
 
 
 
 
 
6138ad1
 
 
 
 
 
 
 
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b48b1fc
 
 
8af7605
b48b1fc
 
 
 
 
8af7605
 
 
 
 
 
 
b48b1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb1cc99
 
 
 
 
 
814ee46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc46458
 
 
 
 
 
65658e1
8af7605
fc46458
 
8af7605
814ee46
 
8af7605
814ee46
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
814ee46
8af7605
 
 
 
 
 
 
 
 
 
814ee46
8af7605
 
 
 
 
 
 
2714d18
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2714d18
8af7605
 
 
 
 
 
 
 
bb1cc99
 
 
 
 
 
 
 
 
 
 
 
 
8af7605
bb1cc99
 
 
 
 
 
 
 
 
3437bb4
 
 
 
 
 
 
 
 
 
 
 
 
8af7605
bb1cc99
 
 
 
8af7605
bb1cc99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9784e1d
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b48b1fc
8af7605
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
/* PixRick online: le stesse API dell'app sul computer, ma la galleria vive nel browser
   e la generazione passa dal motore su Hugging Face. Niente immagini restano sul server. */
(() => {
  "use strict";

  const DB_NAME = "pixrick";
  const DRAFT_TTL_MS = 24 * 3600 * 1000;
  const THUMB_SIDE = 640;
  const MAX_INPUT_SIDE = 2048;
  const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
  const ENGINE_PATH = "/motore/";

  /* ---------- archivio nel browser ---------- */

  let dbPromise = null;
  function db() {
    dbPromise ||= new Promise((resolve, reject) => {
      const req = indexedDB.open(DB_NAME, 1);
      req.onupgradeneeded = () => {
        const d = req.result;
        d.createObjectStore("blobs");
        const items = d.createObjectStore("items", { keyPath: "file" });
        items.createIndex("scope", "scope");
        d.createObjectStore("kv");
      };
      req.onsuccess = () => resolve(req.result);
      req.onerror = () => reject(req.error);
    });
    return dbPromise;
  }

  async function tx(stores, mode, work) {
    const d = await db();
    return new Promise((resolve, reject) => {
      const t = d.transaction(stores, mode);
      let out;
      t.oncomplete = () => resolve(out);
      t.onerror = () => reject(t.error);
      t.onabort = () => reject(t.error || new Error("Archivio del browser non disponibile."));
      out = work(...[].concat(stores).map((s) => t.objectStore(s)));
    });
  }

  const req2p = (r) => new Promise((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); });

  // Le immagini si salvano come ArrayBuffer: Safari in navigazione privata rifiuta i Blob in IndexedDB.
  const pack = async (blob) => (blob instanceof Blob ? { type: blob.type, data: await blob.arrayBuffer() } : blob);
  const unpack = (value) => (value && !(value instanceof Blob) && value.data ? new Blob([value.data], { type: value.type }) : value);

  async function readRaw(path) {
    const d = await db();
    return req2p(d.transaction("blobs").objectStore("blobs").get(path));
  }
  async function readBlob(path) {
    return unpack(await readRaw(path));
  }
  async function readItem(file) {
    const d = await db();
    return req2p(d.transaction("items").objectStore("items").get(file));
  }
  async function itemsIn(scope) {
    const d = await db();
    return req2p(d.transaction("items").objectStore("items").index("scope").getAll(scope));
  }
  async function kvGet(key, fallback) {
    const d = await db();
    const v = await req2p(d.transaction("kv").objectStore("kv").get(key));
    return v === undefined ? fallback : v;
  }
  const kvSet = (key, value) => tx("kv", "readwrite", (s) => { s.put(value, key); });

  /* ---------- immagini ---------- */

  const pad = (n) => String(n).padStart(2, "0");
  const today = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  const clock = (d = new Date()) => `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
  const stamp = (d = new Date()) => `${today(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  const rand = () => Math.random().toString(16).slice(2, 8);

  async function bitmap(blob) {
    try {
      return await createImageBitmap(blob, { imageOrientation: "from-image" });
    } catch {
      throw new Error("Il file non è un'immagine leggibile.");
    }
  }

  function canvasOf(w, h) {
    const c = document.createElement("canvas");
    c.width = w;
    c.height = h;
    return c;
  }

  const toBlob = (canvas, type, quality) => new Promise((r) => canvas.toBlob(r, type, quality));

  async function thumbnail(blob) {
    const bmp = await bitmap(blob);
    const k = Math.min(1, THUMB_SIDE / Math.max(bmp.width, bmp.height));
    const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
    c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height);
    bmp.close?.();
    return (await toBlob(c, "image/webp", 0.84)) || toBlob(c, "image/png");
  }

  /** Ruota secondo l'EXIF, rimpicciolisce e riscrive in PNG: via EXIF e posizione GPS. */
  async function cleanUpload(file) {
    if (file.size > MAX_UPLOAD_BYTES) throw new Error("Immagine troppo pesante (massimo 25 MB).");
    const bmp = await bitmap(file);
    const k = Math.min(1, MAX_INPUT_SIDE / Math.max(bmp.width, bmp.height));
    const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
    const ctx = c.getContext("2d");
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(bmp, 0, 0, c.width, c.height);
    bmp.close?.();
    return { blob: await toBlob(c, "image/png"), width: c.width, height: c.height };
  }

  /* ---------- galleria ---------- */

  // Percorsi come sul computer: bozze in _bozze/, galleria per giorno, cestino in _cestino/.
  const SCOPE_PREFIX = { bozze: "_bozze/", galleria: "", cestino: "_cestino/" };
  const thumbPath = (scope, day, stem) => (scope === "galleria" ? `.miniature/${day}/${stem}.webp` : `${SCOPE_PREFIX[scope]}${day}/${stem}.webp`);

  function splitFile(file) {
    const parts = file.split("/");
    const name = parts.pop();
    return { day: parts.pop(), stem: name.replace(/\.png$/, "") };
  }

  async function storeItem(scope, meta, png, thumb) {
    const day = today();
    const stem = meta._stem || `${clock()}_${meta.modalita || "crea"}_${meta.modello || "img"}_${rand()}`;
    delete meta._stem;
    const file = `${SCOPE_PREFIX[scope]}${day}/${stem}.png`;
    const mini = thumbPath(scope, day, stem);
    const item = { ...meta, file, miniatura: mini, bozza: scope === "bozze", titolo: meta.titolo || "", preferita: !!meta.preferita };
    const [image, small] = await Promise.all([pack(png), pack(thumb)]);
    await tx(["blobs", "items"], "readwrite", (blobs, items) => {
      blobs.put(image, "outputs/" + file);
      blobs.put(small, "outputs/" + mini);
      items.put({ file, scope, t: Date.now(), meta: item });
    });
    return item;
  }

  async function move(file, fromScope, toScope) {
    const rec = await readItem(file);
    if (!rec || rec.scope !== fromScope) return null;
    const { day, stem } = splitFile(file);
    const newFile = `${SCOPE_PREFIX[toScope]}${day}/${stem}.png`;
    const newMini = thumbPath(toScope, day, stem);
    const png = await readRaw("outputs/" + file);
    const thumb = await readRaw("outputs/" + rec.meta.miniatura);
    const meta = { ...rec.meta, file: newFile, miniatura: newMini, bozza: toScope === "bozze" };
    await tx(["blobs", "items"], "readwrite", (blobs, items) => {
      blobs.delete("outputs/" + file);
      blobs.delete("outputs/" + rec.meta.miniatura);
      items.delete(file);
      if (png) blobs.put(png, "outputs/" + newFile);
      if (thumb) blobs.put(thumb, "outputs/" + newMini);
      items.put({ file: newFile, scope: toScope, t: rec.t, meta });
    });
    return meta;
  }

  async function remove(file, scope) {
    const rec = await readItem(file);
    if (!rec || (scope && rec.scope !== scope)) return false;
    await tx(["blobs", "items"], "readwrite", (blobs, items) => {
      blobs.delete("outputs/" + file);
      blobs.delete("outputs/" + rec.meta.miniatura);
      items.delete(file);
    });
    return true;
  }

  async function history(params) {
    const scope = params.get("vista") || "galleria";
    const limit = Math.min(200, Number(params.get("limit") || 60));
    const offset = Math.max(0, Number(params.get("offset") || 0));
    const real = scope === "preferite" ? "galleria" : scope;
    let list = (await itemsIn(real)).map((r) => r.meta);
    if (scope === "preferite") list = list.filter((m) => m.preferita);
    list.sort((a, b) => (a.file < b.file ? 1 : -1));
    return { immagini: list.slice(offset, offset + limit) };
  }

  async function cleanOld() {
    const limit = Date.now() - DRAFT_TTL_MS;
    for (const rec of await itemsIn("bozze")) if (rec.t < limit) await remove(rec.file, "bozze");
    const used = new Set();
    for (const scope of ["galleria", "cestino", "bozze"]) {
      for (const rec of await itemsIn(scope)) {
        (rec.meta.riferimenti || []).forEach((r) => used.add(r));
        if (rec.meta.maschera) used.add(rec.meta.maschera);
      }
    }
    const inputs = (await kvGet("inputs", {})) || {};
    let changed = false;
    for (const [path, t] of Object.entries(inputs)) {
      if (t < limit && !used.has(path)) {
        await tx("blobs", "readwrite", (s) => s.delete(path));
        delete inputs[path];
        changed = true;
      }
    }
    if (changed) await kvSet("inputs", inputs);
  }

  async function saveInput(blob, name) {
    const path = `inputs/${today()}/${clock()}_${rand()}.png`;
    const data = await pack(blob);
    await tx("blobs", "readwrite", (s) => { s.put(data, path); });
    const inputs = (await kvGet("inputs", {})) || {};
    inputs[path] = Date.now();
    await kvSet("inputs", inputs);
    return path;
  }

  /* ---------- stili dell'utente ---------- */

  const ITALIAN = /\b(il|lo|la|gli|le|un|una|uno|di|del|della|dei|delle|che|con|per|sul|sulla|nel|nella|non|più|mentre|sopra|sotto|dietro|davanti|vicino|foto|immagine|ragazza|ragazzo|uomo|donna|cielo|mare|togli|metti|aggiungi|cambia|rendi|sostituisci|fai)\b|[àèéìòù]/i;
  const ENGLISH = new Set(
    "the a an of with and on at is are by to from for under over into his her their its this that wearing holding standing sitting photo picture style".split(" ")
  );
  const looksItalian = (t) => {
    const text = t.replace(/"[^"]*"/g, "");
    if (ITALIAN.test(text)) return true;
    const words = (text.match(/[a-z]+/gi) || []).map((w) => w.toLowerCase());
    if (!words.length || words.some((w) => ENGLISH.has(w))) return false;
    return words.filter((w) => "aeio".includes(w.at(-1))).length / words.length > 0.6;
  };

  const userStyles = () => kvGet("stili", []);

  async function saveStyle(data) {
    const name = String(data.nome || "").trim().slice(0, 40);
    const text = String(data.testo || "").trim().slice(0, 600);
    if (!name || !text) throw new Error("Servono un nome e una descrizione dello stile.");
    let english = text;
    if (looksItalian(text)) english = (await write("traduci", text)) || text;
    const items = await userStyles();
    let id = String(data.id || "");
    if (!id.startsWith("u-") || !items.some((i) => i.id === id)) {
      const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24) || "stile";
      id = `u-${slug}-${rand().slice(0, 4)}`;
    }
    const color = /^#[0-9a-f]{6}$/i.test(data.colore || "") ? data.colore : "#cbbcff";
    const style = {
      id,
      nome: name,
      descrizione: text.length < 90 ? text : text.slice(0, 87) + "…",
      testo: text,
      formato: data.formato || "1:1",
      colore: color,
      modello: ["z-image", "klein", "entrambi"].includes(data.modello) ? data.modello : "",
      qualita: ["rapida", "bilanciata", "massima"].includes(data.qualita) ? data.qualita : "",
      prompt: "{prompt}. " + english.trim().replace(/\.$/, "") + ".",
    };
    const next = items.some((i) => i.id === id) ? items.map((i) => (i.id === id ? style : i)) : [...items, style];
    await kvSet("stili", next);
    return { ...style, categoria: "I tuoi stili", utente: true, campi: [] };
  }

  async function templates() {
    const res = await fetch("/api/templates");
    const data = await res.json();
    const mine = (await userStyles()).map((s) => ({ ...s, categoria: "I tuoi stili", utente: true, campi: [] }));
    return { template: [...data.template, ...mine] };
  }

  /* ---------- motore ---------- */

  let clientPromise = null;
  function engine() {
    const token = readAccount()?.token;
    const connect = (Client, withToken) =>
      Client.connect(location.origin + ENGINE_PATH, { events: ["data", "status"], ...(withToken ? { token } : {}) });
    clientPromise ||= import("/web/vendor/gradio-client.js")
      .then(({ Client }) => connect(Client, Boolean(token)).catch((e) => {
        if (!token) throw e;
        logout();
        return connect(Client, false);
      }))
      .catch((e) => {
        clientPromise = null;
        throw e;
      });
    return clientPromise;
  }

  /* ---------- accesso facoltativo con Hugging Face ---------- */

  const ACCOUNT = "pixrick.account";

  function readAccount() {
    try {
      const a = JSON.parse(localStorage.getItem(ACCOUNT) || "null");
      if (a?.token && a.scade > Date.now() + 60000) return a;
      if (a) localStorage.removeItem(ACCOUNT);
    } catch { /* storage non disponibile */ }
    return null;
  }

  function captureLogin() {
    const m = location.hash.match(/^#accesso=([\w-]+)$/);
    if (!m) return null;
    window.history.replaceState(window.history.state, "", location.pathname + location.search);
    if (m[1].length < 40) return m[1];
    try {
      const a = JSON.parse(atob(m[1].replace(/-/g, "+").replace(/_/g, "/")));
      if (!a.token) return "errore";
      localStorage.setItem(ACCOUNT, JSON.stringify(a));
      return "ok";
    } catch {
      return "errore";
    }
  }

  const loginResult = captureLogin();

  function account() {
    const a = readAccount();
    return a ? { utente: a.utente, nome: a.nome, foto: a.foto } : null;
  }

  function logout() {
    try { localStorage.removeItem(ACCOUNT); } catch { /* storage non disponibile */ }
    clientPromise = null;
  }

  let hiddenSince = 0;
  document.addEventListener("visibilitychange", () => {
    if (document.hidden) hiddenSince = Date.now();
    else if (hiddenSince && Date.now() - hiddenSince > 20000) clientPromise = null;
  });

  const DAY = 24 * 3600 * 1000;
  const FIRST_USE = "pixrick.gpu.inizio";

  function markGpuUse() {
    try {
      const first = Number(localStorage.getItem(FIRST_USE));
      if (!first || Date.now() - first > DAY) localStorage.setItem(FIRST_USE, String(Date.now()));
    } catch { /* storage non disponibile */ }
  }

  function quotaReset() {
    try {
      const first = Number(localStorage.getItem(FIRST_USE));
      return first && first + DAY > Date.now() ? first + DAY : null;
    } catch {
      return null;
    }
  }

  function report(text) {
    try {
      navigator.sendBeacon("/api/errore", new Blob([JSON.stringify({ m: String(text).slice(0, 400) })], { type: "application/json" }));
    } catch { /* solo diagnostica */ }
  }

  const QUOTA = /quota|runs limit|GPU (?:time|duration|limit)/i;
  function engineError(raw) {
    const text = String(raw?.message || (typeof raw === "object" ? JSON.stringify(raw) : raw) || "");
    report(text || "errore vuoto");
    if (QUOTA.test(text)) {
      const wait = text.match(/Try again in (?:(\d+) days?, )?(\d+):(\d+):(\d+)/i);
      const err = new Error("Per oggi hai finito le prove gratuite.");
      err.code = "quota";
      if (wait) err.retryIn = Number(wait[1] || 0) * 86400 + Number(wait[2]) * 3600 + Number(wait[3]) * 60 + Number(wait[4]);
      window.PixOnline?.quota(err.retryIn);
      return err;
    }
    if (/queue is full|too many/i.test(text)) {
      const err = new Error("Ci sono troppe persone in coda in questo momento. Riprova tra un minuto.");
      err.code = "full";
      return err;
    }
    return new Error(text.replace(/^Error:\s*/, "") || "Il motore non risponde. Riprova tra poco.");
  }

  async function write(kind, text) {
    const client = await engine();
    try {
      const res = await client.predict("/scrivi", [kind, text]);
      markGpuUse();
      return res.data[0];
    } catch (e) {
      throw engineError(e);
    }
  }

  async function improve(text, mode) {
    const client = await engine();
    try {
      const res = await client.predict("/migliora", [text, mode]);
      markGpuUse();
      return res.data[0];
    } catch (e) {
      throw engineError(e);
    }
  }

  const jobs = new Map();
  let lastPayload = null;
  const listeners = new Set();
  const emit = (event) => listeners.forEach((fn) => { try { fn(event); } catch { /* ascoltatore rotto */ } });

  function placeholderJob(id, payload) {
    return {
      id,
      status: "invio",
      progress: 0,
      current: 0,
      current_model: "",
      total: Math.max(1, Number(payload.quantita) || 1),
      current_steps: 1,
      model_name: "",
      confronto: false,
      elapsed: 0,
      width: 1024,
      height: 1024,
      results: [],
      request: { mode: payload.modalita || "crea", count: Number(payload.quantita) || 1, mask: payload.maschera || null },
      created: Date.now() / 1000,
    };
  }

  async function startJob(payload) {
    const files = [];
    for (const ref of payload.riferimenti || []) {
      const blob = await readBlob(ref);
      if (!blob) throw new Error("Un'immagine di partenza non c'è più. Ricaricala.");
      files.push(new File([blob], "ref.png", { type: blob.type || "image/png" }));
    }
    let mask = null;
    if (payload.maschera) {
      const blob = await readBlob(payload.maschera);
      if (blob) mask = new File([blob], "mask.png", { type: "image/png" });
    }
    lastPayload = payload;
    const request = { ...payload, stili_utente: await userStyles() };
    const client = await engine();
    const { handle_file: handle } = await import("/web/vendor/gradio-client.js");
    const id = "j" + Date.now().toString(36) + rand();
    const started = Date.now();
    const state = { job: placeholderJob(id, payload), payload };
    jobs.set(id, state);

    const inputs = [JSON.stringify(request), files.map((f) => handle(f)), mask ? handle(mask) : null];

    async function follow(run) {
      let received = false;
      for await (const msg of run) {
        if (msg.type === "status") {
          if (msg.stage === "error") {
            const err = engineError(msg.message);
            err.lost = !received && !msg.message;
            throw err;
          }
          if (msg.stage === "pending" && msg.position != null && state.job.status !== "generazione") {
            state.job = { ...state.job, status: "in_coda", position: msg.position, eta: msg.eta ?? null, queue_size: msg.queue_size ?? null };
          }
        }
        if (msg.type === "data") {
          received = true;
          const [pub, out] = msg.data;
          if (!pub) continue;
          const live = { ...pub, elapsed: Math.round((Date.now() - started) / 100) / 10 };
          if (pub.status === "fatto" && out && out.length) {
            state.job = { ...live, status: "salvataggio" };
            const results = [];
            try {
              for (let i = 0; i < out.length; i++) {
                const res = await fetch(out[i].url);
                if (!res.ok) throw new Error(`download ${res.status}`);
                const png = await res.blob();
                const meta = { ...pub.results[i], riferimenti: payload.riferimenti || [], maschera: payload.maschera || null };
                results.push(await storeItem("bozze", meta, png, await thumbnail(png)));
              }
            } catch (e) {
              report(`salvataggio: ${e?.name || ""} ${e?.message || e}`);
              const err = new Error("L'immagine è pronta ma il browser non è riuscito a salvarla. Riprova; se succede ancora, esci dalla navigazione privata.");
              err.lost = false;
              throw err;
            }
            markGpuUse();
            state.job = { ...live, status: "fatto", results, progress: 1 };
            emit({ type: "generata", count: results.length });
            return;
          }
          state.job = { ...live, status: pub.status === "fatto" ? "salvataggio" : pub.status };
        }
      }
      const err = new Error("Il motore non risponde. Riprova tra poco.");
      err.lost = !received;
      throw err;
    }

    (async () => {
      try {
        try {
          await follow(client.submit("/genera", inputs));
        } catch (e) {
          if (e?.code || e?.lost === false) throw e;
          clientPromise = null;
          const fresh = await engine();
          await follow(fresh.submit("/genera", inputs));
        }
      } catch (e) {
        const err = e instanceof Error && e.code ? e : engineError(e);
        state.job = { ...state.job, status: "errore", error: err.message, error_code: err.code || null, retry_in: err.retryIn || null };
        emit({ type: "errore", code: err.code || null, retryIn: err.retryIn || null });
      }
    })();
    return state.job;
  }

  /* ---------- router delle API ---------- */

  const MODELS = {
    "z-image": { nome: "Z-Image Turbo", descrizione: "Il più fedele al prompt. Foto realistiche e testo dentro l'immagine.", modalita: ["crea", "ristila"], qualita: { rapida: 6, bilanciata: 9, massima: 14 } },
    klein: { nome: "FLUX.2 Klein", descrizione: "Veloce, stile pulito. L'unico che modifica le foto a comando.", modalita: ["crea", "ristila", "modifica", "continua"], qualita: { rapida: 4, bilanciata: 5, massima: 8 } },
  };
  const ASPECTS = { "1:1": [1024, 1024], "4:5": [896, 1120], "3:4": [864, 1152], "2:3": [832, 1248], "9:16": [768, 1344], "16:9": [1344, 768], "3:2": [1248, 832] };

  function status() {
    const busy = [...jobs.values()].filter((s) => !["fatto", "errore"].includes(s.job.status)).length;
    return {
      modello: "pronto",
      modello_caricato: null,
      modelli_installati: { "z-image": true, klein: true },
      lavori_attivi: busy,
      traduttore: true,
      strumenti: { ingrandisci: true, scontorna: true, vettorizza: true },
      motore_finto: false,
      online: true,
      formati: ASPECTS,
      modelli: MODELS,
      automatico: { crea: "z-image", ristila: "klein", modifica: "klein", continua: "klein", rifinisci: "z-image" },
      max_riferimenti: 4,
    };
  }

  async function posterSave(blob, info) {
    const bmp = await bitmap(blob);
    const meta = {
      _stem: `${clock()}_locandina_${rand()}`,
      modalita: "locandina",
      prompt: String(info.titolo || "").slice(0, 120),
      prompt_finale: "",
      template: "libero",
      stili: [],
      campi: {},
      riferimenti: info.sfondo ? [String(info.sfondo)] : [],
      formato: String(info.formato || ""),
      larghezza: bmp.width,
      altezza: bmp.height,
      qualita: "",
      passi: 0,
      seed: 0,
      modello: "compositore",
      modello_nome: "Compositore",
      trasparente: false,
      creata: stamp(),
      titolo: String(info.titolo || "").slice(0, 120),
      preferita: false,
    };
    bmp.close?.();
    return storeItem("galleria", meta, blob, await thumbnail(blob));
  }

  async function vectorize(body) {
    const blob = await readBlob(body.file);
    if (!blob) throw new Error("Immagine non trovata.");
    const form = new FormData();
    form.append("file", blob, "immagine.png");
    form.append("stile", body.stile || "colori");
    form.append("trasparente", String(body.trasparente !== false));
    const res = await fetch("/api/vectorize", { method: "POST", body: form });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(data.detail || "Vettorizzazione non riuscita.");
    return data;
  }

  async function extractStyle(body) {
    const res = await fetch("/api/styles/extract", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...body, stili_utente: await userStyles() }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(data.detail || "Non riuscito.");
    return data;
  }

  const filesOf = (body) => (body.files || (body.file ? [body.file] : [])).map(String);

  async function api(path, body, headers = {}) {
    const url = new URL(path, location.origin);
    const p = url.pathname;
    if (body === undefined) {
      if (p === "/api/status") return status();
      if (p === "/api/templates") return templates();
      if (p === "/api/history") return history(url.searchParams);
      if (p.startsWith("/api/jobs/")) {
        const s = jobs.get(p.split("/").pop());
        if (!s) throw new Error("Lavoro non trovato.");
        return s.job;
      }
      throw new Error("Pagina non trovata.");
    }
    switch (p) {
      case "/api/upload": {
        const { blob, width, height } = await cleanUpload(body);
        const name = decodeURIComponent(headers["X-Filename"] || "").slice(0, 80);
        return { file: await saveInput(blob, name), larghezza: width, altezza: height, nome: name };
      }
      case "/api/poster": {
        const info = JSON.parse(decodeURIComponent(headers["X-Meta"] || "") || "{}");
        return posterSave(body, info);
      }
      case "/api/generate":
        return startJob(body);
      case "/api/enhance":
        if (!String(body.prompt || "").trim()) throw new Error("Scrivi prima un'idea da migliorare.");
        return improve(String(body.prompt), body.modalita || "crea");
      case "/api/translate":
        return { testo: String(body.testo || "").trim() ? await write(body.verso === "it" ? "in_italiano" : "traduci", String(body.testo)) : "" };
      case "/api/vectorize":
        return vectorize(body);
      case "/api/keep": {
        const kept = [];
        for (const f of filesOf(body)) { const m = await move(f, "bozze", "galleria"); if (m) kept.push(m); }
        return { salvate: kept };
      }
      case "/api/discard": {
        let n = 0;
        const list = body.tutto ? (await itemsIn("bozze")).map((r) => r.file) : filesOf(body);
        for (const f of list) if (await remove(f, "bozze")) n++;
        return { scartate: n };
      }
      case "/api/trash": {
        let n = 0;
        for (const f of filesOf(body)) if (await move(f, "galleria", "cestino")) n++;
        return { spostate: n };
      }
      case "/api/restore": {
        let n = 0;
        for (const f of filesOf(body)) if (await move(f, "cestino", "galleria")) n++;
        return { ripristinate: n };
      }
      case "/api/purge": {
        let n = 0;
        const list = body.tutto ? (await itemsIn("cestino")).map((r) => r.file) : filesOf(body);
        for (const f of list) if (await remove(f, "cestino")) n++;
        return { eliminate: n };
      }
      case "/api/update": {
        const rec = await readItem(String(body.file || ""));
        if (!rec || rec.scope !== "galleria") throw new Error("Immagine non trovata.");
        const changes = body.modifiche || {};
        if ("titolo" in changes) rec.meta.titolo = String(changes.titolo || "").trim().slice(0, 120);
        if ("preferita" in changes) rec.meta.preferita = !!changes.preferita;
        await tx("items", "readwrite", (s) => { s.put(rec); });
        return rec.meta;
      }
      case "/api/styles/save":
        return saveStyle(body);
      case "/api/styles/extract":
        return extractStyle(body);
      case "/api/styles/delete": {
        const items = await userStyles();
        const next = items.filter((i) => i.id !== String(body.id || ""));
        if (next.length === items.length) throw new Error("Stile non trovato.");
        await kvSet("stili", next);
        return { ok: true };
      }
      case "/api/unload":
      case "/api/shutdown":
        return { ok: true };
      default:
        throw new Error("Azione non trovata.");
    }
  }

  async function serviceWorker() {
    if (!("serviceWorker" in navigator)) return false;
    try {
      await navigator.serviceWorker.register("/sw.js", { scope: "/" });
      await navigator.serviceWorker.ready;
      if (!navigator.serviceWorker.controller) {
        await new Promise((resolve) => {
          navigator.serviceWorker.addEventListener("controllerchange", resolve, { once: true });
          setTimeout(resolve, 1500);
        });
      }
      return !!navigator.serviceWorker.controller;
    } catch {
      return false;
    }
  }

  const ready = (async () => {
    await db();
    const sw = await serviceWorker();
    cleanOld().catch(() => {});
    if (navigator.storage?.persist) navigator.storage.persist().catch(() => {});
    return { serviceWorker: sw };
  })();

  window.PixBackend = { api, ready, engine, quotaReset, account, logout, loginResult, on: (fn) => listeners.add(fn), readBlob, get lastPayload() { return lastPayload; } };
})();