// Certify Unified — multi-photo gallery and full-page "Nuova opera" form.
const { useState: gS } = React;
const CATS = (window.CU_CATS || ["Opere su tela", "Opere su carta", "Opere seriali", "Grafiche e multipli", "Opere fotografiche", "Gioielli e altri progetti"]);
const PH_LABELS = ["Fronte", "Retro", "Dettaglio", "Firma", "Etichetta", "Allestimento", "Foto d'epoca", "Foto aggiuntiva"];

// Downscale uploads so the demo state stays small in the browser.
async function shrink(file, max = 1100) {
  const bmp = await createImageBitmap(file); const k = Math.min(1, max / Math.max(bmp.width, bmp.height));
  const c = document.createElement("canvas"); c.width = Math.round(bmp.width * k); c.height = Math.round(bmp.height * k);
  c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height); return c.toDataURL("image/jpeg", 0.82);
}

function Gallery({ a, edit }) {
  const { mut, say } = useC();
  const imgs = [a.img ? { src: a.img, label: "Fronte" } : null, ...(a.gallery || [])].filter(Boolean);
  const [i, setI] = gS(0); const cur = imgs[Math.min(i, imgs.length - 1)];
  const off = a.img ? 1 : 0;
  const add = async (files) => {
    const out = []; for (const f of files) out.push({ src: await shrink(f), label: "Foto aggiuntiva" });
    mut((n) => { const w = byId(n.works, a.id); let g = [...(w.gallery || []), ...out]; if (!w.img && g.length) { w.img = g[0].src; g = g.slice(1); } w.gallery = g; log(n, { type: "modifica", artworkId: a.id, text: `${a.title}: ${out.length} ${out.length === 1 ? "foto aggiunta" : "foto aggiunte"}` }); });
    say(out.length === 1 ? "Foto aggiunta" : `${out.length} foto aggiunte`);
  };
  const setLabel = (k, v) => mut((n) => { byId(n.works, a.id).gallery[k - off].label = v; });
  const remove = (k) => { mut((n) => { const w = byId(n.works, a.id); w.gallery = w.gallery.filter((_, j) => j !== k - off); }); setI(0); };
  return <div className="gal">
    <div className="gal-m">{cur ? <img src={cur.src} alt="" /> : <Art a={a} r={0} />}</div>
    {(imgs.length > 1 || edit) && <div className="gal-t">
      {imgs.map((g, k) => <button key={k} className={k === i ? "on" : ""} onClick={() => setI(k)} title={g.label}><img src={g.src} alt="" /></button>)}
      {edit && <label className="gal-add" title="Aggiungi foto"><Ic.plus /><input type="file" accept="image/*" multiple hidden onChange={(e) => { add([...e.target.files]); e.target.value = ""; }} /></label>}
    </div>}
    {edit && cur && <div className="gal-c">
      {i >= off && imgs.length ? <><select value={cur.label} onChange={(e) => setLabel(i, e.target.value)}>{PH_LABELS.map((l) => <option key={l}>{l}</option>)}</select><button className="lnk" onClick={() => remove(i)}>Rimuovi</button></> : <span>{cur.label} · immagine principale</span>}
      <span className="mut">{imgs.length} foto</span></div>}
  </div>;
}

