// Certify Unified — full catalogue raisonné record ("Scheda scientifica"). Demo data, generated per artwork.
const { useState: cS } = React;

const CR_VIS = { public: ["Pubblico", Ic.pub], collector: ["Collezionista", Ic.key], archive: ["Solo archivio", Ic.lock] };
function crHash(str) { let h = 2166136261; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
const pick = (h, arr, k = 0) => arr[(h >>> (k * 3)) % arr.length];

function crGen(a) {
  const h = crHash(a.id + a.title); const y = +a.year || 1965; const paper = /carta|cartone/i.test(a.medium || "");
  return {
    altTitle: pick(h, ["", "", "Senza titolo", `Studio per «${a.title}»`]),
    dating: a.yearLabel || pick(h, [`${y}`, `${y} circa`, `${y}–${y + 1}`]),
    datingNote: (a.yearLabel || a.inscr) ? "" : pick(h, ["Datata sul retro dall'artista.", "Datazione su base stilistica e documentaria.", "Data confermata dalla fotografia d'archivio del " + (y + 1) + "."], 1),
    crNo: `${String(y).slice(2)}.${String((h % 140) + 1).padStart(3, "0")}`,
    oldNo: pick(h, ["", `Arch. FA ${1000 + (h % 900)}`, `Cat. 1988 n. ${(h % 300) + 1}`], 2),
    support: paper ? pick(h, ["Carta intelata su tela", "Cartone", "Carta"]) : pick(h, ["Tela", "Tela grezza", "Tavola"]),
    dimsSheet: paper ? a.dims : "", dimsFrame: a.dims ? pick(h, ["", a.dims.replace(/(\d+)(,\d+)?/g, (m, i, dec) => String(+i + 8) + (dec || ""))], 3) : "",
    edition: a.edition || "Opera unica",
    inscriptions: a.inscr ? a.inscr.split(/;\s*/).filter(Boolean).map((t) => ({ kind: /^Etichetta|etichetta/.test(t) ? "Etichetta" : /[Tt]imbro/.test(t) ? "Timbro" : /^Dedica|dedica/.test(t) && !/^Firmat/.test(t) ? "Dedica" : /^Firmat|^Firma/.test(t) ? "Firma" : "Iscrizione", where: "", text: t, tech: "" })) : [
      { kind: "Firma", where: "Al retro, in alto a destra", text: `Angeli ${String(y).slice(2)}`, tech: "Pennarello nero" },
      ...(h % 3 ? [{ kind: "Iscrizione", where: "Al retro, sul telaio", text: `«${a.title}» ${y}`, tech: "Matita" }] : []),
      ...(h % 2 ? [{ kind: "Etichetta", where: "Al retro, sul telaio", text: "Galleria La Tartaruga, Roma · n. " + (100 + (h % 400)), tech: "Etichetta a stampa" }] : []),
      ...(h % 5 === 0 ? [{ kind: "Timbro", where: "Al retro", text: "Archivio Franco Angeli · n. " + (h % 3000), tech: "Timbro a inchiostro" }] : []),
    ],
    verso: pick(h, ["Telaio originale in legno, chiodi a vista", "Tela rifoderata; telaio non originale, sostituito in occasione del restauro", "Non ispezionabile: pannello di protezione"]),
    frame: pick(h, ["Originale, legno laccato bianco", "Non originale, legno naturale", "Assente"], 4),
    condition: pick(h, ["Buono", "Discreto", "Buono, con lievi cadute di colore ai margini"]),
    conditionDate: `${pick(h, ["03", "05", "09"])}.2025`,
    conditionBy: pick(h, ["Studio Restauri Bellini, Roma", "Laboratorio Conti, Milano"]),
    restorations: h % 2 ? [{ year: String(1990 + (h % 25)), who: pick(h, ["Studio Restauri Bellini, Roma", "Laboratorio Conti, Milano"], 1), what: pick(h, ["Pulitura e consolidamento della pellicola pittorica", "Rifoderatura e sostituzione del telaio"], 2) }] : [],
    expertise: [
      { year: String(y + 2), who: "Franco Angeli", what: "Dichiarazione autografa su fotografia" },
      ...(h % 3 === 0 ? [{ year: "2009", who: "Comitato scientifico dell'Archivio", what: "Parere favorevole, pratica n. " + (200 + (h % 700)) }] : []),
    ],
    biblio: [
      { author: "AA.VV.", title: "Franco Angeli", pub: "Galleria La Tartaruga", place: "Roma", year: String(y + 1), page: `p. ${(h % 40) + 4}`, how: "riprodotto" },
      ...(h % 2 ? [{ author: "L. Meloni (a cura di)", title: "Franco Angeli. Gli anni Sessanta", pub: "Silvana Editoriale", place: "Cinisello Balsamo", year: "2010", page: `p. ${(h % 120) + 20}, tav. ${(h % 60) + 1}`, how: "riprodotto a colori" }] : []),
      ...(h % 3 === 1 ? [{ author: "M. Calvesi", title: "Le due avanguardie", pub: "Lerici", place: "Milano", year: "1966", page: `p. ${(h % 30) + 100}`, how: "citato" }] : []),
    ],
    photos: [
      { view: "Fronte", by: "Archivio fotografico", year: "2024", res: "TIFF 8000 px" },
      { view: "Retro", by: "Archivio fotografico", year: "2024", res: "TIFF 6000 px" },
      { view: "Dettaglio della firma", by: "Archivio fotografico", year: "2024", res: "JPG" },
      ...(h % 2 ? [{ view: "Luce radente", by: "Studio Restauri Bellini", year: "2025", res: "TIFF" }] : []),
      ...(h % 4 === 0 ? [{ view: "Fotografia d'epoca, studio dell'artista", by: "Fotografo sconosciuto", year: String(y + 1), res: "Stampa ai sali d'argento" }] : []),
    ],
    critical: `Opera emblematica della ricerca di Angeli sul simbolo e sulla sua velatura. ${a.title} riprende iconografie del potere e della memoria collettiva, attenuandole con il velatino: l'immagine resta riconoscibile ma si allontana, come un ricordo.`,
    remarks: pick(h, ["Verificare la corrispondenza tra l'etichetta della galleria e il registro delle consegne.", "Da confrontare con la fotografia d'epoca del Fondo De Martiis.", ""], 5),
    vis: { ident: "public", technique: "public", inscriptions: "public", verso: "collector", condition: "archive", expertise: "archive", biblio: "public", photos: "collector", critical: "public", remarks: "archive" },
  };
}
const crOf = (a) => a.cr || crGen(a);

const CR_LBL = { crNo: "N. di catalogo ragionato", oldNo: "Numerazioni precedenti", altTitle: "Titolo alternativo", dating: "Datazione", datingNote: "Nota sulla datazione", support: "Supporto", dimsSheet: "Dimensioni del foglio", dimsFrame: "Dimensioni con cornice", edition: "Edizione / esemplare", verso: "Retro e telaio", frame: "Cornice", condition: "Stato di conservazione", conditionDate: "Ultimo esame", conditionBy: "Esaminato da" };
const CR_SEC = [
  ["ident", "Identificazione"], ["technique", "Tecnica, supporto e dimensioni"], ["inscriptions", "Firma, iscrizioni, etichette e timbri"], ["verso", "Retro e cornice"],
  ["condition", "Stato di conservazione e restauri"], ["expertise", "Pareri e autenticazioni storiche"], ["biblio", "Bibliografia"], ["photos", "Campagna fotografica"],
  ["critical", "Nota critica"], ["remarks", "Osservazioni dell'archivio"],
];

function VisSel({ v, on, edit }) {
  const [l, I] = CR_VIS[v];
  return edit ? <select className="crv" value={v} onChange={(e) => on(e.target.value)}>{Object.keys(CR_VIS).map((k) => <option key={k} value={k}>{CR_VIS[k][0]}</option>)}</select> : <span className="crvs"><I />{l}</span>;
}
const CrHide = ({ on, label }) => <button type="button" className="crx" title={label || "Nascondi voce"} aria-label={label || "Nascondi voce"} onClick={on}><svg viewBox="0 0 24 24" width="15" height="15" 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></button>;
function KV({ rows, edit, d, set, hid = [], hide }) {
  return rows.filter(([k]) => !hid.includes(k)).map(([k, l]) => <div key={k} className={"dr crr" + (edit ? " ed" : "")}><span>{l}</span>{edit ? <input value={d[k] || ""} onChange={(e) => set(k, e.target.value)} /> : <b className={d[k] ? "" : "dr-e"}>{d[k] || "Da compilare"}</b>}{edit && hide && <CrHide on={() => hide(k)} />}</div>);
}
function Tab({ rows, cols, edit, onChange, empty }) {
  const up = (i, k, v) => onChange(rows.map((r, j) => (j === i ? { ...r, [k]: v } : r)));
  return <><div className="crt"><table className={edit ? "ed" : ""}><thead><tr>{cols.map(([k, l]) => <th key={k}>{l}</th>)}{edit && <th className="crt-x"></th>}</tr></thead>
    <tbody>{rows.map((r, i) => <tr key={i}>{cols.map(([k]) => <td key={k}>{edit ? <input value={r[k] || ""} onChange={(e) => up(i, k, e.target.value)} /> : r[k] || "—"}</td>)}{edit && <td className="crt-x"><button className="ib" title="Rimuovi riga" aria-label="Rimuovi riga" onClick={() => onChange(rows.filter((_, j) => j !== i))}><Ic.x /></button></td>}</tr>)}</tbody></table>
    {!rows.length && <div className="empty">{empty}</div>}</div>
    {edit && <button className="lnk" style={{ marginTop: 8 }} onClick={() => onChange([...rows, Object.fromEntries(cols.map(([k]) => [k, ""]))])}>+ Aggiungi riga</button>}</>;
}

function CRTab({ a }) {
  const { s: s0, mut, say } = useC(); const [edit, setEdit] = cS(false); const [mg, setMg] = cS(false); const [d, setD] = cS(null);
  const cur = edit ? d : crOf(a); const set = (k, v) => setD({ ...d, [k]: v }); const setVis = (k, v) => setD({ ...d, vis: { ...d.vis, [k]: v } });
  const H = (s0.crHide || { f: [], s: [] }); const persistH = (fn) => { mut((n) => { n.crHide = n.crHide || { f: [], s: [] }; fn(n.crHide); }); };
  const hideF = (k) => { persistH((h) => { h.f = [...new Set([...h.f, k])]; }); say("Voce nascosta · i dati restano salvati"); };
  const hideS = (k) => { persistH((h) => { h.s = [...new Set([...h.s, k])]; }); say("Sezione nascosta · i dati restano salvati"); };
  const nH = H.f.length + H.s.length;
  const save = () => { mut((n) => { byId(n.works, a.id).cr = d; log(n, { type: "modifica", artworkId: a.id, text: `${a.title}: scheda scientifica aggiornata` }); }); setEdit(false); say("Scheda scientifica salvata"); };
  const body = {
    ident: <KV edit={edit} d={cur} set={set} hid={H.f} hide={hideF} rows={[["crNo", "N. di catalogo ragionato"], ["oldNo", "Numerazioni precedenti"], ["altTitle", "Titolo alternativo"], ["dating", "Datazione"], ["datingNote", "Nota sulla datazione"]]} />,
    technique: <><div className="dr crr"><span>Tecnica<i className="req">*</i></span><b className={a.medium ? "" : "dr-e"}>{a.medium || "Da compilare"}</b></div><div className="dr crr"><span>Dimensioni<i className="req">*</i></span><b className={a.dims ? "" : "dr-e"}>{a.dims || "Da compilare"}</b></div><KV edit={edit} d={cur} set={set} hid={H.f} hide={hideF} rows={[["support", "Supporto"], ["dimsSheet", "Dimensioni del foglio"], ["dimsFrame", "Dimensioni con cornice"], ["edition", "Edizione / esemplare"]]} /></>,
    inscriptions: <Tab edit={edit} rows={cur.inscriptions} onChange={(v) => set("inscriptions", v)} empty="Nessuna iscrizione registrata." cols={[["kind", "Tipo"], ["where", "Posizione"], ["text", "Trascrizione"], ["tech", "Tecnica"]]} />,
    verso: <KV edit={edit} d={cur} set={set} hid={H.f} hide={hideF} rows={[["verso", "Retro e telaio"], ["frame", "Cornice"]]} />,
    condition: <><KV edit={edit} d={cur} set={set} hid={H.f} hide={hideF} rows={[["condition", "Stato di conservazione"], ["conditionDate", "Ultimo esame"], ["conditionBy", "Esaminato da"]]} /><h4 className="crh">Restauri</h4><Tab edit={edit} rows={cur.restorations} onChange={(v) => set("restorations", v)} empty="Nessun restauro documentato." cols={[["year", "Anno"], ["who", "Restauratore"], ["what", "Intervento"]]} /></>,
    expertise: <Tab edit={edit} rows={cur.expertise} onChange={(v) => set("expertise", v)} empty="Nessun parere registrato." cols={[["year", "Anno"], ["who", "Autore"], ["what", "Parere / documento"]]} />,
    biblio: <Tab edit={edit} rows={cur.biblio} onChange={(v) => set("biblio", v)} empty="Nessuna voce bibliografica." cols={[["author", "Autore"], ["title", "Titolo"], ["pub", "Editore"], ["place", "Luogo"], ["year", "Anno"], ["page", "Pagine / tavole"], ["how", "Come"]]} />,
    photos: <Tab edit={edit} rows={cur.photos} onChange={(v) => set("photos", v)} empty="Nessuna fotografia." cols={[["view", "Ripresa"], ["by", "Autore"], ["year", "Anno"], ["res", "Formato"]]} />,
    critical: edit ? <textarea rows={5} value={cur.critical} onChange={(e) => set("critical", e.target.value)} /> : <p className="crp">{cur.critical}</p>,
    remarks: edit ? <textarea rows={3} value={cur.remarks} onChange={(e) => set("remarks", e.target.value)} /> : <p className="crp sm">{cur.remarks || <em className="mut">Nessuna osservazione.</em>}</p>,
  };
  return <div>
    <div className="crbar"><div className="mut sm">{edit ? "Nascondi le voci che il tuo archivio non usa. I dati restano salvati." : "Tutte le voci di una scheda di catalogo ragionato. Per ogni sezione scegli chi può vederla."}</div>
      {nH > 0 && <button className="ds-mg" onClick={() => setMg(true)}>{nH} {nH === 1 ? "voce nascosta" : "voci nascoste"}</button>}{edit ? <div className="row"><Btn k="sm" onClick={() => setEdit(false)}>Annulla</Btn><Btn k="sm dark" onClick={save}>Salva</Btn></div> : <Btn k="sm" onClick={() => { setD(JSON.parse(JSON.stringify(crOf(a)))); setEdit(true); }}>Modifica</Btn>}</div>
    {CR_SEC.filter(([k]) => !H.s.includes(k)).map(([k, l]) => <section key={k} className="card crs"><div className="c-h crs-h"><h2>{l}</h2><div className="crs-a"><VisSel v={cur.vis[k]} edit={edit} on={(v) => setVis(k, v)} />{edit && <CrHide on={() => hideS(k)} label="Nascondi sezione" />}</div></div>{body[k]}</section>)}
    {mg && <Modal title="Voci nascoste" onClose={() => setMg(false)} foot={<><button className="lnk" style={{ marginRight: "auto" }} onClick={() => { persistH((h) => { h.f = []; h.s = []; }); say("Configurazione predefinita ripristinata"); }}>Ripristina tutto</button><Btn k="dark" onClick={() => setMg(false)}>Fatto</Btn></>}>
      <p className="mut" style={{ marginTop: 0 }}>Nascoste per tutto l'archivio. I dati restano salvati e la visibilità pubblica non cambia.</p>
      {!nH && <div className="empty">Nessuna voce nascosta.</div>}
      {H.s.map((k) => <div key={k} className="mg-r"><span><b>{(CR_SEC.find((x) => x[0] === k) || [, k])[1]}</b> · sezione</span><button className="lnk" onClick={() => persistH((h) => { h.s = h.s.filter((x) => x !== k); })}>Mostra</button></div>)}
      {H.f.map((k) => <div key={k} className="mg-r"><span>{CR_LBL[k] || k}</span><button className="lnk" onClick={() => persistH((h) => { h.f = h.f.filter((x) => x !== k); })}>Mostra</button></div>)}
    </Modal>}
  </div>;
}

// Sections the archive marked public, rendered on the public artwork page.
function CRPublic({ a }) {
  const c = crOf(a); const on = (k) => c.vis[k] === "public";
  return <>
    {on("ident") && <div className="psec"><h4>Catalogo ragionato</h4><p>N. {c.crNo}{c.oldNo ? ` · già ${c.oldNo}` : ""}</p><p>{c.dating}</p></div>}
    {on("technique") && (c.support || c.dimsFrame) && <div className="psec"><h4>Supporto</h4><p>{c.support}{c.dimsFrame ? `; ${c.dimsFrame}` : ""}</p></div>}
    {on("inscriptions") && c.inscriptions.length > 0 && <div className="psec"><h4>Firma e iscrizioni</h4>{c.inscriptions.map((x, i) => <p key={i}>{x.where ? <>{x.kind}, {x.where.toLowerCase()}: «{x.text}»</> : x.text}</p>)}</div>}
    {on("verso") && <div className="psec"><h4>Retro e cornice</h4><p><b>Retro:</b> {c.verso}<br/><b>Cornice:</b> {c.frame}</p></div>}
    {on("condition") && <div className="psec"><h4>Conservazione</h4><p>{c.condition}</p>{c.restorations.map((r, i) => <p key={i}>{r.year}, {r.who}: {r.what}</p>)}</div>}
    {on("expertise") && c.expertise.length > 0 && <div className="psec"><h4>Pareri</h4>{c.expertise.map((x, i) => <p key={i}>{x.who}, {x.what}, {x.year}</p>)}</div>}
    {on("biblio") && c.biblio.length > 0 && <div className="psec"><h4>Bibliografia</h4>{c.biblio.map((b, i) => <p key={i}>{b.author}, <i>{b.title}</i>, {b.pub}, {b.place} {b.year}, {b.page} ({b.how})</p>)}</div>}
    {on("critical") && <div className="psec"><h4>Nota critica</h4><p>{c.critical}</p></div>}
  </>;
}
Object.assign(window, { CRTab, CRPublic, crOf });
