// 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 ----
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 [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><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)} />}
  </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 });