const NW_SLOTS = [["front", "Fronte", "Immagine principale"], ["back", "Retro", "Telaio, tela, supporto"], ["sign", "Firma e iscrizioni", "Dettaglio leggibile"], ["label", "Etichette e timbri", "Gallerie, mostre, dogana"], ["detail", "Dettaglio", "Superficie o tecnica"], ["other", "Altra vista", "Facoltativa"]];
const NW4Row = ({ l, req, hint, children }) => <div className="nw4-r"><div className="nw4-l"><b>{l}{req && <i className="req">*</i>}</b>{hint && <span className="nw4-hn">{hint}</span>}</div><div className="nw4-c">{children}</div></div>;
const NW4Sec = ({ n: nn, t, opt, children }) => <section className="nw4-s"><h2><i>{nn}</i>{t}{opt && <span>facoltativo</span>}</h2>{children}</section>;
const NW_VIEWS = ["Fronte", "Retro", "Firma e iscrizioni", "Etichette e timbri", "Dettaglio", "Altra vista"];
const NW_SUB = () => window.CU_SUBCATS || { "Opere su tela": ["Anni '50", "Anni '60", "Anni '70", "Anni '80"], "Opere su carta": ["Anni '50", "Anni '60", "Anni '70", "Anni '80"], "Altro": ["Scritti", "Fotografie", "Video e film", "Gioielli", "Progetti"] };
const NW_DOC = ["PDF", "Certificato", "Documento storico", "Fotografia documentaria", "Corrispondenza", "Altro file"];
const NW_EMPTY = { title: "", year: "", category: "", sub: "", series: "", medium: "", h: "", w: "", dp: "", edition: "", arch: "", inscr: "", provenance: "", history: "", sci: "", note: "", extra: "", imgs: [], refs: { cat: [], bib: [], ex: [], col: [], rel: [], mat: [] }, files: [] };
const NW_KEY = "cu-nw-draft-" + (window.CU_TENANT || "angeli");

