// Certify Unified — store, helpers, primitives, archive shell.
const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;
const KEY = "certify-unified-v5" + (window.CU_TENANT && window.CU_TENANT !== "angeli" ? "-" + window.CU_TENANT + (window.CU_TENANT_REV || "") : "");
const Ctx = createContext(null);const useC = () => useContext(Ctx);
const clone = (x) => JSON.parse(JSON.stringify(x));
const now = () => {const d = new Date();return d.toLocaleDateString("it-IT") + " · " + d.toLocaleTimeString("it-IT", { hour: "2-digit", minute: "2-digit" });};
const today = () => new Date().toLocaleDateString("it-IT");
async function sha(o) {const b = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(o)));return [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");}
const byId = (l, id) => l.find((x) => x.id === id);
const certOf = (s, aid) => s.certs.find((c) => c.artworkId === aid && c.status === "issued");
const fieldOn = (s, k, who) => {const f = s.fields.find((x) => x.k === k);return f ? f[who] : false;};
const snapOf = (s, a) => ({ archive: s.archive.name, artist: s.archive.artist, certifyId: a.certifyId, catNo: a.catNo, title: a.title, year: a.year, medium: a.medium, dims: a.dims });
const drift = (s, a) => {const c = certOf(s, a.id);return c ? JSON.stringify(c.snapshot) !== JSON.stringify(snapOf(s, a)) : false;};
function log(n, e) {n.events.unshift({ at: now(), who: (window.CU_SEED.archive.signatory || "Archivio"), ...e });}

function Provider({ children }) {
  const [s, setS] = useState(() => {try {const raw = localStorage.getItem(KEY);const x = raw && JSON.parse(raw.split('t50-04.jpg').join('t50-14.jpg'));if (x && x.v === window.CU_SEED.v) { ["crText", "crTitle"].forEach((f) => { if (x.archive && x.archive[f] === undefined && window.CU_SEED.archive[f] !== undefined) x.archive[f] = window.CU_SEED.archive[f]; }); if (!x.requests) x.requests = clone(window.CU_SEED.requests || []); x.requests.forEach((r) => { const sr = (window.CU_SEED.requests || []).find((q) => q.id === r.id); if (sr && (!r.photos || !Object.keys(r.photos).length)) r.photos = clone(sr.photos); }); if (!x.reqConfig) x.reqConfig = clone(window.CU_SEED.reqConfig); return x; }} catch (e) {}return clone(window.CU_SEED);});
  const [t, setT] = useState(null);
  useEffect(() => {try {localStorage.setItem(KEY, JSON.stringify(s));} catch (e) {}}, [s]);
  const api = useMemo(() => ({
    mut: (f) => setS((p) => {const n = clone(p);f(n);return n;}),
    go: (r) => {setS((p) => ({ ...p, route: { ...r } }));window.scrollTo(0, 0);},
    say: (m) => {setT(m);clearTimeout(window.__t);window.__t = setTimeout(() => setT(null), 2600);},
    firstRun: (on) => setS((p) => { if (on) { try { localStorage.setItem(KEY + "-bk", JSON.stringify(p)); } catch (e) {} return { ...p, firstRun: true, works: [], exhibitions: [], certs: [], transfers: [], requests: [], events: [], collectors: [], catalogue: { ...p.catalogue, published: false }, route: { v: "archive", p: "overview" } }; } let b = null; try { b = JSON.parse(localStorage.getItem(KEY + "-bk")); } catch (e) {} return b ? { ...b, firstRun: false, route: { v: "archive", p: "overview" } } : clone(window.CU_SEED); }),
    reset: () => {localStorage.removeItem(KEY);setS(clone(window.CU_SEED));}
  }), []);
  return <Ctx.Provider value={{ s, ...api }}>{children}{t && <div className="toast">{t}</div>}</Ctx.Provider>;
}

// ---- icons ----
const P = (d, w = 17) => () => <svg width={w} height={w} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
const Ic = {
  home: P(<path d="M4 11l8-7 8 7v8a1 1 0 0 1-1 1h-4v-6h-6v6H5a1 1 0 0 1-1-1z" />),
  works: P(<><rect x="4" y="4" width="7" height="7" rx="1.5" /><rect x="13" y="4" width="7" height="7" rx="1.5" /><rect x="4" y="13" width="7" height="7" rx="1.5" /><rect x="13" y="13" width="7" height="7" rx="1.5" /></>),
  globe: P(<><circle cx="12" cy="12" r="8" /><path d="M4 12h16M12 4c2.5 2.5 2.5 13.5 0 16M12 4c-2.5 2.5-2.5 13.5 0 16" /></>),
  seal: P(<><circle cx="12" cy="10" r="6" /><path d="M9 15l-1.5 6L12 19l4.5 2L15 15" /></>),
  users: P(<><circle cx="9" cy="9" r="3.5" /><path d="M3 20c0-3.5 3-5.5 6-5.5s6 2 6 5.5M15.5 6.2a3.2 3.2 0 0 1 0 6M17.5 14.6c2 .6 3.5 2.4 3.5 5.4" /></>),
  clock: P(<><circle cx="12" cy="12" r="8" /><path d="M12 8v4l3 2" /></>),
  cog: P(<><circle cx="12" cy="12" r="3" /><path d="M12 3v2.5M12 18.5V21M3 12h2.5M18.5 12H21M5.6 5.6l1.8 1.8M16.6 16.6l1.8 1.8M5.6 18.4l1.8-1.8M16.6 7.4l1.8-1.8" /></>),
  search: P(<><circle cx="11" cy="11" r="6.5" /><path d="M20 20l-4-4" /></>, 15),
  plus: P(<path d="M12 5v14M5 12h14" />, 15), x: P(<path d="M6 6l12 12M18 6L6 18" />, 15), chev: P(<path d="M9 6l6 6-6 6" />, 14), back: P(<path d="M15 6l-6 6 6 6" />, 15),
  lock: P(<><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></>, 14),
  key: P(<><circle cx="8" cy="15" r="3.5" /><path d="M10.5 12.5L19 4M16 7l2 2" /></>, 14),
  pub: P(<><circle cx="12" cy="12" r="8" /><path d="M4 12h16M12 4c2.5 2.5 2.5 13.5 0 16" /></>, 14),
  check: P(<path d="M5 12l5 5L20 7" />, 14), up: P(<path d="M12 16V5M7 10l5-5 5 5M5 16v3h14v-3" />, 15),
  list: P(<path d="M9 7h11M9 12h11M9 17h11M4.5 7h.01M4.5 12h.01M4.5 17h.01" />, 15), grid: P(<><rect x="4" y="4" width="7" height="7" rx="1.5" /><rect x="13" y="4" width="7" height="7" rx="1.5" /><rect x="4" y="13" width="7" height="7" rx="1.5" /><rect x="13" y="13" width="7" height="7" rx="1.5" /></>, 15),
  frame: P(<><rect x="4" y="5" width="16" height="14" rx="1.5" /><path d="M7 16l3.5-4 3 3 2-2 2.5 3" /></>),
  box: P(<><path d="M4 8l8-4 8 4v8l-8 4-8-4z" /><path d="M4 8l8 4 8-4M12 12v8" /></>),
  qr: P(<><rect x="4" y="4" width="6" height="6" /><rect x="14" y="4" width="6" height="6" /><rect x="4" y="14" width="6" height="6" /><path d="M14 14h2v2h-2zM18 18h2v2h-2zM14 18h2M18 14h2" /></>, 15)
};
const Mark = ({ s = 22 }) => <svg width={s} height={s} viewBox="0 0 100 100" fill="none"><path d="M77.1 66.96 A 32 32 0 1 1 77.1 33.04" stroke="currentColor" strokeWidth="20" /><rect x="41" y="41" width="18" height="18" fill="currentColor" /></svg>;

// ---- primitives ----
function Art({ a, label = true, r = 10 }) {
  if (a.img) return <div className="art" style={{ borderRadius: r, background: "#efebe2" }}><img src={a.img} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} /></div>;
  const h = a.hue;
  return <div className="art" style={{ borderRadius: r, background: `hsl(${h} 18% 86%)` }}>
    <i style={{ background: `hsl(${h} 32% 52%)`, left: `${12 + h % 30}%`, top: `${14 + h % 20}%`, width: `${38 + h % 25}%`, height: `${40 + h % 20}%` }}></i>
    <i style={{ background: `hsl(${(h + 40) % 360} 22% 30%)`, left: `${40 + h % 18}%`, top: `${48 + h % 14}%`, width: "28%", height: "22%" }}></i>
    {label && <span>Segnaposto</span>}
  </div>;
}
const Pill = ({ k = "", children }) => <span className={"pill " + k}>{children}</span>;
const Btn = ({ k = "", children, ...p }) => <button className={"btn " + k} {...p}>{children}</button>;
function Modal({ title, onClose, children, foot, w = 560 }) {
  useEffect(() => {const f = (e) => e.key === "Escape" && onClose();window.addEventListener("keydown", f);return () => window.removeEventListener("keydown", f);}, []);
  return <div className="ov" onClick={onClose}><div className="modal" style={{ width: w }} onClick={(e) => e.stopPropagation()}>
    <div className="m-h"><h3>{title}</h3><button className="ib" onClick={onClose} aria-label="Chiudi"><Ic.x /></button></div>
    <div className="m-b">{children}</div>{foot && <div className="m-f">{foot}</div>}</div></div>;
}
function Tg({ on, onClick, label }) {return <button className={"tg" + (on ? " on" : "")} onClick={onClick}><i></i>{label && <span>{label}</span>}</button>;}
const PubPill = ({ a }) => a.pub === "published" ? <Pill k="ok">Nel catalogo</Pill> : a.pub === "review" ? <Pill k="warn">In revisione</Pill> : <Pill>Bozza</Pill>;
function AuthPill({ s, a }) {
  if (!s.modules.auth) return null;const c = certOf(s, a.id);
  if (!c) {const old = s.certs.find((x) => x.artworkId === a.id);return old ? <Pill k="bad">{old.status === "revoked" ? "Autentica revocata" : "Sostituita"}</Pill> : <Pill k="lt">Non autenticata</Pill>;}
  return <Pill k="bx">Autentica {c.id.slice(-6)}</Pill>;
}
const PH = ({ k, t, sub, right }) => <div className="ph"><div>{k && <div className="ph-k">{k}</div>}<h1>{t}</h1>{sub && <p>{sub}</p>}</div>{right && <div className="row">{right}</div>}</div>;

