// Certify Unified — overview, artworks database, artwork record (three views).
const { useState: uS, useEffect: uE } = React;

function Welcome() {
  const { s, go } = useC(); const A = s.archive;
  const S = [["Importa le opere", "Da FileMaker, Excel o CSV. Ti affianchiamo nella mappatura dei campi.", Ic.up, () => go({ v: "archive", p: "import" }), "Importa"],
    ["Oppure aggiungi la prima opera", "Inizia con una scheda: titolo, anno, tecnica, immagine.", Ic.plus, () => go({ v: "archive", p: "new" }), "Nuova opera"],
    ["Configura il catalogo pubblico", "Categorie, campi pubblici e aspetto del catalogo.", Ic.globe, () => go({ v: "archive", p: "catalogue" }), "Configura"],
    ["Invita il team", "Aggiungi collaboratori e scegli cosa possono fare.", Ic.users, () => go({ v: "archive", p: "settings", sec: "team" }), "Invita"]];
  return <div className="page wl"><button className="lnk ob-again" onClick={openTour}>Scopri cosa puoi fare con Certify →</button><div className="wl-h"><img src="unified/img/logo-fa.png" alt="" /><h1>Benvenuta su Certify.</h1><p>Il tuo archivio è pronto. Inizia portando le opere: il resto si costruisce da lì.</p></div>
    <div className="wl-l">{S.map(([t, d, I, f, cta], i) => <div key={t} className={i === 0 ? "first" : ""}><span className="wl-i"><I /></span><div><b>{t}</b><span>{d}</span></div><Btn k={i === 0 ? "dark" : ""} onClick={f}>{cta}</Btn></div>)}</div>
    <p className="wl-f">Hai bisogno di aiuto con la migrazione? <a href="#" onClick={(e) => e.preventDefault()}>Prenota una sessione con il team Certify</a></p></div>;
}
const Warn = () => <svg className="warn-i" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.5h.01"/></svg>;
function Overview() {
  const { s, go, mut } = useC(); if (s.firstRun && !s.works.length) return <Welcome />; const W = s.works; const R = s.requests || [];
  const hr = new Date().getHours(); const hi = hr < 13 ? "Buongiorno" : hr < 18 ? "Buon pomeriggio" : "Buonasera";
  const full = (a) => a.title && a.year && a.medium && a.dims && a.catNo;
  const done = W.filter(full).length; const pct = W.length ? Math.round(done / W.length * 100) : 0;
  const pending = R.filter((r) => ["new", "review", "inspection", "payment"].includes(r.status)).length;
  const review = W.filter((a) => a.pub === "review").length;
  const K = [["Opere in archivio", W.length.toLocaleString("it-IT"), Ic.works, () => go({ v: "archive", p: "works" })], ["Pubblicate", W.filter((a) => a.pub === "published").length.toLocaleString("it-IT"), Ic.globe, () => go({ v: "archive", p: "works" })], ["Schede incomplete", (W.length - done).toLocaleString("it-IT"), Ic.list, () => go({ v: "archive", p: "works", sv: "inc" }), W.length - done > 0], ["Richieste in attesa", pending, Ic.clock, () => go({ v: "archive", p: "requests" })]];
  const missing = W.length - done; const one = (n, a, b) => n === 1 ? a : b;
  const newR = R.filter((r) => r.status === "new"), insp = R.filter((r) => r.status === "inspection");
  const blocked = W.filter((a) => a.pub === "review" && !full(a)).length, ready = review - blocked;
  const live = s.exhibitions.filter((x) => typeof exStatus === "function" && exStatus(x)[1] === "In corso");
  // u = blocks a process and needs action now; shown first and highlighted
  const items = [
    ...newR.slice(0, 2).map((r) => [Ic.seal, "Nuova richiesta di autentica", `${r.title} · inviata da ${r.name}`, () => go({ v: "archive", p: "request", id: r.id }), 1]),
    ...(insp.length ? [[Ic.clock, `${insp.length} ${one(insp.length, "opera da esaminare", "opere da esaminare")} in sede`, "Visione dell'originale richiesta", () => go({ v: "archive", p: "requests" }), 1]] : []),
    ...(blocked ? [[Ic.list, `${blocked} ${one(blocked, "pubblicazione bloccata", "pubblicazioni bloccate")}`, "Mancano campi obbligatori", () => go({ v: "archive", p: "works", sv: "blocked" }), 1]] : []),
    ...(ready ? [[Ic.globe, `${ready} ${one(ready, "opera pronta", "opere pronte")} da pubblicare`, "Approva la pubblicazione nel catalogo", () => go({ v: "archive", p: "works", sv: "ready" })]] : []),
    ...(missing ? [[Warn, `${missing.toLocaleString("it-IT")} opere con informazioni mancanti`, "Completa le schede quando hai i dati", () => go({ v: "archive", p: "works", sv: "inc" })]] : []),
    ...live.slice(0, 1).map((x) => [Ic.clock, `In mostra ora: ${x.title}`, `${x.venue}, ${x.city}`, () => go({ v: "archive", p: "exhibitions", id: x.id })]),
  ];
  const nu = items.filter((x) => x[4]).length;
  const hid = (s.dash && s.dash.hidden) || []; const [cz, setCz] = uS(false);
  const togH = (k) => mut((n) => { n.dash = n.dash || { hidden: [] }; const h = n.dash.hidden || []; n.dash.hidden = h.includes(k) ? h.filter((x) => x !== k) : [...h, k]; });
  const WG = [["w:todo", "Da seguire", "Le attività che richiedono un'azione"], ...(s.modules.auth ? [["w:auth", "Autentiche", "Incassi, emesse ed esiti"]] : []), ["w:recent", "Ultime opere", "Le schede aggiunte di recente"], ["w:activity", "Attività recente", "Ultime modifiche nell'archivio"]];
  return <div className="page ov3 ov4">
    <div className="ov4-top"><div className="ov3-h"><h1>{hi}{/^(archivio|fondazione)/i.test(s.archive.signatory) ? "" : ", " + s.archive.signatory.split(" ")[0]}.</h1><p>Ecco cosa succede nel tuo archivio.</p></div><div className="ov4-qa"><Btn onClick={() => setCz(true)}>Personalizza</Btn><Btn onClick={() => go({ v: "archive", p: "import" })}><Ic.up /> Importa</Btn><Btn onClick={() => go({ v: "archive", p: "requests" })}><Ic.clock /> Richieste</Btn><Btn onClick={() => go({ v: "public", p: "home" })}><Ic.globe /> Catalogo pubblico</Btn><Btn k="dark" onClick={() => go({ v: "archive", p: "new" })}><Ic.plus /> Nuova opera</Btn></div></div>
    {(() => { const KK = K.filter(([l]) => !hid.includes("k:" + l)); return KK.length > 0 && <div className="ov3-k" style={{ gridTemplateColumns: `repeat(${Math.min(KK.length, 4)},minmax(0,1fr))` }}>{KK.map(([l, v, I, f, w]) => <button key={l} onClick={f}><div><span>{l}</span>{w ? <Warn /> : <I />}</div><b>{v}</b></button>)}</div>; })()}
    {s.modules.auth && !hid.includes("w:auth") && (() => { const RR = s.requests || []; const inc = RR.reduce((t, x) => t + (x.paid || 0), 0); const iss = s.certs.filter((c) => c.status === "issued").length; const dec = RR.filter((x) => ["approved", "payment", "issued", "rejected", "archived"].includes(x.status)); const ok = dec.filter((x) => ["approved", "payment", "issued"].includes(x.status)).length; const due = RR.filter((x) => x.status === "payment").reduce((t, x) => t + ((x.fee && x.fee.cert) || 0), 0);
      return <div className="ov5"><div className="ov5-h"><b>Autentiche</b><button className="lnk" onClick={() => go({ v: "archive", p: "requests" })}>Richieste</button></div>
        <div className="ov5-g"><div><span>Incassato</span><b>€ {inc.toLocaleString("it-IT")}</b></div><div><span>Da incassare</span><b>€ {due.toLocaleString("it-IT")}</b></div><div><span>Autentiche emesse</span><b>{iss}</b></div><div><span>In esame</span><b>{RR.filter((x) => ["new", "review", "inspection"].includes(x.status)).length}</b></div><div><span>Esiti positivi</span><b>{dec.length ? Math.round(ok / dec.length * 100) + "%" : "—"}</b></div></div></div>; })()}
    <div className="ov4-g">{!hid.includes("w:todo") && <section className="ov4-p"><h2 className="ov3-t">Da seguire{nu > 0 && <span className="ov3-n">{nu} da fare ora</span>}</h2>
    <div className="ov3-l">{items.map(([I, tt, sub, f, u], k) => <button key={k} className={u ? "ov3-u" : ""} onClick={f}><span className="ov3-i"><I /></span><div><b>{tt}</b><span>{sub}</span></div><Ic.chev /></button>)}{!items.length && <div className="empty">Tutto in ordine.</div>}</div></section>}
    {!hid.includes("w:recent") && <section className="ov4-p"><h2 className="ov3-t">Ultime opere</h2><div className="ov4-w">{W.slice().sort((x, y) => (y.added || 0) - (x.added || 0)).slice(0, 2).map((a) => <button key={a.id} onClick={() => go({ v: "archive", p: "work", id: a.id })}><div><Art a={a} label={false} r={0} /></div><b>{a.title}</b><span>{a.yearLabel || a.year}</span></button>)}</div></section>}
    {!hid.includes("w:activity") && <section className="ov4-p"><h2 className="ov3-t">Attività recente</h2>
    <div className="ov3-l">{s.events.slice(0, 5).map((e, k) => <div key={k} className="ov3-e"><span className={"ev-d " + (e.type || "")}></span><div><b>{e.text}</b><span>{e.who} · {e.at}</span></div></div>)}</div></section>}</div>
    {cz && <Modal title="Personalizza la dashboard" onClose={() => setCz(false)} foot={<><button className="lnk" style={{ marginRight: "auto" }} onClick={() => mut((n) => { n.dash = { hidden: [] }; })}>Ripristina</button><Btn k="dark" onClick={() => setCz(false)}>Fatto</Btn></>}>
      <p className="mut" style={{ marginTop: 0 }}>Scegli cosa tenere in evidenza. Vale per tutto l'archivio.</p>
      <div className="dz-h">In evidenza</div>
      {K.map(([l, v, I]) => <label key={l} className="dz-r"><span className="dz-i"><I /></span><div><b>{l}</b><span>{v}</span></div><Toggle on={!hid.includes("k:" + l)} set={() => togH("k:" + l)} /></label>)}
      <div className="dz-h">Sezioni</div>
      {WG.map(([k, l, d]) => <label key={k} className="dz-r"><span className="dz-i"><Ic.list /></span><div><b>{l}</b><span>{d}</span></div><Toggle on={!hid.includes(k)} set={() => togH(k)} /></label>)}
    </Modal>}
  </div>;
}
function WkSel({ v, set, label, opts }) {
  const O = opts.filter(Boolean).map((o) => Array.isArray(o) ? o : [o, o]); const cur = v ? O.find((o) => o[0] === v) : null;
  return <label className={"wk-f" + (v ? " on" : "")}><span>{cur ? cur[1] : label}</span><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg>
    <select value={v} onChange={(e) => set(e.target.value)}><option value="">{label}: tutte</option>{O.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></label>;
}
function Works() {
  const { s, go, mut, say } = useC();
  const [bd, setBd] = uS(false);
  const CAT_ORD = (window.CU_CATS || ["Opere su tela", "Opere su carta", "Opere seriali", "Grafiche e multipli", "Opere fotografiche", "Gioielli e altri progetti"]); const cats0 = [...new Set(s.works.map((a) => a.category))].sort((x, y) => ((CAT_ORD.indexOf(x) + 1) || 99) - ((CAT_ORD.indexOf(y) + 1) || 99));
  const [q, setQ] = uS("");const [cat, setCat] = uS(s.route.sv ? "" : (cats0[0] || ""));const [pub, setPub] = uS("");const [au, setAu] = uS("");const [pg, setPg] = uS(0);const [sel, setSel] = uS([]);const [view, setView] = uS("grid");const [add, setAdd] = uS(false);const [ord, setOrd] = uS("year-asc");const [grp, setGrp] = uS("catdec");const [mat, setMat] = uS("");const [col, setCol] = uS(""); const [sv, setSv] = uS(s.route.sv || "all"); uE(() => { if (s.route.sv) { setSv(s.route.sv); setCat(""); } }, [s.route.sv]);
  const cats = cats0;const mats = [...new Set(s.works.map((a) => a.medium))];const cols = [...new Set(s.works.map((a) => a.collection).filter(Boolean))];
  const inc = (a) => !(a.title && a.year && a.medium && a.dims && a.catNo);
  const SV = [["all", "Tutte", () => true], ["inc", "Schede incomplete", inc], ["ready", "Pronte da pubblicare", (a) => a.pub === "review" && !inc(a)], ["blocked", "Pubblicazioni bloccate", (a) => a.pub === "review" && inc(a)], ["pub", "Pubblicate", (a) => a.pub === "published"], ...(s.modules.auth ? [["auth", "Autenticate", (a) => !!certOf(s, a.id)]] : []), ["rec", "Aggiornate di recente", (a) => ["adesso", "oggi", "ieri"].includes(a.edited)]];
  const svf = (SV.find((x) => x[0] === sv) || SV[0])[2];
  const L = sortWorks(s.works.filter(svf).filter((a) => (!cat || a.category === cat) && (!mat || a.medium === mat) && (!col || a.collection === col) && (!pub || a.pub === pub) && (!au || (au === "yes" ? !!certOf(s, a.id) : !certOf(s, a.id))) && (a.title + a.catNo + a.year + a.certifyId + a.medium + a.collection).toLowerCase().includes(q.toLowerCase())), ord);
  const CO = s.customOrder || []; if (ord === "custom") L.sort((x, y) => ((CO.indexOf(x.id) + 1) || 1e6) - ((CO.indexOf(y.id) + 1) || 1e6) || x.added - y.added);
  const bindW = useReorder(L.map((a) => a.id), (o) => { mut((n) => { const rest = (n.customOrder || []).filter((id) => !o.includes(id)); n.customOrder = [...o, ...rest]; }); if (ord !== "custom") setOrd("custom"); say("Ordine personalizzato salvato"); });
  const N = 40;const page = L.slice(pg * N, pg * N + N);uE(() => setPg(0), [q, cat, pub, au, mat, col, ord, grp, sv]);
  const bulk = (st) => {mut((n) => {n.works.forEach((a) => {if (sel.includes(a.id)) a.pub = st;});log(n, { type: "catalogo", text: `${sel.length} opere ${st === "published" ? "pubblicate nel catalogo" : "riportate in bozza"}` });});say(`${sel.length} opere aggiornate`);setSel([]);};
  return <div className="page">
    <PH t="Opere" right={<><Btn onClick={() => go({ v: "archive", p: "import" })}><Ic.up /> Importa</Btn><Btn k="dark" onClick={() => go({ v: "archive", p: "new" })}><Ic.plus /> Nuova opera</Btn></>} />
    <div className="ctab">{[["", "Tutte", s.works.length], ...cats0.map((c) => [c, c, s.works.filter((x) => x.category === c).length])].map(([k, l, n]) => <button key={k || "all"} className={cat === k ? "on" : ""} onClick={() => setCat(k)}>{l}<em>{n}</em></button>)}</div>
    <div className="wt2">
      <label className="wt2-s"><Ic.search /><input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Cerca titolo, anno o numero…" />{q && <button onClick={() => setQ("")} aria-label="Cancella">×</button>}</label>
      <div className="wt2-f">
        <WkSel v={sv === "all" ? "" : sv} set={(x) => setSv(x || "all")} label="Vista" opts={SV.filter((x) => x[0] !== "all").map(([k, l, f]) => [k, `${l} · ${s.works.filter(f).length}`])} />
        <WkSel v={mat} set={setMat} label="Tecnica" opts={mats} />
        <WkSel v={col} set={setCol} label="Collezione" opts={cols} />
        <WkSel v={pub} set={setPub} label="Stato" opts={[["published", "Pubblicate"], ["review", "In revisione"], ["draft", "Bozze"]]} />
        {s.modules.auth && <WkSel v={au} set={setAu} label="Autentica" opts={[["yes", "Autenticate"], ["no", "Non autenticate"]]} />}
        {(mat || col || pub || au || sv !== "all") && <button className="wt2-clr" onClick={() => { setMat(""); setCol(""); setPub(""); setAu(""); setSv("all"); }}>Azzera</button>}
      </div>
      <div className="wt2-r">
        <label className="wt2-o"><select value={ord} onChange={(e) => setOrd(e.target.value)}>{[["year-asc", "Dal più antico"], ["year-desc", "Dal più recente"], ["added-desc", "Ultime aggiunte"], ["title", "Titolo A–Z"], ["custom", "Ordine personalizzato"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6"/></svg></label>
        <label className="wt2-o"><select value={grp} onChange={(e) => setGrp(e.target.value)}>{[["catdec", "Per decennio"], ["year", "Per anno"], ["medium", "Per tecnica"], ["collection", "Per collezione"], ["none", "Senza gruppi"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M6 9l6 6 6-6"/></svg></label>
        <div className="wt2-vt"><button className={view === "grid" ? "on" : ""} onClick={() => setView("grid")} aria-label="Griglia"><Ic.grid /></button><button className={view === "list" ? "on" : ""} onClick={() => setView("list")} aria-label="Elenco"><Ic.list /></button></div>
      </div>
    </div>
    {sel.length > 0 && <div className="bulk"><b>{sel.length} selezionate</b><Btn k="sm" onClick={() => bulk("published")}>Pubblica</Btn><Btn k="sm" onClick={() => bulk("draft")}>Riporta in bozza</Btn><Btn k="sm ghost-del" onClick={() => setBd(true)}>Elimina</Btn>{bd && <DeleteWorks ids={sel} onClose={() => setBd(false)} onDone={(x) => setSel(sel.filter((i) => !x.includes(i)))} />}<button className="lnk" onClick={() => setSel([])}>Annulla</button></div>}
    {groupWorks(grp === "none" ? page : L, grp).map(([gl, page]) => <Group key={gl || "all"} label={gl} items={page} render={(page) => view === "list" ? <div className="tbl"><table><thead><tr><th style={{ width: 34 }}><input type="checkbox" checked={page.length > 0 && page.every((a) => sel.includes(a.id))} onChange={(e) => setSel(e.target.checked ? [...new Set([...sel, ...page.map((a) => a.id)])] : sel.filter((x) => !page.some((a) => a.id === x)))} /></th><th></th><th>Opera</th><th>N. catalogo</th><th>Stato</th>{s.modules.auth && <th>Autentica</th>}</tr></thead>
      <tbody>{page.map((a) => <tr key={a.id} className="drg-tr" {...bindW(a.id)} onClick={() => go({ v: "archive", p: "work", id: a.id })}>
        <td className="drg-td" onClick={(e) => e.stopPropagation()}><Grip /><input type="checkbox" checked={sel.includes(a.id)} onChange={(e) => setSel(e.target.checked ? [...sel, a.id] : sel.filter((x) => x !== a.id))} /></td>
        <td style={{ width: 52 }}><div className="th"><Art a={a} label={false} r={6} /></div></td>
        <td><b className="wi-t">{a.title}{inc(a) && <span className="wi-w" title="Scheda incompleta"><Warn /></span>}</b><div className="mut sm">{a.yearLabel || a.year} · {a.medium}</div></td><td className="mono">{a.catNo}</td><td><PubPill a={a} /></td>{s.modules.auth && <td><AuthPill s={s} a={a} /></td>}</tr>)}</tbody></table></div> :
    <div className="wgrid">{page.map((a) => <button key={a.id} className="wc drg-on" {...bindW(a.id)} onClick={() => go({ v: "archive", p: "work", id: a.id })}><Grip /><div className="wc-i"><Art a={a} r={10} />{inc(a) && <span className="wc-w" title="Scheda incompleta"><Warn /></span>}</div><b>{a.title}</b><span className="mut sm">{a.yearLabel || a.year} · <span className="mono">{a.catNo}</span></span><div className="row" style={{ flexWrap: "wrap" }}><PubPill a={a} /><AuthPill s={s} a={a} /></div></button>)}</div>} />)}
    {!L.length && <div className="empty">Nessuna opera corrisponde ai filtri.</div>}
    {grp === "none" && L.length > N && <div className="pager"><span className="mut">{pg * N + 1}–{Math.min(L.length, pg * N + N)} di {L.length.toLocaleString("it-IT")}</span><Btn k="sm" disabled={pg === 0} onClick={() => setPg(pg - 1)}>Precedenti</Btn><Btn k="sm" disabled={(pg + 1) * N >= L.length} onClick={() => setPg(pg + 1)}>Successive</Btn></div>}
    {add && <NewWork onClose={() => setAdd(false)} />}
  </div>;
}

function NewWork({ onClose }) {
  const { s, mut, go, say } = useC();const [d, setD] = uS({ title: "", year: "", medium: "", dims: "", category: "Opere su tela" });
  const create = () => {const i = s.works.length + 1000;const a = { ...window.CU_MAKE(i), ...d, year: +d.year || d.year, catNo: `EM-${d.year || "SD"}-${String(s.works.length + 1).padStart(4, "0")}`, series: "", exhibitions: [], provenance: [], docs: [], edited: "adesso" };
    mut((n) => {n.works.unshift(a);log(n, { type: "catalogo", text: `Nuova scheda: ${a.title}` });});say("Scheda creata");onClose();go({ v: "archive", p: "work", id: a.id });};
  const F = (k, l) => <label className="fld"><span>{l}</span><input value={d[k]} onChange={(e) => setD({ ...d, [k]: e.target.value })} /></label>;
  return <Modal title="Nuova opera" onClose={onClose} foot={<><Btn onClick={onClose}>Annulla</Btn><Btn k="dark" disabled={!d.title.trim()} onClick={create}>Crea scheda</Btn></>}>
    <p className="mut" style={{ marginTop: 0 }}>Crea il record dell'opera. Potrai completarlo, pubblicarlo e autenticarlo dalla stessa scheda.</p>
    {F("title", "Titolo")}<div className="g2f">{F("year", "Anno")}<label className="fld"><span>Categoria</span><select value={d.category} onChange={(e) => setD({ ...d, category: e.target.value })}>{(window.CU_CATS || ["Opere su tela", "Opere su carta", "Opere seriali", "Grafiche e multipli", "Opere fotografiche", "Gioielli e altri progetti"]).map((c) => <option key={c}>{c}</option>)}</select></label></div>
    <div className="g2f">{F("medium", "Tecnica")}{F("dims", "Dimensioni")}</div>
  </Modal>;
}

// ---- artwork record ----
const VIS = { pub: [Ic.pub, "Pubblico"], col: [Ic.key, "Collezionista"], arc: [Ic.lock, "Solo archivio"] };
function VisDots({ s, k }) {const f = s.fields.find((x) => x.k === k);if (!f) return null;return <span className="vis">{f.pub ? <span title="Visibile nel catalogo pubblico"><Ic.pub /></span> : null}{f.col ? <span title="Visibile al collezionista"><Ic.key /></span> : null}{!f.pub && !f.col ? <span title="Solo archivio"><Ic.lock /></span> : null}</span>;}

// ---- shared drag-to-reorder: three-line handle shown on hover, left of the item; autosaves ----
const Grip = () => <span className="grip" aria-hidden="true"><svg viewBox="0 0 16 16" width="14" height="14"><path d="M3 4.5h10M3 8h10M3 11.5h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg></span>;
function useReorder(list, onSave) {
  const [drag, setDrag] = uS(null); const [over, setOver] = uS(null);
  const bind = (id) => ({ draggable: true, "data-drag": drag === id ? "1" : over === id ? "over" : undefined,
    onDragStart: (e) => { setDrag(id); e.dataTransfer.effectAllowed = "move"; try { e.dataTransfer.setData("text/plain", id); } catch (_) {} },
    onDragOver: (e) => { if (drag == null) return; e.preventDefault(); if (over !== id) setOver(id); },
    onDragEnd: () => { setDrag(null); setOver(null); },
    onDrop: (e) => { e.preventDefault(); if (drag == null || drag === id) return setOver(null); const L = list.filter((x) => x !== drag); const k = L.indexOf(id); L.splice(k < 0 ? L.length : k + (list.indexOf(drag) < list.indexOf(id) ? 1 : 0), 0, drag); onSave(L); setDrag(null); setOver(null); } });
  return bind;
}
const REQ = ["title", "year", "medium", "dims"];
const ARCH_P = "In corso di archiviazione";
const archLabel = (a) => a.catNo || (a.archStatus === "process" ? ARCH_P : "");
const EyeOff = () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><path d="M3 3l18 18"/><path d="M10.6 5.1A10 10 0 0 1 12 5c5 0 8.5 4.5 9.5 7a13 13 0 0 1-2.6 3.6M6.6 6.6C4.4 8 2.9 10.2 2.5 12c1 2.5 4.5 7 9.5 7 1.5 0 2.9-.4 4.1-1"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg>;
const isAdmin = (s) => !s.role || /ammin|presid/i.test(s.archive.role || "Amministratrice") || s.role === "admin";
const DSECS = [
  ["main", "Informazioni principali", "Titolo, anno, tecnica, dimensioni, n. archivio", ["title", "year", "medium", "dims", "catNo"], true],
  ["class", "Classificazione", "Categoria, serie, edizione", ["category", "series", "edition"]],
  ["doc", "Documentazione", "Iscrizioni, note", ["inscr", "notePub"]],
  ["where", "Dove si trova", "Collezione, conservazione, mostra in corso", ["collection", "loc", "show"]],
  ["admin", "Dati amministrativi", "Informazioni interne", ["notes", "origin"]],
];

function Work() {
  const { s, go, mut, say } = useC();const a = byId(s.works, s.route.id);
  const [tab, setTab] = uS(s.route.tab || "overview");const [as, setAs] = uS("archive");const [ed, setEd] = uS(false);const [d, setD] = uS(null);const [issue, setIssue] = uS(false);const [del, setDel] = uS(false);
  uE(() => {setTab(s.route.tab || "overview");setEd(false);setAs("archive");}, [s.route.id, s.route.tab]);
  if (!a) return <div className="page"><div className="empty">Opera non trovata.</div></div>;
  const c = certOf(s, a.id);const own = c && c.ownerId ? byId(s.collectors, c.ownerId) : null;const all = s.certs.filter((x) => x.artworkId === a.id);
  const T = [["overview", "Scheda"], ["cr", "Scientifica"], ["docs", "Documenti"], ["prov", "Mostre e provenienza"], ["biblio", "Bibliografia"], ...(s.modules.auth ? [["auth", "Autentica"], ["owner", "Proprietà"]] : []), ["activity", "Attività"]];
  const save = () => {mut((n) => {const x = byId(n.works, a.id);["title", "year", "medium", "dims", "category", "collection", "loc", "notes", "inscr", "notePub", "catNo", "archStatus"].forEach((k) => {if (String(x[k] || "") !== String(d[k] || "")) {log(n, { type: "modifica", artworkId: a.id, text: `${a.title}: ${k} «${x[k] || "—"}» → «${d[k] || "—"}»` });x[k] = d[k];}});x.edited = "adesso"; x.updatedAt = new Date().toLocaleDateString("it-IT");});setEd(false);say("Modifiche salvate e registrate");};
  const setPub = (st) => {mut((n) => {byId(n.works, a.id).pub = st;log(n, { type: "catalogo", artworkId: a.id, text: `${a.title}: ${st === "published" ? "pubblicata nel catalogo" : st === "review" ? "inviata in revisione" : "rimossa dal catalogo"}` });});say(st === "published" ? "Pubblicata nel catalogo" : "Stato aggiornato");};
  const Row = ({ k, l, v, b, hide }) => <div className="dr" {...(b || {})}>{b && <Grip />}<span>{l}{REQ.includes(k) && <i className="req">*</i>}<VisDots s={s} k={k} />{hide && <button className="dr-hide" title="Nascondi campo" aria-label="Nascondi campo" onClick={(e) => { e.stopPropagation(); hide(); }}><EyeOff /></button>}</span>{k === "catNo" ? (ed ? <ArchNo d={d} setD={setD} /> : a.catNo ? <b>{a.catNo}</b> : a.archStatus === "process" ? <b><span className="ap-pill">{ARCH_P}</span></b> : <b className="dr-e">Non assegnato</b>) : ed && ["title", "year", "medium", "dims", "category", "collection", "loc", "notes", "inscr", "notePub"].includes(k) ? <input value={d[k] || ""} onChange={(e) => setD({ ...d, [k]: e.target.value })} /> : <b className={v ? "" : "dr-e"}>{v || "Da compilare"}</b>}</div>;
  return <div className="page">
    {(() => { const same = s.works.filter((w) => w.category === a.category).sort((x, y) => (x.added || 0) - (y.added || 0) || x.year - y.year); const k = same.findIndex((w) => w.id === a.id); const pv = same[k - 1], nx = same[k + 1];
      const nav = (w) => w && go({ v: "archive", p: "work", id: w.id });
      return <div className="wdn"><button className="lnk back" onClick={() => go({ v: "archive", p: "works" })}><Ic.back /> Opere</button>
        <div className="wdn-p"><span>{a.category} · {k + 1} di {same.length}</span>
          <button disabled={!pv} title={pv ? pv.title : ""} onClick={() => nav(pv)} aria-label="Opera precedente"><Ic.back /></button>
          <button disabled={!nx} title={nx ? nx.title : ""} onClick={() => nav(nx)} aria-label="Opera successiva"><Ic.chev /></button></div></div>; })()}
    <div className="wd"><div className="wd-l"><div className="wh-i"><Gallery a={a} edit /></div></div><div className="wd-r">
    <div className="wh">
      <div className="wh-b"><div className="ids"><span>N. catalogo <b>{a.catNo}</b></span><span>Certify ID <b>{a.certifyId}</b></span></div>
        <h1>{a.title}</h1><div className="wh-m">{[s.archive.artist, a.yearLabel || a.year, a.medium, a.dims].filter(Boolean).join(" · ")}</div>
        <div className="wh-p">{s.modules.catalogue && <PubPill a={a} />}<AuthPill s={s} a={a} />{own && <Pill k="lt">Proprietario registrato</Pill>}</div></div>
      <div className="wh-a">
        {s.modules.catalogue && (a.pub !== "published" ? <Btn onClick={() => setPub("published")}><Ic.globe /> Pubblica nel catalogo</Btn> : <Btn onClick={() => go({ v: "public", p: "work", id: a.id })}><Ic.globe /> Vedi nel catalogo</Btn>)}
        {s.modules.auth && (c ? <Btn k="dark" onClick={() => setTab("auth")}><Ic.seal /> Autentica {c.id.slice(-6)}</Btn> : <Btn k="bx" onClick={() => setTab("auth")}><Ic.seal /> Emetti autentica digitale</Btn>)}
        <button className="wh-del" onClick={() => setDel(true)}>Elimina opera</button>
      </div>
      {del && <DeleteWorks ids={[a.id]} onClose={() => setDel(false)} onDone={() => go({ v: "archive", p: "works" })} />}
    </div>
    <div className="vw5"><span>Vedi come</span><div className="vw5-s">{[["archive", "Archivio"], ["public", "Catalogo"], ["collector", "Collezionista"]].map(([k, l]) => <button key={k} className={as === k ? "on" : ""} onClick={() => setAs(k)}>{l}</button>)}</div></div>
    {as !== "archive" ? <AsView a={a} who={as} /> : <>
      <div className="tabs">{T.map(([k, l]) => <button key={k} className={tab === k ? "on" : ""} onClick={() => setTab(k)}>{l}</button>)}</div>
      {drift(s, a) && <div className="warn"><b>I dati della scheda sono cambiati dopo l'emissione dell'autentica.</b> Il certificato conserva i dati certificati il {c.issuedAt}. <button className="lnk" onClick={() => setTab("auth")}>Valuta una rettifica</button></div>}
      {tab === "overview" && <DetailSections a={a} s={s} Row={Row} ed={ed} setEd={setEd} setD={setD} save={save} go={go} mut={mut} />}
      {tab === "cr" && <CRTab a={a} />}
      {tab === "docs" && <MediaTab a={a} />}
      {tab === "biblio" && <BiblioTab a={a} />}
      {tab === "prov" && <div className="g2" style={{ alignItems: "start" }}>
        <div className="card"><div className="c-h"><h2>Mostre</h2><VisDots s={s} k="exhibitions" /></div>{a.exhibitions.map((id) => {const x = byId(s.exhibitions, id);return <div key={id} className="li"><span className="mono mut">{(x.from || "").slice(0, 4)}</span><div className="grow"><button className="lnk" style={{ textDecoration: "none", textAlign: "left" }} onClick={() => go({ v: "archive", p: "exhibitions", id: x.id })}><b>{x.title}</b></button><div className="mut sm">{x.venue}, {x.city} · {fmtD(x.from)}</div></div><Pill k={exStatus(x)[0]}>{exStatus(x)[1]}</Pill><button className="ib" aria-label="Scollega" onClick={() => mut((n) => {const w = byId(n.works, a.id);w.exhibitions = w.exhibitions.filter((e) => e !== id);})}><Ic.x /></button></div>;})}{!a.exhibitions.length && <div className="empty">Nessuna mostra collegata.</div>}
          <select style={{ marginTop: 12 }} value="" onChange={(e) => e.target.value && mut((n) => {const w = byId(n.works, a.id);if (!w.exhibitions.includes(e.target.value)) w.exhibitions.push(e.target.value);log(n, { type: "catalogo", artworkId: a.id, text: `${a.title}: collegata a una mostra` });})}><option value="">+ Collega una mostra…</option>{s.exhibitions.filter((x) => !a.exhibitions.includes(x.id)).map((x) => <option key={x.id} value={x.id}>{x.title} · {(x.from || "").slice(0, 4)}</option>)}</select></div>
        <div className="card"><div className="c-h"><h2>Provenienza</h2><VisDots s={s} k="provenance" /></div>{a.provenance.map((p, i) => <div key={i} className="li"><span className="mono mut" style={{ minWidth: 96 }}>{p.when}</span><b className="grow">{p.who}</b>
          <select value={p.show} onChange={(e) => mut((n) => {byId(n.works, a.id).provenance[i].show = e.target.value;})}><option value="named">Con nome</option><option value="anon">«Collezione privata»</option><option value="hidden">Non pubblicato</option></select></div>)}{!a.provenance.length && <div className="empty">Nessun passaggio registrato.</div>}</div>
      </div>}
      {tab === "auth" && <AuthTab a={a} onIssue={() => setTab("auth")} />}
      {tab === "owner" && <OwnerTab a={a} />}
      {tab === "activity" && <div className="card">{s.events.filter((e) => e.artworkId === a.id).map((e, i) => <div key={i} className="ev"><span className={"ev-d " + (e.type || "")}></span><div><b>{e.text}</b><span>{e.who} · {e.at}{e.hash ? " · evento verificabile" : ""}</span></div></div>)}{!s.events.some((e) => e.artworkId === a.id) && <div className="empty">Nessuna attività registrata per questa opera.</div>}</div>}
    </>}
    </div></div>
    {issue && <IssueFlow a={a} onClose={() => setIssue(false)} />}
  </div>;
}

const Toggle = ({ on, set }) => <button type="button" className={"tg" + (on ? " on" : "")} onClick={(e) => { e.preventDefault(); set(); }} aria-pressed={on}><i></i></button>;
// Archive number: blank, "in corso di archiviazione", or an assigned number.
function ArchNo({ d, setD }) {
  const proc = d.archStatus === "process";
  return <div className="ap2">
    <input value={proc ? "" : (d.catNo || "")} disabled={proc} placeholder={proc ? "In corso di archiviazione" : "Es. P-090317/894"} onChange={(e) => setD({ ...d, catNo: e.target.value, archStatus: "" })} />
    <label className={"ap2-c" + (proc ? " on" : "")}><input type="checkbox" checked={proc} onChange={(e) => setD({ ...d, archStatus: e.target.checked ? "process" : "", catNo: e.target.checked ? "" : d.catNo })} /><i></i>Opera in corso di archiviazione</label>
  </div>;
}
function DetailSections({ a, s, Row, ed, setEd, setD, save, go, mut }) {
  const L = { title: "Titolo", year: "Anno", medium: "Tecnica", dims: "Dimensioni", catNo: "N. Archivio", category: "Categoria", series: "Serie", edition: "Edizione", inscr: "Iscrizioni", notePub: "Note", collection: "Collezione", loc: "Luogo di conservazione", notes: "Note di ricerca" };
  const lay = s.detailLayout || {}; const secOrd = (lay.secs || DSECS.map((x) => x[0])).filter((k) => DSECS.some((x) => x[0] === k));
  DSECS.forEach((x) => { if (!secOrd.includes(x[0])) secOrd.push(x[0]); });
  const [open, setOpen] = uS({ main: true }); const [saved, setSaved] = uS(false); const [mg, setMg] = uS(false);
  const hidF = lay.hidden || []; const hidS = lay.hiddenSecs || []; const adm = isAdmin(s);
  const persist = (fn) => { mut((n) => { n.detailLayout = n.detailLayout || {}; fn(n.detailLayout); }); setSaved(true); clearTimeout(window.__dlT); window.__dlT = setTimeout(() => setSaved(false), 1400); };
  const bindSec = useReorder(secOrd, (o) => persist((dl) => { dl.secs = o; }));
  const hideF = (k) => persist((dl) => { dl.hidden = [...new Set([...(dl.hidden || []), k])]; });
  const togF = (k) => persist((dl) => { const h = dl.hidden || []; dl.hidden = h.includes(k) ? h.filter((x) => x !== k) : [...h, k]; });
  const togS = (k) => persist((dl) => { const h = dl.hiddenSecs || []; dl.hiddenSecs = h.includes(k) ? h.filter((x) => x !== k) : [...h, k]; });
  const miss = REQ.filter((k) => !a[k]);
  const Fields = ({ sec }) => { const base = sec[3]; const ord = ((lay.fields || {})[sec[0]] || base).filter((k) => base.includes(k)); base.forEach((k) => { if (!ord.includes(k)) ord.push(k); });
    const bind = useReorder(ord, (o) => persist((dl) => { dl.fields = dl.fields || {}; dl.fields[sec[0]] = o; }));
    return <div className="ds-f">{ord.filter((k) => !hidF.includes(k)).map((k) => {
      if (k === "show") { const sh = currentShow(s, a); return <div key={k} className="dr" {...bind(k)}><Grip /><span>Mostra in corso</span><b className={sh ? "" : "dr-e"}>{sh ? <button className="lnk" onClick={() => go({ v: "archive", p: "exhibitions", id: sh.id })}>{sh.venue}, {sh.city} · fino al {fmtD(sh.to)}</button> : "Nessuna"}</b></div>; }
      if (k === "origin") return <div key={k} className="dr" {...bind(k)}><Grip /><span>Origine della scheda</span><b className="mut" style={{ fontWeight: 400 }}>{a.added < (window.CU_REAL_N || 0) ? "Importata dal database dell'archivio" : a.added >= 1000 ? "Nuova scheda" : "Importata da FileMaker"} · n. {a.added + 1}{a.file ? " · " + a.file : ""}</b></div>;
      return <Row key={k} k={k} l={L[k]} v={a[k]} b={bind(k)} hide={adm && !ed && !REQ.includes(k) ? () => hideF(k) : null} />; })}</div>; };
  const done = (sec) => sec[3].filter((k) => !["show", "origin"].includes(k)).filter((k) => a[k]).length + "/" + sec[3].filter((k) => !["show", "origin"].includes(k)).length;
  return <div className="card ds">
    <div className="c-h"><h2>Dati dell'opera</h2><div className="row">{saved && <span className="ds-sv">Salvato</span>}{adm && <button className="ds-mg" onClick={() => setMg(true)}>Gestisci campi{hidF.length + hidS.length ? ` · ${hidF.length + hidS.length} ${hidF.length + hidS.length === 1 ? "nascosto" : "nascosti"}` : ""}</button>}{ed ? <><Btn k="sm" onClick={() => setEd(false)}>Annulla</Btn><Btn k="sm dark" onClick={save}>Salva</Btn></> : <Btn k="sm" onClick={() => { setD({ ...a }); setEd(true); }}>Modifica</Btn>}</div></div>
    {miss.length > 0 && <div className="ds-miss"><div className="ds-miss-h"><b>Scheda da completare</b><span>{miss.length} {miss.length === 1 ? "campo" : "campi"}</span></div>
      <div className="ds-miss-l"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#e0a100" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16h.01"/></svg>{miss.map((k, i) => <React.Fragment key={k}>{i > 0 && (i === miss.length - 1 ? " e " : ", ")}<button onClick={() => { setD({ ...a }); setEd(true); }}>{L[k].toLowerCase()}</button></React.Fragment>)} {miss.length === 1 ? "mancante" : "mancanti"}</div>
      {s.modules.catalogue && <p>Completa i campi obbligatori per pubblicare l'opera.</p>}</div>}
    {secOrd.filter((id) => !hidS.includes(id)).map((id) => { const sec = DSECS.find((x) => x[0] === id); const on = sec[4] || open[id] || ed;
      return <section key={id} className={"ds-s" + (on ? " on" : "")} {...bindSec(id)}>
        <div className="ds-h" onClick={() => !sec[4] && setOpen({ ...open, [id]: !open[id] })}><Grip />
          <svg className="ds-c" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2"><path d={on ? "M6 9l6 6 6-6" : "M9 6l6 6-6 6"} /></svg>
          <b>{sec[1]}</b><span>{sec[4] ? "Sempre aperta" : on ? done(sec) + " compilati" : sec[2]}</span></div>
        {on && <Fields sec={sec} />}
      </section>; })}
    {mg && <Modal title="Gestisci campi" onClose={() => setMg(false)}>
      <p className="mut" style={{ marginTop: 0 }}>Scegli cosa mostrare nella scheda di lavoro. Vale per tutto l'archivio. Nascondere un campo non cancella i dati e non cambia la visibilità nel catalogo pubblico.</p>
      {secOrd.map((id) => { const sec = DSECS.find((x) => x[0] === id); return <div key={id} className="mg-s">
        <label className="mg-r mg-sh"><b>{sec[1]}</b>{sec[4] ? <span className="mut sm">Sempre visibile</span> : <Toggle on={!hidS.includes(id)} set={() => togS(id)} />}</label>
        {sec[3].map((k) => <label key={k} className={"mg-r" + (hidS.includes(id) ? " off" : "")}><span>{k === "show" ? "Mostra in corso" : k === "origin" ? "Origine della scheda" : L[k]}{REQ.includes(k) && <i className="req">*</i>}</span>{REQ.includes(k) ? <span className="mut sm">Obbligatorio</span> : <Toggle on={!hidF.includes(k)} set={() => togF(k)} />}</label>)}
      </div>; })}
      <div className="row" style={{ justifyContent: "space-between", marginTop: 16 }}><button className="lnk" onClick={() => persist((dl) => { delete dl.hidden; delete dl.hiddenSecs; delete dl.secs; delete dl.fields; })}>Ripristina configurazione predefinita</button><Btn k="dark" onClick={() => setMg(false)}>Fatto</Btn></div>
    </Modal>}
    <div className="legend"><span><i className="req">*</i> Obbligatorio</span><span><Ic.pub /> Catalogo pubblico</span><span><Ic.key /> Collezionista</span><span><Ic.lock /> Solo archivio</span><button className="lnk" onClick={() => go({ v: "archive", p: "catalogue" })}>Gestisci visibilità</button></div>
  </div>;
}

// The same record rendered as the public catalogue and as the collector see it.
function AsView({ a, who }) {
  const { s } = useC();const k = who === "public" ? "pub" : "col";const c = certOf(s, a.id);
  const own = c && c.ownerId ? byId(s.collectors, c.ownerId) : null;
  const blocked = who === "public" ? !s.modules.catalogue || a.pub !== "published" : !own;
  const rows = [["catNo", "N. catalogo", a.catNo], ["medium", "Tecnica", a.medium], ["dims", "Dimensioni", a.dims], ["category", "Categoria", a.category], ["series", "Serie", a.series], ["collection", "Collezione", a.collection], ["loc", "Luogo di conservazione", a.loc]].filter((r) => fieldOn(s, r[0], k) && r[2]);
  const hidden = s.fields.filter((f) => !f[k]).map((f) => f.l);
  return <div className="asv">
    <div className="asv-n">{who === "public" ? blocked ? "Quest'opera non è nel catalogo pubblico: un visitatore non la vede." : `Così appare su ${s.catalogue.url}` : blocked ? "Nessun collezionista collegato: nessuno vede questa vista." : `Così la vede ${own.name} nel suo portale`}</div>
    <div className={"asv-c" + (blocked ? " off" : "")}>
      <div className="asv-i"><Art a={a} /></div>
      <div><h2 className="asv-t">{a.title}</h2><div className="mut" style={{ fontSize: 17, marginBottom: 16 }}>{a.year}</div>
        <dl className="pdl">{rows.map(([kk, l, v]) => <React.Fragment key={kk}><dt>{l}</dt><dd>{v}</dd></React.Fragment>)}</dl>
        {fieldOn(s, "exhibitions", k) && a.exhibitions.length > 0 && <div className="psec"><h4>Mostre</h4>{a.exhibitions.map((id) => {const x = byId(s.exhibitions, id);return <p key={id}>{x.title}, {x.venue}, {x.city}, {(x.from || "").slice(0, 4)}</p>;})}</div>}
        {fieldOn(s, "provenance", k) && a.provenance.filter((p) => who === "collector" || p.show !== "hidden").length > 0 && <div className="psec"><h4>Provenienza</h4>{a.provenance.filter((p) => who === "collector" || p.show !== "hidden").map((p, i) => <p key={i}>{who === "public" && p.show === "anon" ? "Collezione privata" : p.who}, {p.when}</p>)}</div>}
        {a.docs.filter((x) => who === "collector" ? x.vis !== "archive" : x.vis === "public").length > 0 && <div className="psec"><h4>Documenti e contenuti</h4>{a.docs.filter((x) => who === "collector" ? x.vis !== "archive" : x.vis === "public").map((x) => <p key={x.id}>{MT[x.type || "doc"][1]} · {x.label}</p>)}</div>}
        {s.modules.auth && c && (who === "collector" || c.public) && <div className="pcert"><Ic.seal /><div><b>Autentica digitale emessa dall'{s.archive.name}</b><span className="mono">{c.id}</span></div></div>}
      </div>
    </div>
    <div className="asv-h"><Ic.lock /> Non visibile in questa vista: {hidden.join(", ")}{who === "public" ? ", proprietari, documenti riservati" : ""}.</div>
  </div>;
}

Object.assign(window, { Overview, Works, Work, AsView, VisDots });