// Certify Artists — store, helpers, shell. Reuses Certify's shared UI from cu-core.jsx (window.Ic, Art, Pill, Btn, Modal, Tg).
const CIc = window.Ic, CArt = window.Art, CPill = window.Pill, CBtn = window.Btn, CModal = window.Modal, CTg = window.Tg;
const caKEY = window.CA_KEY || "certify-artists-v1"; const CaCtx = React.createContext(null); const useCa = () => React.useContext(CaCtx);
const caClone = (x) => JSON.parse(JSON.stringify(x));
const caToday = () => new Date().toISOString().slice(0, 10);
const caFmt = (d) => d ? d.slice(8, 10) + "." + d.slice(5, 7) + "." + d.slice(0, 4) : "—";
const caEur = (n) => n == null || n === "" ? "—" : "€ " + Number(n).toLocaleString("it-IT");
const caDays = (d) => Math.round((new Date(d) - new Date(caToday())) / 864e5);
const caById = (L, id) => L.find((x) => x.id === id);
const caLog = (n, text, wid) => n.events.unshift({ at: new Date().toLocaleDateString("it-IT") + " · " + new Date().toLocaleTimeString("it-IT", { hour: "2-digit", minute: "2-digit" }), text, wid: wid || null });
const CA_REQ = [["title", "Titolo"], ["year", "Anno"], ["medium", "Tecnica"], ["dims", "Dimensioni"], ["inv", "N. inventario"]];
const caMissing = (a) => CA_REQ.filter(([k]) => !a[k]).map(([, l]) => l);
const caDocsOf = (s, a) => s.docs.filter((d) => d.wid === a.id);
const caCertOf = (s, a) => s.certs.find((c) => c.wid === a.id && c.status === "issued") || s.certs.find((c) => c.wid === a.id && (c.status === "await" || c.status === "draft"));
const caCompl = (s, a) => { const c = [a.title, a.year, a.medium, a.dims, a.inv, a.desc, caDocsOf(s, a).length || caCertOf(s, a)]; return Math.round(c.filter(Boolean).length / c.length * 100); };
const caLoanOf = (s, a) => s.loans.find((l) => l.wid === a.id && !l.back);
const caExhOf = (s, a) => s.exhibitions.filter((e) => e.works.includes(a.id));
const CA_ROLES = ["Artista", "Studio manager", "Assistente", "Sola lettura"];
const CA_PERMS = [["view", "Consultare opere e documenti", [1, 1, 1, 1]], ["edit", "Aggiungere e modificare le opere", [1, 1, 1, 0]], ["ops", "Ubicazioni, prestiti e mostre", [1, 1, 1, 0]], ["crm", "Contatti e vendite", [1, 1, 0, 0]], ["prep", "Preparare un certificato", [1, 1, 0, 0]], ["sign", "Firmare ed emettere certificati", [1, 0, 0, 0]], ["admin", "Team e impostazioni", [1, 0, 0, 0]]];
const caCan = (s, k) => { if (k === "sign" && s.viewAs === "Studio manager" && s.delegate) return true; const p = CA_PERMS.find((x) => x[0] === k); return !!(p && p[2][CA_ROLES.indexOf(s.viewAs)]); };
const CA_LOC = ["Studio", "Galleria", "Collezionista", "Museo", "Deposito", "Mostra", "In transito"];
const CA_AV = window.CA_AV_OVERRIDE || ["Disponibile", "Riservata", "Venduta", "Non in vendita"];
const CA_CATS = window.CA_CATS_OVERRIDE || ["Performance", "Sculture", "Installazioni", "Opere a parete", "Fotografia e video", "Opere su carta"];
const caAvK = (v) => ({ Disponibile: "ok", Riservata: "warn", "In conto vendita": "warn", "In produzione": "lt" })[v] || "lt";
const CA_CS = { issued: ["Emesso", "ok"], await: ["Da firmare", "warn"], draft: ["Bozza", "lt"], replaced: ["Sostituito", "lt"], revoked: ["Revocato", "bad"] };
const CaCertPill = ({ s, a }) => { const c = caCertOf(s, a); return c ? <CPill k={CA_CS[c.status][1]}>{CA_CS[c.status][0]}</CPill> : <CPill k="lt">Senza certificato</CPill>; };
const CaI = {
  pin: () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 21s-6-5.5-6-11a6 6 0 0 1 12 0c0 5.5-6 11-6 11z" /><circle cx="12" cy="10" r="2.2" /></svg>,
  euro: () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M17 6.5A6.5 6.5 0 1 0 17 17.5" /><path d="M5 10h8M5 14h8" /></svg>,
  doc: () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /><path d="M14 3v5h5" /></svg>,
  alert: () => <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="#e0a100" strokeWidth="2"><circle cx="12" cy="12" r="9" /><path d="M12 7.5v5.5M12 16.5h.01" /></svg>,
};
const CaF = ({ l, req, children }) => <label className="ca-f"><span>{l}{req && <i className="req">*</i>}</span>{children}</label>;