// ---- archive shell ----

// ---- "Novità" popup: shown once per release, reopenable from the user menu ----
const WN_VER = "2026-11-scheda-opera";
const WN_CSS = `.wn-ov{position:fixed;inset:0;z-index:300;background:rgba(20,20,22,.28);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);display:grid;place-items:center;padding:24px;animation:wnf .25s ease}
.wn{width:min(760px,100%);max-height:calc(100vh - 48px);overflow:auto;background:#fff;border-radius:22px;box-shadow:0 30px 90px rgba(0,0,0,.22);display:flex;flex-direction:column}
.wn-h{padding:26px 30px 0}.wn-k{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:#611B26;background:#f3e2e4;border-radius:999px;padding:4px 10px}
.wn-h h2{font-size:26px;font-weight:600;letter-spacing:-.02em;margin:12px 0 6px}.wn-h p{margin:0;font-size:14.5px;color:#6e6e73;line-height:1.5;max-width:560px}
.wn-pv{margin:20px 30px 0;border-radius:16px;background:#f5f5f7;height:300px;position:relative;overflow:hidden}
.wn-tabs{display:flex;gap:6px;padding:16px 30px 0;flex-wrap:wrap}.wn-tabs button{border:0;background:none;font:inherit;font-size:13px;color:#86868b;padding:7px 12px;border-radius:999px;cursor:pointer}.wn-tabs button.on{background:#1d1d1f;color:#fff}
.wn-tx{padding:14px 30px 0;min-height:66px}.wn-tx b{display:block;font-size:15.5px;font-weight:600;margin-bottom:4px}.wn-tx span{font-size:14px;color:#6e6e73;line-height:1.5}
.wn-f{display:flex;align-items:center;gap:10px;padding:20px 30px 24px;margin-top:6px}.wn-f .wn-dots{display:flex;gap:6px;margin-right:auto}.wn-dots i{width:6px;height:6px;border-radius:50%;background:#d1d1d6}.wn-dots i.on{background:#1d1d1f}
.wn-c{position:absolute;inset:22px;background:#fff;border-radius:12px;box-shadow:0 8px 30px rgba(0,0,0,.08);padding:18px 20px;display:flex;gap:18px;animation:wnu .35s ease}
.wn-img{width:150px;flex:0 0 150px;border-radius:8px;overflow:hidden;position:relative;background:#ececee}
.wn-fl{flex:1;display:flex;flex-direction:column;gap:10px;min-width:0}.wn-l{font-size:10.5px;color:#86868b;margin-bottom:3px}.wn-l i{font-style:normal;color:#b3261e}
.wn-in{height:28px;border-radius:7px;box-shadow:inset 0 0 0 1px #e5e5ea;display:flex;align-items:center;padding:0 10px;font-size:12px;color:#1d1d1f}
.wn-in.ph{color:#c7c7cc}.wn-2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.wn-chips{display:flex;flex-wrap:wrap;gap:7px}.wn-chip{font-size:11.5px;padding:6px 11px;border-radius:999px;box-shadow:inset 0 0 0 1px #e5e5ea;color:#1d1d1f;display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
.wn-chip.on{background:#1d1d1f;color:#fff;box-shadow:none}.wn-chip.dot::after{content:"";width:6px;height:6px;border-radius:50%;background:#e0a100}
.wn-panel{margin-top:4px;border-radius:10px;background:#fafafa;padding:12px 14px;display:flex;flex-direction:column;gap:8px}
.wn-g{display:flex;flex-direction:column;gap:6px}.wn-gh{display:flex;justify-content:space-between;font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:#86868b}.wn-gh em{font-style:normal;font-weight:400;text-transform:none;letter-spacing:0;color:#a1a1a6}
.wn-th{display:flex;gap:6px}.wn-th span{width:44px;height:44px;border-radius:6px;background:#ececee;display:grid;place-items:end center;font-size:9px;color:#86868b;padding-bottom:3px;box-sizing:border-box;position:relative;overflow:hidden}
.wn-th span.add{background:none;box-shadow:inset 0 0 0 1px #d1d1d6;place-items:center;font-size:16px;color:#a1a1a6;padding:0}
.wn-dd{border-radius:9px;box-shadow:0 8px 24px rgba(0,0,0,.1);background:#fff;overflow:hidden;font-size:12px}.wn-dd div{padding:8px 12px;border-top:1px solid #f2f2f4}.wn-dd div:first-child{border-top:0}.wn-dd .new{color:#611B26;font-weight:500}
@keyframes wnf{from{opacity:0}to{opacity:1}}@keyframes wnu{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
@media (max-width:640px){.wn-img{display:none}.wn-pv{height:340px}}`;
function WhatsNew({ force, onClose }) {
  const { s, go } = useC(); const [open, setOpen] = React.useState(!!force); const [k, setK] = React.useState(0);
  React.useEffect(() => { if (force) return; let seen = null; try { seen = localStorage.getItem("certify-whatsnew"); } catch (e) {}
    if (seen === WN_VER) return; const t = setTimeout(() => { if (!document.querySelector('[class^="gd-"],[class*=" gd-"]')) setOpen(true); }, 900); return () => clearTimeout(t); }, []);
  if (!open) return null;
  const close = () => { try { localStorage.setItem("certify-whatsnew", WN_VER); } catch (e) {} setOpen(false); onClose && onClose(); };
  const a = (s.works || []).find((w) => w.img) || (s.works || [])[0];
  const P = [
    ["Solo l'essenziale, subito", "Bastano titolo e datazione per salvare un'opera. Tecnica, dimensioni e numero d'archivio sono a portata di mano, il resto quando serve.",
      <div className="wn-c"><div className="wn-img">{a && <Art a={a} label={false} r={0} />}</div><div className="wn-fl">
        <div><div className="wn-l">Titolo <i>*</i></div><div className="wn-in">{a ? a.title : "Senza titolo"}</div></div>
        <div className="wn-2"><div><div className="wn-l">Datazione <i>*</i></div><div className="wn-in">{a ? (a.yearLabel || a.year) : "1964"}</div></div><div><div className="wn-l">N. archivio</div><div className="wn-in ph">In corso di archiviazione</div></div></div>
        <div><div className="wn-l">Tecnica e supporto</div><div className="wn-in">{a && a.medium ? a.medium : "Olio su tela"}</div></div>
        <div className="wn-2"><div><div className="wn-l">Dimensioni</div><div className="wn-in">{a && a.dims ? a.dims : "100 × 80 cm"}</div></div><div><div className="wn-l">Categoria</div><div className="wn-in">{a && a.category ? a.category : "Opere su tela"}</div></div></div></div></div>],
    ["Aggiungi i dettagli quando servono", "Serie, iscrizioni, provenienza, note, mostre e documenti si aprono con un clic. Un puntino giallo indica le parti già compilate.",
      <div className="wn-c" style={{ flexDirection: "column" }}><div className="wn-l" style={{ fontSize: 12, color: "#1d1d1f", fontWeight: 500 }}>Aggiungi dettagli</div>
        <div className="wn-chips"><span className="wn-chip">Serie ed edizione</span><span className="wn-chip on">Iscrizioni e firme</span><span className="wn-chip dot">Storia e provenienza</span><span className="wn-chip">Note</span><span className="wn-chip">Mostre, collezioni e pubblicazioni</span><span className="wn-chip">Documenti</span></div>
        <div className="wn-panel"><div className="wn-gh">Iscrizioni e firme</div><div className="wn-2"><div className="wn-in">Firma · Retro</div><div className="wn-in">«Angeli 65»</div></div><div className="wn-in ph">+ Aggiungi iscrizione</div></div></div>],
    ["Immagini ordinate per gruppi", "Fronte, retro e firma dell'opera, poi studi, cataloghi correlati e altro materiale. Ogni gruppo compare così anche nel catalogo ragionato.",
      <div className="wn-c" style={{ flexDirection: "column", gap: 12 }}>{[["Opera", "Fronte · Retro · Firma", ["Fronte", "Retro", "Firma"]], ["Studi", "Bozzetti e disegni", ["Studio"]], ["Cataloghi correlati", "Pubblicazioni che citano l'opera", ["1965"]], ["Altro", "Foto d'archivio, allestimenti", []]].map(([t, d, th]) => <div key={t} className="wn-g"><div className="wn-gh">{t}<em>{d}</em></div><div className="wn-th">{th.map((x, i) => <span key={i}>{i === 0 && a && t === "Opera" ? <Art a={a} label={false} r={0} /> : null}{!(i === 0 && a && t === "Opera") && x}</span>)}<span className="add">+</span></div></div>)}</div>],
    ["Mostre collegate in un passaggio", "Scegli la mostra da un elenco o creane una nuova direttamente dalla scheda: comparirà subito anche nella sezione Mostre.",
      <div className="wn-c" style={{ flexDirection: "column" }}><div><div className="wn-l">Mostre</div><div className="wn-in" style={{ justifyContent: "space-between" }}>Cerca o scegli una mostra<span style={{ color: "#a1a1a6" }}>▾</span></div></div>
        <div className="wn-dd"><div>XXXII Biennale di Venezia · 1964</div><div>Roma Pop City 60-67 · MACRO, 2016</div><div>Personale · Galleria La Tartaruga, 1963</div><div className="new">+ Crea nuova mostra</div></div>
        <div className="wn-l" style={{ marginTop: 4 }}>La bozza si salva automaticamente mentre scrivi.</div></div>],
  ];
  const cur = P[k];
  return <div className="wn-ov" onClick={close}><style>{WN_CSS}</style><div className="wn" role="dialog" aria-label="Novità" onClick={(e) => e.stopPropagation()}>
    <div className="wn-h"><span className="wn-k">Novità · Novembre 2026</span><h2>La nuova scheda opera</h2><p>Abbiamo ridisegnato la creazione di un'opera: più semplice da compilare, più ordinata da consultare. Nessun dato esistente è stato modificato.</p></div>
    <div className="wn-tabs">{P.map((p, i) => <button key={i} className={i === k ? "on" : ""} onClick={() => setK(i)}>{p[0]}</button>)}</div>
    <div className="wn-pv" key={k}>{cur[2]}</div>
    <div className="wn-tx"><b>{cur[0]}</b><span>{cur[1]}</span></div>
    <div className="wn-f"><div className="wn-dots">{P.map((_, i) => <i key={i} className={i === k ? "on" : ""}></i>)}</div>
      {k < P.length - 1 ? <><Btn onClick={close}>Più tardi</Btn><Btn k="dark" onClick={() => setK(k + 1)}>Avanti</Btn></>
        : <><Btn onClick={close}>Chiudi</Btn><Btn k="dark" onClick={() => { close(); go({ v: "archive", p: "new" }); }}>Prova la nuova scheda</Btn></>}</div>
  </div></div>;
}

