// 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", "Studi", "Cataloghi correlati", "Altra foto"];

// 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-gs">{[["L'opera", (l) => !["Studi", "Cataloghi correlati", "Altra foto", "Foto aggiuntiva"].includes(l)], ["Studi", (l) => l === "Studi"], ["Cataloghi correlati", (l) => l === "Cataloghi correlati"], ["Altro", (l) => l === "Altra foto" || l === "Foto aggiuntiva"]].map(([gt, f]) => { const L = imgs.map((g, k) => [g, k]).filter(([g]) => f(g.label)); return L.length ? <div key={gt} className="gal-g"><div className="gal-gh">{gt}<em>{L.length}</em></div><div className="gal-t">{L.map(([g, k]) => <button key={k} className={k === i ? "on" : ""} onClick={() => setI(k)} title={g.label}><img src={g.src} alt="" /></button>)}</div></div> : null; })}
      {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", "Studi", "Cataloghi correlati", "Altra foto"];
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 = { dateType: "", collection: "", exIds: [], exOther: "", 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(() => ({ ed: !!(d.series || d.edition), ins: !!d.inscr, hist: !!(d.provenance || d.history), note: !!(d.sci || d.note || d.extra), refs: Object.values(d.refs || {}).some((x) => x.length), docs: (d.files || []).length > 0 })); 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.dateType === "sd" || (d.dateType === "decade" ? /'\d0/.test(d.year || "") : d.dateType === "range" ? /^\d{4}–\d{4}$/.test(d.year || "") : /^\d{4}$/.test(d.year || "")));
  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.dateType === "circa" ? "circa " : "") + 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: d.collection || col0, collections: [d.collection, ...R.col.map((x) => x.t)].filter(Boolean), medium_en: d.medium_en || "", inscr_en: d.inscr_en || "", notePub_en: d.note_en || "", provenance_en: d.provenance_en || "", 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: [...new Set([...(d.exIds || []), ...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) => {
      (d.exOther || "").split("\n").map((x) => x.trim()).filter(Boolean).forEach((tt) => { const id = "x" + Date.now() + Math.random().toString(36).slice(2, 5); nn.exhibitions.push({ id, title: tt, venue: "", city: "", from: "", to: "" }); a.exhibitions.push(id); });
      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 });
  };
  const [lg, setLg] = gS({}); const [exq, setExq] = gS(""); const [more, setMore] = gS(Object.values(d.refs || {}).some((x) => x.length) || (d.files || []).length > 0);
  const SLOTS = [["Fronte", "Immagine principale"], ["Retro", "Telaio, tela, supporto"], ["Firma e iscrizioni", "Dettaglio leggibile"], ["Etichette e timbri", "Gallerie, mostre, dogana"], ["Dettaglio", "Superficie o tecnica"], ["Altra vista", "Facoltativa"]];
  const GRP = [["Studi", "Studi", "Bozzetti, disegni e studi preparatori"], ["Cataloghi correlati", "Cataloghi correlati", "Copertine o pagine di cataloghi in cui compare l'opera"], ["Altra foto", "Altro", "Fotografie storiche, allestimenti, altro"]];
  const [nex, setNex] = gS(null);
  const slotImg = (l) => d.imgs.find((x) => x.label === l);
  const putSlot = async (l, files) => { const f = [...files].find((x) => x.type.startsWith("image/")); if (!f) return; const src = await shrink(f); setD((p) => { const L = p.imgs.filter((x) => x.label !== l); const it = { src, label: l }; return { ...p, imgs: l === "Fronte" ? [it, ...L] : [...L, it] }; }); };
  const addExtra = async (files, lab) => { const out = []; for (const f of files) if (f.type.startsWith("image/")) out.push({ src: await shrink(f), label: lab || "Altra foto" }); setD((p) => ({ ...p, imgs: [...p.imgs, ...out] })); };
  const rmImg = (it) => setD((p) => ({ ...p, imgs: p.imgs.filter((x) => x !== it) }));
  const extras = d.imgs.filter((x) => !SLOTS.some(([l]) => l === x.label) && !["Studi", "Cataloghi correlati"].includes(x.label));
  const ofLab = (lab) => lab === "Altra foto" ? extras : d.imgs.filter((x) => x.label === lab);
  const kk = (k) => (lg[k] === "EN" ? k + "_en" : k);
  const TI = (k, ph, rows) => rows ? <textarea rows={rows} value={d[kk(k)] || ""} placeholder={lg[k] === "EN" ? "English" : ph} onChange={(e) => up(kk(k), e.target.value)} /> : <input value={d[kk(k)] || ""} placeholder={lg[k] === "EN" ? "English" : ph} onChange={(e) => up(kk(k), e.target.value)} />;
  const cols = [...new Set(s.works.map((a) => a.collection).filter(Boolean))].sort();
  const EX = (s.exhibitions || []).map((x) => ({ id: x.id, t: x.title, y: (String(x.from || x.year || "").match(/\d{4}/) || [""])[0] })).sort((a, b) => (b.y || "").localeCompare(a.y || ""));
  const exSel = d.exIds || []; const exL = exq.trim() ? EX.filter((x) => !exSel.includes(x.id) && (x.t + " " + x.y).toLowerCase().includes(exq.toLowerCase())).slice(0, 6) : [];
  const SECS = [["id", "Identificazione", !!ok], ["tec", "Dati tecnici", !!d.medium.trim()], ["col", "Collocazione", !!d.collection], ["st", "Storia", !!(d.provenance.trim() || exSel.length || d.note.trim())]];
  const go7 = (k) => { const el = document.getElementById("nw7-" + k); if (!el) return; const m = el.closest(".main, .cu-main, main"); const top = el.getBoundingClientRect().top; (m && m.scrollHeight > m.clientHeight ? m : document.scrollingElement).scrollBy({ top: top - 90, behavior: "smooth" }); };
  const dirty = JSON.stringify(d) !== JSON.stringify(NW_EMPTY);
  return <div className="page nw nw4 nw5 nw7">
    <button className="lnk back" onClick={() => go({ v: "archive", p: "works" })}><Ic.back /> Opere</button>
    <div className="nw7-h"><div><div className="ph-k">Nuova scheda di catalogo</div><h1>{d.title.trim() || "Senza titolo"}</h1><p className="mut">Titolo e data sono obbligatori. Il resto puoi completarlo dopo.</p></div>
      <nav className="nw7-nav">{SECS.map(([k, l, v]) => <button key={k} type="button" className={v ? "ok" : ""} onClick={() => go7(k)}><i>{v ? "✓" : ""}</i>{l}</button>)}</nav></div>

    <div className="nw7-grid">
      <aside className="nw7-ph">
        <div className="nw7-ph-h"><b>Foto</b><span>{d.imgs.length} di 20</span></div>
        {(() => { const [l, h] = SLOTS[0]; const g = slotImg(l); return <label className="nw7-main" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); putSlot(l, e.dataTransfer.files); }}>
          {g ? <><img src={g.src} alt="" /><button type="button" className="nw7-x" aria-label="Rimuovi" onClick={(e) => { e.preventDefault(); rmImg(g); }}><Ic.x /></button></> : <span><Ic.plus /><b>Fronte</b><em>Immagine principale · trascina o scegli</em></span>}
          <input type="file" accept="image/*" hidden onChange={(e) => { putSlot(l, e.target.files); e.target.value = ""; }} /></label>; })()}
        <div className="nw7-gl">L'opera</div>
        <div className="nw7-slots">{SLOTS.slice(1).map(([l, h]) => { const g = slotImg(l); return <div key={l} className="nw7-sl"><label onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); putSlot(l, e.dataTransfer.files); }}>{g ? <><img src={g.src} alt="" /><button type="button" className="nw7-x" aria-label="Rimuovi" onClick={(e) => { e.preventDefault(); rmImg(g); }}><Ic.x /></button></> : <Ic.plus />}<input type="file" accept="image/*" hidden onChange={(e) => { putSlot(l, e.target.files); e.target.value = ""; }} /></label><b>{l}</b><span>{h}</span></div>; })}</div>
        {GRP.map(([lab, title, hint]) => { const L = ofLab(lab); return <div key={lab} className="nw7-pg"><div className="nw7-gl">{title}<em>{L.length ? L.length : ""}</em></div><p>{hint}</p>
          <div className="nw7-gr">{L.map((g, k) => <div key={k}><img src={g.src} alt="" /><button type="button" className="nw7-x" aria-label="Rimuovi" onClick={() => rmImg(g)}><Ic.x /></button></div>)}
            <label className="nw7-add" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); addExtra([...e.dataTransfer.files], lab); }}><Ic.plus /><input type="file" accept="image/*" multiple hidden onChange={(e) => { addExtra([...e.target.files], lab); e.target.value = ""; }} /></label></div></div>; })}
        <p className="mut sm">JPG o PNG, fino a 20 foto. Il fronte è l'immagine del catalogo; studi e cataloghi correlati compaiono nella scheda pubblica.</p>
      </aside>

      <div className="nw7-form">
        <section id="nw7-id" className="nw7-s"><h2><span>01</span>Identificazione</h2>
          <NW7F lg={lg} setLg={setLg} l="Titolo" req wide>{In("title", "Es. Half Dollar", "big")}</NW7F>
          <div className="nw7-2"><NW7F lg={lg} setLg={setLg} l="Data" req>{(() => { const p = d.dateType || "year"; const y4 = (v) => v.replace(/\D/g, "").slice(0, 4);
              const setP = (np) => setD((q) => { const y = ((q.year || "").match(/\d{4}/) || [""])[0]; const lab = np === "sd" ? "s.d." : np === "decade" ? (y ? "anni '" + y.slice(2, 3) + "0" : "") : np === "range" ? (y ? y + "–" : "") : y; return { ...q, dateType: np === "year" ? "" : np, year: lab, year2: "" }; });
              const [ya = "", yb = ""] = (d.year || "").split("–").map((x) => x.replace(/\D/g, ""));
              return <div className="nw7-date2"><div className="exf-seg sm">{[["year", "Anno"], ["circa", "Circa"], ["decade", "Decennio"], ["range", "Intervallo"], ["sd", "s.d."]].map(([k, l]) => <button key={k} type="button" className={p === k ? "on" : ""} onClick={() => setP(k)}>{l}</button>)}</div>
                {(p === "year" || p === "circa") && <input inputMode="numeric" maxLength={4} placeholder="Es. 1964" value={ya} onChange={(e) => up("year", y4(e.target.value))} />}
                {p === "decade" && <select value={(d.year.match(/'(\d)0/) || [])[1] || ""} onChange={(e) => up("year", e.target.value ? "anni '" + e.target.value + "0" : "")}><option value="">Scegli il decennio</option>{[4, 5, 6, 7, 8, 9, 0, 1, 2].map((k) => <option key={k} value={k}>Anni {k}0</option>)}</select>}
                {p === "range" && <div className="nw7-rg"><input inputMode="numeric" maxLength={4} placeholder="Dal" value={ya} onChange={(e) => up("year", y4(e.target.value) + "–" + yb)} /><em>–</em><input inputMode="numeric" maxLength={4} placeholder="Al" value={yb} onChange={(e) => up("year", ya + "–" + y4(e.target.value))} /></div>}
                {p === "sd" && <div className="nw7-sd">Senza data · l'opera comparirà come «s.d.»</div>}
              </div>; })()}</NW7F>
            <NW7F lg={lg} setLg={setLg} l="N. archivio" hint="assegnato dall'archivio">{In("arch", "Es. P-260916/781")}</NW7F></div>
          <div className="nw7-2"><NW7F lg={lg} setLg={setLg} l="Sezione del catalogo"><select value={d.category} onChange={(e) => setD((p) => ({ ...p, category: e.target.value, sub: "" }))}><option value="">Scegli la sezione</option>{CATL.map((c) => <option key={c}>{c}</option>)}</select></NW7F>
            <NW7F lg={lg} setLg={setLg} l="Sottosezione" hint={(SUB[d.category] || []).length ? "" : "nessuna"}><select value={d.sub} disabled={!(SUB[d.category] || []).length} onChange={(e) => up("sub", e.target.value)}><option value="">—</option>{(SUB[d.category] || []).map((x) => <option key={x}>{x}</option>)}</select></NW7F></div>
          <NW7F lg={lg} setLg={setLg} l="Serie" hint="facoltativa" wide>{In("series", "Es. Half Dollar")}</NW7F>
        </section>

        <section id="nw7-tec" className="nw7-s"><h2><span>02</span>Dati tecnici</h2>
          <div className="nw7-2"><NW7F lg={lg} setLg={setLg} l="Tecnica" hint="tecnica e supporto" lang="medium"><input list="nw-mats" value={d[kk("medium")] || ""} placeholder={lg.medium === "EN" ? "English" : "Es. smalto e velatino su tela"} onChange={(e) => up(kk("medium"), e.target.value)} /><datalist id="nw-mats">{mats.map((m) => <option key={m} value={m} />)}</datalist></NW7F>
            <NW7F lg={lg} setLg={setLg} l="Dimensioni" hint="cm · 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>)}</div></NW7F></div>
          <div className="nw7-2"><NW7F lg={lg} setLg={setLg} l="Iscrizioni" hint="tipo, posizione, testo" lang="inscr">{TI("inscr", "Firma e data al retro: «Angeli 64»", 2)}</NW7F><NW7F lg={lg} setLg={setLg} l="Edizione" hint="facoltativa">{In("edition", "Opera unica · 3/25")}</NW7F></div>
        </section>

        <section id="nw7-col" className="nw7-s"><h2><span>03</span>Collocazione</h2>
          <NW7F lg={lg} setLg={setLg} l="Collezione" wide><select value={d.collection || ""} onChange={(e) => up("collection", e.target.value)}><option value="">Non indicata</option>{cols.map((c) => <option key={c}>{c}</option>)}</select></NW7F>
        </section>

        <section id="nw7-st" className="nw7-s"><h2><span>04</span>Storia dell'opera<em>facoltativo</em></h2>
          <NW7F lg={lg} setLg={setLg} l="Provenienza" hint="un passaggio per riga, dal più antico" lang="provenance" wide>{TI("provenance", "Galleria La Tartaruga, Roma\nCollezione privata, Milano", 3)}</NW7F>
          <NW7F lg={lg} setLg={setLg} l="Esposizioni" hint="mostre dell'archivio" wide>
            {exSel.length > 0 && <div className="nw7-chips">{exSel.map((id) => { const x = EX.find((e) => e.id === id); return x ? <span key={id}>{x.t}{x.y ? " · " + x.y : ""}<button type="button" aria-label="Rimuovi" onClick={() => up("exIds", exSel.filter((y) => y !== id))}><Ic.x /></button></span> : null; })}</div>}
            <select value="" onChange={(e) => { const v = e.target.value; if (v === "__new") setNex({ title: "", venue: "", city: "", year: "" }); else if (v) up("exIds", [...exSel, v]); }}><option value="">{exSel.length ? "Aggiungi un'altra mostra…" : "Seleziona una mostra…"}</option>{EX.filter((x) => !exSel.includes(x.id)).map((x) => <option key={x.id} value={x.id}>{x.t}{x.y ? " · " + x.y : ""}</option>)}<option value="__new">+ Crea nuova mostra</option></select>
            {nex && <div className="nw7-nex"><div className="nw7-nex-h"><b>Nuova mostra</b><span>Verrà aggiunta anche alla sezione Mostre</span></div>
              <input autoFocus placeholder="Titolo della mostra *" value={nex.title} onChange={(e) => setNex({ ...nex, title: e.target.value })} />
              <div className="nw7-3"><input placeholder="Sede / istituzione" value={nex.venue} onChange={(e) => setNex({ ...nex, venue: e.target.value })} /><input placeholder="Città" value={nex.city} onChange={(e) => setNex({ ...nex, city: e.target.value })} /><input placeholder="Anno" inputMode="numeric" value={nex.year} onChange={(e) => setNex({ ...nex, year: e.target.value.replace(/[^0-9]/g, "").slice(0, 4) })} /></div>
              <div className="row" style={{ justifyContent: "flex-end" }}><Btn k="sm" onClick={() => setNex(null)}>Annulla</Btn><Btn k="sm dark" disabled={!nex.title.trim()} onClick={() => { const id = "x" + Date.now().toString(36); mut((n) => { n.exhibitions.push({ id, title: nex.title.trim(), venue: nex.venue.trim(), city: nex.city.trim(), from: nex.year ? nex.year + "-01-01" : "", to: nex.year ? nex.year + "-12-31" : "" }); log(n, { type: "catalogo", text: "Nuova mostra: " + nex.title.trim() }); }); up("exIds", [...exSel, id]); setNex(null); say("Mostra creata · ora è anche in Mostre"); }}>Crea e collega</Btn></div></div>}
          </NW7F>
          <NW7F lg={lg} setLg={setLg} l="Note" hint="visibili nel catalogo" lang="note" wide>{TI("note", "Per descrivere l'opera, se necessario", 3)}</NW7F>
        </section>

        <section className="nw7-s nw7-x2"><button type="button" className="nw7-more" onClick={() => setMore(!more)}><b>Riferimenti e documenti</b><span>{nRef + d.files.length ? (nRef + d.files.length) + " collegati" : "Cataloghi, bibliografia, opere correlate, file"}</span><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d={more ? "M6 15l6-6 6 6" : "M6 9l6 6 6-6"} /></svg></button>
          {more && <>{RG.filter(([k]) => k !== "ex" && k !== "col").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>)}
            <label className="nw5-drop" onDragOver={(e) => e.preventDefault()} onDrop={(e) => { e.preventDefault(); addFiles(e.dataTransfer.files); }}><Ic.up /><span>Trascina PDF, certificati o documenti<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 = (k2, v) => setD((p) => ({ ...p, files: p.files.map((x, jj) => jj === k ? { ...x, [k2]: 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>; })}</>}
        </section>
      </div>
    </div>

    {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 ? "Titolo e data sono obbligatori" : dirty ? <>Bozza salvata automaticamente · <button type="button" className="lnk" onClick={() => setD({ ...NW_EMPTY })}>Svuota</button></> : ""}</span>
      <Btn onClick={() => go({ v: "archive", p: "works" })}>Annulla</Btn><Btn disabled={!ok} onClick={() => save(false)}>Salva bozza</Btn><Btn k="dark" disabled={!ok} onClick={() => save(true)}>Salva e pubblica</Btn></div>
  </div>;
}

const NW7LT = ({ k, lg, setLg }) => <span className="nw7-lg">{["IT", "EN"].map((x) => <button key={x} type="button" className={(lg[k] || "IT") === x ? "on" : ""} onClick={() => setLg({ ...lg, [k]: x })}>{x}</button>)}</span>;
const NW7F = ({ l, req, hint, lang, wide, lg, setLg, children }) => <div className={"nw7-f" + (wide ? " w" : "")}><div className="nw7-fl"><b>{l}{req && <i className="req">*</i>}</b>{hint && <em>{hint}</em>}{lang && <NW7LT k={lang} lg={lg} setLg={setLg} />}</div>{children}</div>;
Object.assign(window, { Gallery, NewWorkPage, shrink, CATS });