function CaProvider({ children }) {
  const [s, setS] = React.useState(() => { try { const x = JSON.parse(localStorage.getItem(caKEY)); if (x && x.v === 2) { (window.CA_SEED.works || []).forEach((w) => { if (!w.img) return; const i = (x.works || []).findIndex((o) => o.id === w.id); if (i < 0) { x.works.unshift(caClone(w)); return; } let o = x.works[i]; if (!o.img) o = x.works[i] = Object.assign({}, o, caClone(w)); if (Array.isArray(o.gallery)) o.gallery = ""; if (w.photos) { const g = o.photos || []; o.photos = g.concat(caClone(w.photos.filter((p) => !g.some((q) => q.src === p.src)))); } }); return x; } } catch (e) {} return caClone(window.CA_SEED); });
  const [msg, setMsg] = React.useState(null);
  React.useEffect(() => { localStorage.setItem(caKEY, JSON.stringify(s)); }, [s]);
  const api = React.useMemo(() => ({
    mut: (fn) => setS((p) => { const n = caClone(p); fn(n); return n; }),
    go: (r) => { setS((p) => ({ ...p, route: r })); const m = document.querySelector(".main"); if (m) m.scrollTop = 0; window.scrollTo(0, 0); },
    say: (m) => { setMsg(m); clearTimeout(window.__caT); window.__caT = setTimeout(() => setMsg(null), 2400); },
    reset: () => { localStorage.removeItem(caKEY); setS(caClone(window.CA_SEED)); },
  }), []);
  return <CaCtx.Provider value={{ s, ...api }}>{children}{msg && <div className="ca-toast">{msg}</div>}</CaCtx.Provider>;
}

function CaMove({ ids, onClose }) {
  const { s, mut, say } = useCa(); const [w, setW] = React.useState(ids && ids.length ? ids : []); const [f, setF] = React.useState({ t: "Studio", d: "Studio, " + ((window.CA_SEED.studio || {}).city || "Roma"), at: caToday(), note: "" });
  const save = () => { mut((n) => { w.forEach((id) => { const a = caById(n.works, id); a.loc = { t: f.t, d: f.d }; a.locHist.push({ ...f }); caLog(n, "Ubicazione aggiornata: " + a.title + " · " + f.d, id); }); }); say(w.length === 1 ? "Ubicazione aggiornata" : w.length + " opere aggiornate"); onClose(); };
  return <CModal title="Aggiorna ubicazione" onClose={onClose} foot={<><CBtn onClick={onClose}>Annulla</CBtn><CBtn k="dark" disabled={!w.length || !f.d} onClick={save}>Salva</CBtn></>}>
    {!(ids && ids.length) && <CaF l="Opera" req><select value={w[0] || ""} onChange={(e) => setW(e.target.value ? [e.target.value] : [])}><option value="">Scegli un'opera…</option>{s.works.map((a) => <option key={a.id} value={a.id}>{a.title} · {a.inv}</option>)}</select></CaF>}
    {ids && ids.length > 1 && <p className="mut" style={{ marginTop: 0 }}>{ids.length} opere selezionate</p>}
    <div className="ca-g2"><CaF l="Tipo di ubicazione"><select value={f.t} onChange={(e) => setF({ ...f, t: e.target.value })}>{CA_LOC.map((x) => <option key={x}>{x}</option>)}</select></CaF>
      <CaF l="Luogo" req><input value={f.d} onChange={(e) => setF({ ...f, d: e.target.value })} placeholder="Es. Deposito" /></CaF>
      <CaF l="Data"><input type="date" value={f.at} onChange={(e) => setF({ ...f, at: e.target.value })} /></CaF>
      <CaF l="Nota"><input value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} placeholder="Facoltativa" /></CaF></div>
  </CModal>;
}