function Shell({ children }) {
  const { s, go } = useC(); const p = s.route.p; const M = s.modules;
  const [col, setCol] = useState(() => localStorage.getItem("cu-side") === "1"); const [um, setUm] = useState(false); const [wn, setWn] = React.useState(false); const [k, setK] = useState(false);
  useEffect(() => { const f = (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setK(true); } }; window.addEventListener("keydown", f); return () => window.removeEventListener("keydown", f); }, []);
  const nNew = (s.requests || []).filter((r) => r.status === "new").length; const nTr = s.transfers.filter((t) => t.status === "requested").length;
  const SEC = [
    ["Panoramica", [["overview", "Dashboard", Ic.home, true]]],
    ["Archivio", [["works", "Opere", Ic.works, true], ["exhibitions", "Mostre", Ic.frame, true], ["collections", "Collezioni", Ic.box, true]]],
    ["Autenticazione", [["requests", "Richieste", Ic.clock, true, nNew], ["certs", "Autentiche", Ic.seal, M.auth], ["seguito", "Diritto di seguito", Ic.clock, true]]],
    ["Pubblicazione", [["catalogue", "Catalogo pubblico", Ic.globe, M.catalogue]]],
    ["Gestione", [["collectors", "Collezionisti", Ic.users, M.auth, nTr], ["settings", "Impostazioni", Ic.cog, true], ["about", "Informazioni", Ic.globe, true]]],
  ];
  const on = (x) => p === x || x === "works" && (p === "work" || p === "new" || p === "import") || x === "requests" && p === "request" || x === "certs" && (p === "cert" || p === "newauth" || p === "newauthx" || p === "fee");
  const crumb = { work: ["Opere", "works"], new: ["Opere", "works"], import: ["Opere", "works"], request: ["Richieste", "requests"], cert: ["Autentiche", "certs"], newauth: ["Autentiche", "certs"], newauthx: ["Autentiche", "certs"], fee: ["Autentiche", "certs"], activity: ["Dashboard", "overview"] }[p];
  return <div className={"app" + (col ? " col" : "")}>
    <aside className="side">
      <div className="brand"><b>CERTIFY</b><button className="sd-c" onClick={() => { setCol(!col); localStorage.setItem("cu-side", col ? "0" : "1"); }} aria-label="Comprimi barra laterale"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="5" width="16" height="14" rx="2"/><path d="M10 5v14"/></svg></button></div>
      <div className="org"><span className={"org-m" + (s.archive.logo ? " lg" : "")}>{s.archive.logo ? <img src={s.archive.logo} alt={s.archive.name} /> : <b style={{ fontSize: 12, letterSpacing: ".04em" }}>{s.archive.mark}</b>}</span><div><b>{s.archive.name}</b><span>{!M.auth ? "Solo catalogo" : "Archivio completo"}</span></div></div>
      
      {SEC.map(([t, L]) => { const vis = L.filter((x) => x[3]); if (!vis.length) return null; return <div key={t} className="sd-s"><div className="sd-t">{t}</div>{vis.map(([x, l, I, , n]) => <button key={x} title={l} className={"nav" + (on(x) ? " on" : "")} onClick={() => go({ v: "archive", p: x })}><I /><span>{l}</span>{n > 0 && <i>{n}</i>}</button>)}{t === "Autenticazione" && !M.auth && <button className="nav dim" onClick={() => go({ v: "archive", p: "settings" })}><Ic.seal /><span>Autentiche</span><em>Attiva</em></button>}</div>; })}
      
      <div className="sf-w">{um && <div className="um" onClick={() => setUm(false)}><button onClick={() => go({ v: "archive", p: "settings", sec: "archive" })}>Impostazioni</button><button onClick={() => go({ v: "archive", p: "settings", sec: "billing" })}>Abbonamento e fatturazione</button><button onClick={() => go({ v: "archive", p: "settings", sec: "team" })}>Team e permessi</button><button onClick={() => setWn(true)}>Novità</button><hr/><button className="mut">Esci</button></div>}<button className="side-f" onClick={() => setUm(!um)}><span className="av">{s.archive.initials || "MA"}</span><div><b>{s.archive.signatory}</b><span>{s.archive.role}</span></div><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M7 15l5-5 5 5"/></svg></button></div>
    </aside>
    <main className="main"><div className="tbar"><div className="crumb">{crumb && <><button onClick={() => go({ v: "archive", p: crumb[1] })}>{crumb[0]}</button><span>/</span><b>{p === "work" ? (byId(s.works, s.route.id) || {}).title : p === "request" ? "Richiesta" : p === "new" ? "Nuova opera" : p === "import" ? "Importa" : p === "newauth" ? "Nuova autentica" : p === "cert" ? s.route.id : "Attività"}</b></>}</div><button className="tk" onClick={() => setK(true)} aria-label="Cerca"><Ic.search /><span>Cerca</span><kbd>⌘K</kbd></button></div>{children}</main>
    {k && <Spot onClose={() => setK(false)} />}
    <WhatsNew />{wn && <WhatsNew force onClose={() => setWn(false)} />}
  </div>;
}
function Spot({ onClose }) {
  const { s, go } = useC(); const [q, setQ] = useState(""); const t = q.trim().toLowerCase();
  useEffect(() => { const f = (e) => e.key === "Escape" && onClose(); window.addEventListener("keydown", f); return () => window.removeEventListener("keydown", f); }, []);
  const G = !t ? [] : [
    ["Opere", s.works.filter((a) => (a.title + a.catNo + a.year + a.certifyId).toLowerCase().includes(t)).slice(0, 6).map((a) => [a.title, `${a.yearLabel || a.year} · ${a.catNo}`, { v: "archive", p: "work", id: a.id }, a])],
    ["Mostre", s.exhibitions.filter((x) => (x.title + x.venue + x.city).toLowerCase().includes(t)).slice(0, 4).map((x) => [x.title, `${x.venue}, ${x.city}`, { v: "archive", p: "exhibitions", id: x.id }])],
    ["Contatti", s.collectors.filter((c) => (c.name + c.email).toLowerCase().includes(t)).slice(0, 4).map((c) => [c.name, c.email, { v: "archive", p: "collectors", id: c.id }])],
    ["Autentiche", s.certs.filter((c) => (c.id + c.snapshot.title).toLowerCase().includes(t)).slice(0, 4).map((c) => [c.id, c.snapshot.title, { v: "archive", p: "work", id: c.artworkId, tab: "auth" }])],
    ["Richieste", (s.requests || []).filter((r) => (r.id + r.title + r.name).toLowerCase().includes(t)).slice(0, 4).map((r) => [r.title, `${r.name} · ${r.id}`, { v: "archive", p: "request", id: r.id }])],
  ].filter((g) => g[1].length);
  const pick = (r) => { go(r); onClose(); };
  return <div className="spot-ov" onClick={onClose}><div className="spot" onClick={(e) => e.stopPropagation()}>
    <label className="spot-i"><Ic.search /><input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Cerca opere, numeri di catalogo, mostre, collezionisti, autentiche…" onKeyDown={(e) => { if (e.key === "Enter" && G[0]) pick(G[0][1][0][2]); }} /><kbd>esc</kbd></label>
    <div className="spot-r">{!t ? <div className="spot-h">Inizia a scrivere per cercare in tutto l'archivio.</div> : G.length ? G.map(([g, L]) => <div key={g}><div className="spot-g">{g}</div>{L.map(([a, b, r, w], i) => <button key={i} onClick={() => pick(r)}>{w ? <span className="spot-th"><Art a={w} label={false} r={4} /></span> : <span className="spot-th e"></span>}<div><b>{a}</b><span>{b}</span></div></button>)}</div>) : <div className="spot-h">Nessun risultato per «{q}».</div>}</div>
  </div></div>;
}


Object.assign(window, { Spot, Provider, useC, clone, now, today, sha, byId, certOf, fieldOn, snapOf, drift, log, Ic, Mark, Art, Pill, Btn, Modal, Tg, PubPill, AuthPill, PH, Shell });