function RefPicker({ kind, onClose, onAdd }) {
  const { s } = useC(); const [q, setQ] = gS(""); const [sel, setSel] = gS(null); const [ref, setRef] = gS(""); const [nw, setNw] = gS(null);
  const cols = [...new Set(s.works.map((a) => a.collection).filter(Boolean))].sort();
  const SRC = {
    cat: [(s.catalogues || []).map((c) => ({ id: c.id, t: c.title, m: [c.kind, c.editor, c.year].filter(Boolean).join(" · ") })), "Pagina e tavola", "Es. p. 42, tav. 12"],
    bib: [(s.publications || []).map((p) => ({ id: p.id, t: p.title, m: [p.author, p.where, p.year].filter(Boolean).join(" · ") })), "Pagina", "Es. p. 18"],
    ex: [s.exhibitions.map((x) => ({ id: x.id, t: x.title, m: [x.venue, x.city, (x.from || "").slice(0, 4)].filter(Boolean).join(" · ") })), "N. in catalogo della mostra", "Es. n. 24"],
    col: [cols.map((c) => ({ id: c, t: c, m: s.works.filter((a) => a.collection === c).length + " opere" })), "Note", "Facoltativo"],
    rel: [s.works.map((a) => ({ id: a.id, t: a.title, m: [a.yearLabel || a.year, a.catNo].filter(Boolean).join(" · "), a })), "Relazione", "Es. studio, stessa serie, variante"],
    mat: [[], "Descrizione", "Es. lettera dell'artista, 1965"],
  };
  const [list, refL, refP] = SRC[kind]; const L = list.filter((x) => (x.t + x.m).toLowerCase().includes(q.toLowerCase())).slice(0, 40);
  const T = { cat: "catalogo", bib: "pubblicazione", ex: "mostra", col: "collezione", rel: "opera correlata", mat: "materiale" }[kind];
  const pickNew = kind === "mat" || nw;
  return <Modal title={"Aggiungi " + T} onClose={onClose} foot={<><Btn onClick={onClose}>Annulla</Btn><Btn k="dark" disabled={pickNew ? !(nw && nw.t.trim()) : !sel} onClick={() => onAdd(pickNew ? { id: "new:" + Date.now(), t: nw.t.trim(), m: nw.m.trim(), ref, isNew: true } : { ...sel, ref })}>Collega</Btn></>}>
    {kind !== "mat" && !nw && <>
      <label className="wk-s" style={{ marginBottom: 10 }}><Ic.search /><input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder={"Cerca " + T + " nell'archivio…"} /></label>
      <div className="rp-l">{L.map((x) => <button key={x.id} type="button" className={sel && sel.id === x.id ? "on" : ""} onClick={() => setSel(x)}>{x.a && <span className="rp-th"><Art a={x.a} label={false} r={4} /></span>}<div><b>{x.t}</b><span>{x.m}</span></div>{sel && sel.id === x.id && <Ic.check />}</button>)}{!L.length && <div className="empty">Nessun risultato.</div>}</div>
      {kind !== "rel" && <button type="button" className="lnk" style={{ marginTop: 10 }} onClick={() => setNw({ t: q, m: "" })}>+ Non c'è: crea {kind === "ex" ? "una nuova" : "un nuovo"} {T}</button>}
    </>}
    {pickNew && <div className="g2f"><label className="fld"><span>Titolo<i className="req">*</i></span><input autoFocus value={(nw || {}).t || ""} onChange={(e) => setNw({ ...(nw || { m: "" }), t: e.target.value })} /></label><label className="fld"><span>{kind === "mat" ? "Tipologia" : "Anno e riferimento"}</span><input value={(nw || {}).m || ""} onChange={(e) => setNw({ ...(nw || { t: "" }), m: e.target.value })} placeholder={kind === "mat" ? "Documento, fotografia, corrispondenza" : "Es. Milano, 2010"} /></label></div>}
    {(sel || pickNew) && <label className="fld" style={{ marginTop: 10 }}><span>{refL}</span><input value={ref} onChange={(e) => setRef(e.target.value)} placeholder={refP} /></label>}
  </Modal>;
}

function NewWorkPage() {
  const { s, mut, go, say } = useC();
  const [d, setD] = gS(() => { try { const x = JSON.parse(localStorage.getItem(NW_KEY)); if (x && x.refs) return { ...NW_EMPTY, ...x }; } catch (e) {} return { ...NW_EMPTY }; });
  const [open, setOpen] = gS({ s1: true }); const [pk, setPk] = gS(null); const [cq, setCq] = gS(""); const [cOpen, setCOpen] = gS(false); const [drag, setDrag] = gS(null);
  React.useEffect(() => { localStorage.setItem(NW_KEY, JSON.stringify(d)); }, [d]);
  const up = (k, v) => setD((p) => ({ ...p, [k]: v }));
  const mats = [...new Set(s.works.map((a) => a.medium).filter(Boolean))].sort();
  const SUB = NW_SUB(); const CATL = [...new Set([...CATS, ...Object.keys(SUB)])];
  const ok = d.title.trim() && d.year.trim();
  const dims = [d.h, d.w, d.dp].filter(Boolean).join(" × ") + (d.h || d.w ? " cm" : "");
  const addImgs = async (files) => { const out = []; for (const f of files) if (f.type.startsWith("image/")) out.push({ src: await shrink(f), label: d.imgs.length + out.length === 0 ? "Fronte" : "Altra vista" }); setD((p) => ({ ...p, imgs: [...p.imgs, ...out] })); };
  const move = (from, to) => setD((p) => { const L = p.imgs.slice(); const [x] = L.splice(from, 1); L.splice(to, 0, x); return { ...p, imgs: L }; });
  const addFiles = (files) => setD((p) => ({ ...p, files: [...p.files, ...[...files].map((f) => ({ name: f.name.replace(/\.[^.]+$/, ""), file: f.name, type: /pdf$/i.test(f.name) ? "PDF" : /\.(jpe?g|png|tiff?)$/i.test(f.name) ? "Fotografia documentaria" : "Altro file", desc: "", vis: "archive" }))] }));
  const setRefs = (k, v) => setD((p) => ({ ...p, refs: { ...p.refs, [k]: v } }));
  const nRef = Object.values(d.refs).reduce((t, x) => t + x.length, 0);
  const SEC = [["s1", "01", "Identificazione", !!ok], ["s2", "02", "Immagini e dati tecnici", !!(d.imgs.length && d.medium.trim())], ["s3", "03", "Storia e provenienza", !!(d.provenance.trim() || d.history.trim())], ["s4", "04", "Materiali e riferimenti", nRef > 0], ["s5", "05", "Documenti e allegati", d.files.length > 0]];
  const goSec = (k) => { setOpen((o) => ({ ...o, [k]: true })); setTimeout(() => { const el = document.getElementById("nw-" + k); const m = el && el.closest(".main, .cu-main, main") ; if (el) { const top = el.getBoundingClientRect().top; const sc = document.scrollingElement; (m && m.scrollHeight > m.clientHeight ? m : sc).scrollBy({ top: top - 90, behavior: "smooth" }); } }, 30); };
  const Sec = ({ k, nn, t, done, sum, children }) => <section id={"nw-" + k} className={"nw5-s" + (open[k] ? " on" : "")}><button type="button" className="nw5-h" onClick={() => setOpen((o) => ({ ...o, [k]: !o[k] }))}><i className={done ? "ok" : ""}>{done ? "✓" : nn}</i><b>{t}</b><span>{!open[k] && sum}</span><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d={open[k] ? "M6 15l6-6 6 6" : "M6 9l6 6 6-6"} /></svg></button>{open[k] && <div className="nw5-b">{children}</div>}</section>;
  const In = (k, ph0, x) => <input className={x || ""} value={d[k]} placeholder={ph0} onChange={(e) => up(k, e.target.value)} />;
  const RG = [["cat", "Cataloghi"], ["bib", "Bibliografia e pubblicazioni"], ["ex", "Mostre"], ["col", "Collezioni"], ["rel", "Opere correlate"], ["mat", "Altri materiali documentari"]];
  const save = (pub) => {
    const n0 = Math.max(0, ...s.works.map((a) => a.added || 0)) + 1; const y = parseInt((d.year.match(/\d{4}/) || [])[0]) || (d.year.match(/'(\d)0/) ? 1900 + 10 * +d.year.match(/'(\d)0/)[1] : 1960);
    const R = d.refs; const col0 = R.col[0] ? R.col[0].t : "";
    const a = { ...window.CU_MAKE(5000 + n0), added: n0, title: d.title.trim(), year: y, yearLabel: d.year.trim(), category: d.category || CATS[0], subcategory: d.sub, series: d.series.trim(), medium: d.medium.trim(), dims, edition: d.edition.trim(), img: d.imgs[0] && d.imgs[0].src, gallery: d.imgs.slice(1), inscr: d.inscr, arch: d.arch, catNo: d.arch || "", collection: col0, collections: R.col.map((x) => x.t), loc: "", notes: d.sci, notePub: d.note, history: d.history, extra: d.extra,
      provenance: d.provenance.split("\n").map((x) => x.trim()).filter(Boolean).map((who) => ({ who, when: "", show: "named" })),
      exhibitions: R.ex.filter((x) => !x.isNew).map((x) => x.id), related: R.rel.map((x) => ({ id: x.id, rel: x.ref })),
      docs: [...R.mat.map((x) => ["doc", x.t, "archive", [x.m, x.ref].filter(Boolean).join(" · ")]), ...d.files.map((f) => [f.type === "Fotografia documentaria" ? "image" : "doc", f.name, f.vis, [f.type, f.desc].filter(Boolean).join(" · ")])],
      pub: pub ? "published" : "draft", edited: "adesso", updatedAt: new Date().toLocaleDateString("it-IT") };
    mut((nn) => {
      R.ex.filter((x) => x.isNew).forEach((x) => { const id = "x" + Date.now() + Math.random().toString(36).slice(2, 5); nn.exhibitions.push({ id, title: x.t, venue: "", city: x.m, from: "", to: "" }); a.exhibitions.push(id); });
      R.cat.forEach((x) => { let c = x.isNew ? null : byId(nn.catalogues || [], x.id); if (!c) { c = { id: "k" + Date.now() + Math.random().toString(36).slice(2, 5), title: x.t, kind: "Catalogo", editor: "", place: x.m, year: "", works: [] }; (nn.catalogues = nn.catalogues || []).push(c); } c.works.push({ id: a.id, page: x.ref, plate: "" }); });
      R.bib.forEach((x) => { let p = x.isNew ? null : byId(nn.publications || [], x.id); if (!p) { p = { id: "p" + Date.now() + Math.random().toString(36).slice(2, 5), title: x.t, author: "", where: x.m, year: "", kind: "Pubblicazione", works: [] }; (nn.publications = nn.publications || []).push(p); } p.works.push({ id: a.id, page: x.ref }); });
      nn.works.unshift(a); log(nn, { type: "catalogo", artworkId: a.id, text: `Nuova scheda: ${a.title}${nRef ? ` · ${nRef} riferimenti collegati` : ""}${pub ? " · pubblicata nel catalogo" : ""}` }); });
    localStorage.removeItem(NW_KEY); say(pub ? "Opera salvata e pubblicata" : "Bozza salvata"); go({ v: "archive", p: "work", id: a.id });
  };
  return <div className="page nw nw4 nw5">
    <button className="lnk back" onClick={() => go({ v: "archive", p: "works" })}><Ic.back /> Opere</button>
    <div className="nw4-h"><div><div className="ph-k">Nuova scheda di catalogo</div><h1>{d.title.trim() || "Senza titolo"}</h1>
      <p className="mut">{[d.year, d.medium, dims].filter(Boolean).join(" · ") || "Titolo e data sono obbligatori. Il resto puoi completarlo dopo."}</p></div></div>
    <nav className="nw5-nav">{SEC.map(([k, nn, t, v]) => <button key={k} type="button" className={v ? "ok" : ""} onClick={() => goSec(k)}><i>{v ? "✓" : nn}</i>{t}</button>)}{JSON.stringify(d) !== JSON.stringify(NW_EMPTY) && <span className="nw5-dr">Bozza salvata automaticamente · <button type="button" className="lnk" onClick={() => setD({ ...NW_EMPTY })}>Svuota</button></span>}</nav>

    <Sec k="s1" nn="01" t="Identificazione" done={!!ok} sum={[d.title, d.year, d.arch].filter(Boolean).join(" · ")}>
      <NW4Row l="Titolo" req>{In("title", "Es. Half Dollar", "big")}</NW4Row>
      <div className="nw4-3"><NW4Row l="Datazione" req>{In("year", "1964 · anni '60 · s.d.")}</NW4Row><NW4Row l="N. archivio">{In("arch", "Es. P-260916/781")}</NW4Row><NW4Row l="Serie">{In("series", "Facoltativa")}</NW4Row></div>
      <NW4Row l="Categoria"><div className="nw5-cat">
        <button type="button" className="nw5-cs" onClick={() => setCOpen(!cOpen)}>{d.category ? <b>{d.category}{d.sub ? <em> · {d.sub}</em> : ""}</b> : <span className="mut">Scegli la categoria</span>}<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6" /></svg></button>
        {cOpen && <div className="nw5-cp"><input autoFocus value={cq} onChange={(e) => setCq(e.target.value)} placeholder="Cerca categoria…" />
          {CATL.filter((c) => (c + (SUB[c] || []).join(" ")).toLowerCase().includes(cq.toLowerCase())).map((c) => <div key={c}><button type="button" className={d.category === c ? "on" : ""} onClick={() => { setD((p) => ({ ...p, category: c, sub: "" })); if (!(SUB[c] || []).length) setCOpen(false); }}>{c}{(SUB[c] || []).length > 0 && <em>{SUB[c].length}</em>}</button>
            {d.category === c && (SUB[c] || []).length > 0 && <div className="nw5-sub">{SUB[c].map((x) => <button key={x} type="button" className={d.sub === x ? "on" : ""} onClick={() => { up("sub", x); setCOpen(false); setCq(""); }}>{x}</button>)}</div>}</div>)}</div>}
      </div></NW4Row>
    </Sec>

    <Sec k="s2" nn="02" t="Immagini e dati tecnici" done={!!(d.imgs.length && d.medium.trim())} sum={[d.imgs.length ? d.imgs.length + " immagini" : "", d.medium, dims].filter(Boolean).join(" · ")}>
      <div className="nw5-img">
        <label className="nw5-main" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); if (drag == null) addImgs([...e.dataTransfer.files]); }}>
          {d.imgs[0] ? <img src={d.imgs[0].src} alt="" /> : <span><Ic.plus />Trascina l'immagine principale<br /><em>o scegli un file · JPG, PNG</em></span>}
          <input type="file" accept="image/*" multiple hidden onChange={(e) => { addImgs([...e.target.files]); e.target.value = ""; }} /></label>
        {d.imgs.length > 0 && <div className="nw5-th">{d.imgs.map((g, k) => <div key={k} className={"nw5-t" + (drag === k ? " dr" : "")} draggable onDragStart={() => setDrag(k)} onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); e.stopPropagation(); if (drag != null && drag !== k) move(drag, k); setDrag(null); }} onDragEnd={() => setDrag(null)}>
          <img src={g.src} alt="" /><select value={g.label} onChange={(e) => setD((p) => ({ ...p, imgs: p.imgs.map((x, j) => j === k ? { ...x, label: e.target.value } : x) }))}>{NW_VIEWS.map((v) => <option key={v}>{v}</option>)}</select>
          <button type="button" aria-label="Rimuovi" onClick={() => setD((p) => ({ ...p, imgs: p.imgs.filter((_, j) => j !== k) }))}><Ic.x /></button>{k === 0 && <span className="nw5-pr">Principale</span>}</div>)}
          <label className="nw5-add" title="Aggiungi immagine"><Ic.plus /><input type="file" accept="image/*" multiple hidden onChange={(e) => { addImgs([...e.target.files]); e.target.value = ""; }} /></label></div>}
      </div>
      <div className="nw4-2"><NW4Row l="Tecnica e supporto"><input list="nw-mats" value={d.medium} placeholder="Es. smalto e velatino su tela" onChange={(e) => up("medium", e.target.value)} /><datalist id="nw-mats">{mats.map((m) => <option key={m} value={m} />)}</datalist></NW4Row>
        <NW4Row l="Dimensioni" hint="A × L × P"><div className="nw-dims">{[["h", "Alt."], ["w", "Largh."], ["dp", "Prof."]].map(([k, l], jj) => <React.Fragment key={k}>{jj > 0 && <em>×</em>}<input inputMode="decimal" placeholder={l} value={d[k]} onChange={(e) => up(k, e.target.value)} /></React.Fragment>)}<em>cm</em></div></NW4Row></div>
      <div className="nw4-2"><NW4Row l="Edizione">{In("edition", "Opera unica · 3/25")}</NW4Row><NW4Row l="Iscrizioni e firme"><textarea rows={1} value={d.inscr} placeholder="Firma e data al retro" onChange={(e) => up("inscr", e.target.value)} /></NW4Row></div>
    </Sec>

    <Sec k="s3" nn="03" t="Storia e provenienza" done={!!(d.provenance.trim() || d.history.trim())} sum={d.provenance.split("\n").filter(Boolean).length ? d.provenance.split("\n").filter(Boolean).length + " passaggi" : ""}>
      <div className="nw4-2"><NW4Row l="Provenienza" hint="Un passaggio per riga"><textarea rows={3} value={d.provenance} placeholder={"Galleria La Tartaruga, Roma\nCollezione privata, Milano"} onChange={(e) => up("provenance", e.target.value)} /></NW4Row>
        <NW4Row l="Storia dell'opera"><textarea rows={3} value={d.history} placeholder="Eventi, esposizioni, passaggi rilevanti" onChange={(e) => up("history", e.target.value)} /></NW4Row></div>
      <div className="nw4-2"><NW4Row l="Note scientifiche" hint="Solo archivio"><textarea rows={2} value={d.sci} onChange={(e) => up("sci", e.target.value)} /></NW4Row>
        <NW4Row l="Note per il catalogo" hint="Pubblicabili"><textarea rows={2} value={d.note} onChange={(e) => up("note", e.target.value)} /></NW4Row></div>
      <NW4Row l="Informazioni aggiuntive"><textarea rows={1} value={d.extra} onChange={(e) => up("extra", e.target.value)} /></NW4Row>
    </Sec>

    <Sec k="s4" nn="04" t="Materiali e riferimenti" done={nRef > 0} sum={nRef ? nRef + " collegati" : ""}>
      <p className="mut sm" style={{ margin: "0 0 6px" }}>Collega elementi già presenti nell'archivio, o creali. Si aggiornano ovunque: mostre, collezioni e pubblicazioni restano sincronizzate.</p>
      {RG.map(([k, l]) => <div key={k} className="mr-g"><div className="mr-h"><b>{l}</b>{d.refs[k].length > 0 && <span>{d.refs[k].length}</span>}<button type="button" className="lnk" onClick={() => setPk(k)}>+ Aggiungi</button></div>
        {d.refs[k].map((x, ii) => <div key={ii} className="mr-r">{x.a && <span className="mr-th"><Art a={x.a} label={false} r={3} /></span>}<div><b>{x.t}{x.isNew && <em> · nuovo</em>}</b><span>{[x.m, x.ref].filter(Boolean).join(" · ")}</span></div><button type="button" className="ib" aria-label="Scollega" onClick={() => setRefs(k, d.refs[k].filter((_, jj) => jj !== ii))}><Ic.x /></button></div>)}</div>)}
    </Sec>

    <Sec k="s5" nn="05" t="Documenti e allegati" done={d.files.length > 0} sum={d.files.length ? d.files.length + " file" : ""}>
      <label className="nw5-drop" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); addFiles(e.dataTransfer.files); }}><Ic.up /><span>Trascina PDF, certificati, documenti storici o fotografie<em> · oppure scegli i file</em></span><input type="file" multiple hidden onChange={(e) => { addFiles(e.target.files); e.target.value = ""; }} /></label>
      {d.files.map((f, k) => { const set = (kk, v) => setD((p) => ({ ...p, files: p.files.map((x, jj) => jj === k ? { ...x, [kk]: v } : x) })); return <div key={k} className="nw5-f"><input value={f.name} onChange={(e) => set("name", e.target.value)} aria-label="Nome" /><select value={f.type} onChange={(e) => set("type", e.target.value)}>{NW_DOC.map((x) => <option key={x}>{x}</option>)}</select><input value={f.desc} placeholder="Breve descrizione" onChange={(e) => set("desc", e.target.value)} /><select value={f.vis} onChange={(e) => set("vis", e.target.value)}><option value="archive">Solo archivio</option><option value="collector">Collezionista</option><option value="public">Pubblico</option></select><button type="button" className="ib" aria-label="Rimuovi" onClick={() => setD((p) => ({ ...p, files: p.files.filter((_, jj) => jj !== k) }))}><Ic.x /></button></div>; })}
      {d.files.length > 0 && <p className="mut sm" style={{ margin: "8px 0 0" }}>I file caricati qui appartengono all'opera. Per collegare elementi già presenti nell'archivio usa «Materiali e riferimenti».</p>}
    </Sec>

    {pk && <RefPicker kind={pk} onClose={() => setPk(null)} onAdd={(x) => { if (!d.refs[pk].some((y) => y.id === x.id)) setRefs(pk, [...d.refs[pk], x]); setPk(null); }} />}
    <div className="nw-bar"><span className="mut sm">{ok ? "Pronta per essere salvata" : "Titolo e datazione sono obbligatori"}</span>
      <Btn onClick={() => go({ v: "archive", p: "works" })}>Chiudi</Btn><Btn disabled={!ok} onClick={() => save(false)}>Salva bozza</Btn><Btn k="dark" disabled={!ok} onClick={() => save(true)}>Salva e pubblica</Btn></div>
  </div>;
}

Object.assign(window, { Gallery, NewWorkPage, shrink, CATS });