const caShrink = (file, max = 1400) => new Promise((res) => { const r = new FileReader(); r.onload = () => { const im = new Image(); im.onload = () => { const k = Math.min(1, max / Math.max(im.width, im.height)); const cv = document.createElement("canvas"); cv.width = im.width * k; cv.height = im.height * k; cv.getContext("2d").drawImage(im, 0, 0, cv.width, cv.height); res(cv.toDataURL("image/jpeg", 0.82)); }; im.src = r.result; }; r.readAsDataURL(file); });
function CaNewWork() {
  const { s, mut, go, say } = useCa(); const city = (window.CA_SEED.studio || {}).city || "Roma";
  const [drag, setDrag] = React.useState(false);
  const [f, setF] = React.useState({ img: "", title: "", year: String(new Date().getFullYear()), cat: CA_CATS[0], medium: "", dims: "", edition: "Opera unica", desc: "", lt: "Studio", ld: "Studio, " + city, cust: "", at: caToday(), auth: "later" });
  const up = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const pick = async (files) => { const x = files && files[0]; if (x && /^image\//.test(x.type)) up("img", await caShrink(x)); };
  const canSign = caCan(s, "prep") && caMod(s, "certs");
  const save = () => { const id = "aq-n" + Date.now().toString(36);
    mut((n) => { n.works.unshift({ id, inv: (n.studio.initials || "AQ") + "-" + f.year + "-" + String(n.works.length + 1).padStart(3, "0"), title: f.title, year: +f.year || f.year, cat: f.cat, medium: f.medium, dims: f.dims, edition: f.edition, img: f.img || undefined, avail: "Disponibile", loc: { t: f.lt, d: f.ld, cust: f.cust || undefined, updated: f.at }, locHist: [{ t: f.lt, d: f.ld, at: f.at, note: "Opera inserita" }], price: null, salePrice: null, gallery: "", desc: f.desc, pub: false, hue: Math.floor(Math.random() * 360), pubs: [], added: 1000 + n.works.length }); caLog(n, "Opera aggiunta all'inventario: " + f.title, id); });
    if (f.auth === "now" && canSign) { say("Opera aggiunta · prepara il certificato"); go({ p: "issue", wid: id }); } else { say("Opera aggiunta"); go({ p: "work", id }); } };
  const custOpts = s.contacts.filter((c) => f.lt === "Galleria" ? c.type === "Galleria" : f.lt === "Museo" || f.lt === "Mostra" ? ["Museo", "Istituzione", "Galleria"].includes(c.type) : f.lt === "Collezionista" ? c.type === "Collezionista" : true);
  const cancel = () => go({ p: "works" }); const valid = !!(f.title && f.year && f.ld);
  const H = ({ t, d }) => <div className="caw-h"><h2>{t}</h2>{d && <p>{d}</p>}</div>;
  return <div className="page caw-page">
    <div className="ca-ph"><div><h1>Nuova opera</h1><p className="mut">Compila i dati essenziali: il resto si completa dalla scheda in qualsiasi momento.</p></div>
      <div className="caw-act"><CBtn onClick={cancel}>Annulla</CBtn><CBtn k="dark" disabled={!valid} onClick={save}>{f.auth === "now" && canSign ? "Crea e prepara il certificato" : "Crea opera"}</CBtn></div></div>
    <div className="caw-lay">
      <aside className="caw-side">
        <label className={"caw-drop" + (drag ? " on" : "") + (f.img ? " has" : "")} onDragOver={(e) => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)} onDrop={(e) => { e.preventDefault(); setDrag(false); pick(e.dataTransfer.files); }}>
          <input type="file" accept="image/*" hidden onChange={(e) => pick(e.target.files)} />
          {f.img ? <><img src={f.img} alt="" /><span className="caw-ch">Cambia immagine</span></> : <><CIc.plus /><b>Immagine dell'opera</b><span className="mut">Trascina qui la foto o clicca per sceglierla</span></>}</label>
        <p className="mut sm">Retro, dettagli e firma si aggiungono dalla scheda dell'opera.</p>
      </aside>
      <div className="caw-main">
        <section className="card caw-sec"><H t="Dati dell'opera" />
          <CaF l="Titolo" req><input autoFocus value={f.title} onChange={(e) => up("title", e.target.value)} /></CaF>
          <div className="caw-g3"><CaF l="Anno" req><input value={f.year} onChange={(e) => up("year", e.target.value)} /></CaF>
            <CaF l="Categoria"><select value={f.cat} onChange={(e) => up("cat", e.target.value)}>{CA_CATS.map((x) => <option key={x}>{x}</option>)}</select></CaF>
            <CaF l="Edizione"><input value={f.edition} onChange={(e) => up("edition", e.target.value)} placeholder="Opera unica" /></CaF></div>
          <div className="ca-g2"><CaF l="Tecnica"><input value={f.medium} onChange={(e) => up("medium", e.target.value)} placeholder="Es. Silicone e olio su tela" /></CaF>
            <CaF l="Dimensioni"><input value={f.dims} onChange={(e) => up("dims", e.target.value)} placeholder="Es. 150 × 120 cm" /></CaF></div>
          <CaF l="Descrizione"><textarea className="ca-ta" value={f.desc} onChange={(e) => up("desc", e.target.value)} placeholder="Facoltativa" /></CaF></section>
        <section className="card caw-sec"><H t="Ubicazione" d="Dove si trova l'opera adesso. Lo storico delle ubicazioni parte da qui." />
          <div className="ca-g2"><CaF l="Tipo di ubicazione"><select value={f.lt} onChange={(e) => { const t = e.target.value; setF((p) => ({ ...p, lt: t, ld: t === "Studio" ? "Studio, " + city : t === "Deposito" ? "Deposito, " + city : "", cust: "" })); }}>{CA_LOC.map((x) => <option key={x}>{x}</option>)}</select></CaF>
            <CaF l="Luogo" req><input value={f.ld} onChange={(e) => up("ld", e.target.value)} placeholder="Es. Galleria, città" /></CaF>
            {!["Studio", "Deposito"].includes(f.lt) && <CaF l="Presso"><select value={f.cust} onChange={(e) => { const c = caById(s.contacts, e.target.value); setF((p) => ({ ...p, cust: e.target.value, ld: c && !p.ld ? (c.org || c.name) + (c.city ? ", " + c.city : "") : p.ld })); }}><option value="">Nessun contatto</option>{custOpts.map((c) => <option key={c.id} value={c.id}>{c.org && c.org !== c.name ? c.org : c.name}</option>)}</select></CaF>}
            <CaF l="Dal"><input type="date" value={f.at} onChange={(e) => up("at", e.target.value)} /></CaF></div></section>
        <section className="card caw-sec"><H t="Autentica" d="Il certificato usa il tuo modello di autentica." />
          <div className="caw-opt">{[["now", "Prepara subito il certificato", canSign ? "Dopo il salvataggio si apre l'emissione: verifica dati, anteprima, firma e invio al collezionista." : "Il tuo ruolo non può preparare certificati."], ["later", "Più tardi", "L'opera resta senza certificato. Puoi emetterlo dalla scheda quando vuoi."]].map(([k, l, d]) => <button key={k} disabled={k === "now" && !canSign} className={f.auth === k ? "on" : ""} onClick={() => up("auth", k)}><i></i><div><b>{l}</b><span>{d}</span></div></button>)}</div>
          {canSign && <button className="lnk" style={{ marginTop: 10 }} onClick={() => go({ p: "template" })}>Vedi il modello di autentica</button>}</section>
        <div className="caw-foot"><span className="mut sm">{valid ? "Pronta per essere salvata." : "Obbligatori: titolo, anno e luogo."}</span><div className="caw-act"><CBtn onClick={cancel}>Annulla</CBtn><CBtn k="dark" disabled={!valid} onClick={save}>{f.auth === "now" && canSign ? "Crea e prepara il certificato" : "Crea opera"}</CBtn></div></div>
      </div></div>
  </div>;
}

function CaSearch({ onClose }) {
  const { s, go } = useCa(); const [q, setQ] = React.useState(""); const t = q.trim().toLowerCase();
  React.useEffect(() => { const f = (e) => e.key === "Escape" && onClose(); window.addEventListener("keydown", f); return () => window.removeEventListener("keydown", f); }, []);
  const R = !t ? [] : [...s.works.filter((a) => (a.title + a.inv + a.year).toLowerCase().includes(t)).slice(0, 6).map((a) => ["Opera", a.title + " · " + a.year, { p: "work", id: a.id }]),
    ...s.certs.filter((c) => c.id.toLowerCase().includes(t)).slice(0, 3).map((c) => ["Certificato", c.id, { p: "cert", id: c.id }]),
    ...s.contacts.filter((c) => (c.name + c.org).toLowerCase().includes(t)).slice(0, 4).map((c) => ["Contatto", c.name + (c.org && c.org !== c.name ? " · " + c.org : ""), { p: "contact", id: c.id }]),
    ...s.exhibitions.filter((e) => (e.title + e.venue).toLowerCase().includes(t)).slice(0, 3).map((e) => ["Mostra", e.title + " · " + e.venue, { p: "exh", id: e.id }])];
  return <div className="ca-ov" onClick={onClose}><div className="ca-k" onClick={(e) => e.stopPropagation()}>
    <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Cerca opere, certificati, contatti, mostre…" />
    {R.map(([k, l, r], i) => <button key={i} onClick={() => { go(r); onClose(); }}><span>{k}</span><b>{l}</b></button>)}
    {t && !R.length && <div className="ca-empty">Nessun risultato.</div>}
  </div></div>;
}

function CaShell({ children }) {
  const { s, go, mut, reset } = useCa(); const p = s.route.p; const [um, setUm] = React.useState(false); const [k, setK] = React.useState(false);
  React.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 nAw = s.certs.filter((c) => c.status === "await").length; const crm = caCan(s, "crm");
  const SEC = window.CA_SECF ? window.CA_SECF(s, { nAw, crm }) : [["", [["dash", "Dashboard", CIc.home, true], ["works", "Opere", CIc.works, true]]],
    ["Autentiche", [["certs", "Certificati", CIc.seal, caMod(s, "certs"), nAw], ["template", "Modello di autentica", CaI.doc, caMod(s, "certs")]]],
    ["Archivio", [["locations", "Ubicazioni e collezioni", CaI.pin, true], ["exhibitions", "Mostre", CIc.frame, true], ["biblio", "Bibliografia", CaI.doc, true]]],
    ["Relazioni", [["sales", "Vendite", CaI.euro, crm && caMod(s, "crm")], ["contacts", "Contatti", CIc.users, crm && caMod(s, "crm")]]],
    ["", [["public", "Archivio pubblico", CIc.globe, caMod(s, "public")], ["docs", "Documenti", CaI.doc, true], ["settings", "Impostazioni", CIc.cog, true]]]];
  const on = (x) => p === x || (x === "works" && (p === "work" || p === "new")) || (x === "certs" && (p === "cert" || p === "issue")) || (x === "exhibitions" && p === "exh") || (x === "contacts" && p === "contact") || (x === "series" && p === "serie");
  const crumb = { work: ["Opere", "works", (caById(s.works, s.route.id) || {}).title], cert: ["Certificati", "certs", s.route.id], issue: ["Certificati", "certs", "Nuovo certificato"], new: ["Opere", "works", "Nuova opera"], serie: ["Serie e collezioni", "series", ((s.series || []).find((x) => x.id === s.route.id) || {}).title], exh: ["Mostre", "exhibitions", (caById(s.exhibitions, s.route.id) || {}).title], contact: ["Contatti", "contacts", (caById(s.contacts, s.route.id) || {}).name] }[p];
  const me = s.team.find((m) => m.r === s.viewAs) || s.team[0];
  return <div className="app">
    <aside className="side">
      <div className="brand"><b>CERTIFY</b><span className="ca-prod">Artists</span></div>
      <div className="org"><span className="org-m"><b style={{ fontSize: 12, letterSpacing: ".04em" }}>{s.studio.initials}</b></span><div><b>{s.studio.name}</b><span>Studio d'artista</span></div></div>
      {SEC.map(([t, L]) => { const vis = L.filter((x) => x[3]); if (!vis.length) return null; return <div key={t || L[0][0]} className="sd-s">{t && <div className="sd-t">{t}</div>}{vis.map(([x, l, I, , n]) => <button key={x} title={l} className={"nav" + (on(x) ? " on" : "")} onClick={() => go({ p: x })}><I /><span>{l}</span>{n > 0 && <i>{n}</i>}</button>)}</div>; })}
      <div className="sf-w">{um && <div className="um" onClick={() => setUm(false)}>
        <div className="ca-um-t">Visualizza come</div>{CA_ROLES.map((r) => <button key={r} onClick={() => mut((n) => { n.viewAs = r; n.route = { p: "dash" }; })}>{r}{s.viewAs === r ? " ✓" : ""}</button>)}<hr />
        <button onClick={() => { location.href = "Certify FINAL.html"; }}>Passa a Certify Archives</button><button onClick={() => { setUm(false); mut((n) => { n.tour = 0; }); }}>Tour di Certify Artists</button><button onClick={reset}>Ripristina demo</button></div>}
        <button className="side-f" onClick={() => setUm(!um)}><span className="av">{me.n.split(" ").map((x) => x[0]).slice(0, 2).join("")}</span><div><b>{me.n}</b><span>{s.viewAs}</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>
    <CaTour />
    <main className="main"><div className="ca-top"><div className="ca-crumb">{crumb && <><button onClick={() => go({ p: crumb[1] })}>{crumb[0]}</button><span>/</span><b>{crumb[2]}</b></>}</div>
      <span className="ca-demo">Dati dimostrativi</span>{window.CA_I18N && <button className="ca-lang" onClick={() => window.CA_I18N.toggle()} title="Language / Lingua"><b className={window.CA_I18N.lang === "en" ? "on" : ""}>EN</b><b className={window.CA_I18N.lang === "it" ? "on" : ""}>IT</b></button>}<button className="ca-tk" onClick={() => setK(true)}><CIc.search /><span>Cerca</span><kbd>⌘K</kbd></button></div>{children}</main>
    {k && <CaSearch onClose={() => setK(false)} />}
  </div>;
}

Object.assign(window, { CIc, CArt, CPill, CBtn, CModal, CTg, useCa, CaProvider, CaShell, CaMove, CaNewWork, CaF, CaI, CaCertPill, caClone, caToday, caFmt, caEur, caDays, caById, caLog, CA_REQ, caMissing, caDocsOf, caCertOf, caCompl, caLoanOf, caExhOf, CA_ROLES, CA_PERMS, caCan, CA_LOC, CA_AV, CA_CATS, caAvK, CA_CS });
