// Certify for Artists — editions, inventory, series, artist-specific navigation.
const caEdAll = (a) => (a && a.eds ? a.eds.flatMap((g) => g.items.map((it) => ({ ...it, g: g.g, fmt: g.fmt, key: g.g + ":" + it.n, price: it.price != null ? it.price : g.price }))) : []);
function caEdFind(a, key) { if (!a || !key) return null; for (const g of a.eds || []) for (const it of g.items) if (g.g + ":" + it.n === key) return { g, it }; return null; }
const caEdLabel = (a, key) => { const f = caEdFind(a, key); return f ? f.it.n + " · " + f.g.fmt : ""; };
function caEdSync(w) { if (!w || !w.eds) return; const L = caEdAll(w).filter((x) => !/^AP/.test(x.n)); w.avail = L.some((x) => x.st === "Disponibile") ? "Disponibile" : L.some((x) => x.st === "Riservata" || x.st === "In conto vendita") ? "Riservata" : L.every((x) => x.st === "Venduta") ? "Venduta" : w.avail; }
const caEdSum = (a) => { const L = caEdAll(a); const c = (st) => L.filter((x) => x.st === st).length; return { tot: L.length, av: c("Disponibile"), sold: c("Venduta"), res: c("Riservata"), con: c("In conto vendita") }; };
const CA_SELL = [["display", "Solo visione", "L'opera è mostrata senza funzioni commerciali."], ["inquire", "Richiedi informazioni", "I visitatori possono scriverti a proposito dell'opera."], ["request", "Prezzo su richiesta", "I visitatori chiedono il prezzo con un modulo."], ["buy", "Acquisto diretto", "Prezzo visibile e pagamento con Stripe per gli esemplari disponibili."]];

function CaEditions({ a }) {
  const { s, mut, say, go } = useCa(); const can = caCan(s, "edit"); const [pay, setPay] = React.useState(null); const [ng, setNg] = React.useState(null);
  const upd = (fn, msg) => { mut((n) => { const w = caById(n.works, a.id); fn(w, n); caEdSync(w); }); msg && say(msg); };
  const addGroup = () => { const g = String.fromCharCode(65 + (a.eds || []).length); const size = Math.max(1, +ng.size || 1), ap = Math.max(0, +ng.ap || 0);
    const items = []; for (let i = 1; i <= size; i++) items.push({ n: i + "/" + size, st: "Disponibile" }); for (let j = 1; j <= ap; j++) items.push({ n: "AP " + j + "/" + ap, st: "Collezione dell'artista" });
    upd((w) => { w.eds = [...(w.eds || []), { g, fmt: ng.fmt, size, ap, price: +ng.price || null, items }]; }, "Edizione " + g + " creata: " + size + " + " + ap + " PA"); setNg(null); };
  const extra = (g) => { const used = g.items.filter((x) => !/^AP/.test(x.n)).length; if (used >= g.size) { say("Attenzione: l'edizione dichiarata è di " + g.size + " esemplari. Modifica la tiratura prima di aggiungerne altri."); return; } };
  const D = a.digital || {}; const sum = caEdSum(a);
  return <div className="ed-w">
    <section className="ex-sec"><h2>Formato</h2>
      <div className="ed-kv"><span>Tipo di opera</span>{can ? <select value={a.kind || ""} onChange={(e) => upd((w) => { w.kind = e.target.value; })}>{["Opera unica fisica", "Edizione fisica", "Opera digitale unica", "Edizione digitale", "Fotografia", "Video o immagine in movimento", "Scultura", "Installazione", "Altro"].map((x) => <option key={x}>{x}</option>)}</select> : <b>{a.kind}</b>}</div>
      {(/digital|Video/i.test(a.kind || "") || a.digital) && <div className="ed-dg">{[["format", "Formato file"], ["res", "Risoluzione"], ["dur", "Durata"], ["link", "Link esterno"], ["chain", "Blockchain"], ["contract", "Indirizzo del contratto"], ["token", "Token ID"]].map(([k, l]) => <label key={k} className="ca-f"><span>{l}</span><input value={D[k] || ""} disabled={!can} placeholder="Facoltativo" onChange={(e) => upd((w) => { w.digital = { ...(w.digital || {}), [k]: e.target.value }; })} /></label>)}</div>}
    </section>
    <section className="ex-sec"><h2>Edizioni {a.eds && <em>{sum.tot} esemplari · {sum.av} disponibili · {sum.sold} venduti</em>}</h2>
      {!a.eds && <p className="mut">Opera unica. Se è un'opera in edizione, definisci tiratura e prove d'artista: gli esemplari vengono gestiti qui, senza duplicare la scheda.</p>}
      {(a.eds || []).map((g, gi) => <div key={g.g} className="ed-g">
        <div className="ed-gh"><div><b>Edizione {g.g}</b><span>{g.fmt} · {g.size} + {g.ap} PA{g.price ? " · " + caEur(g.price) : ""}</span></div><button className="lnk" onClick={() => extra(g)}>+ Esemplare</button></div>
        <div className="ca-tw"><table className="ca-t ed-t"><thead><tr><th>N.</th><th>Stato</th><th>Prezzo</th><th>Presso / collezionista</th><th>Certificato</th><th></th></tr></thead><tbody>
          {g.items.map((it, ii) => { const key = g.g + ":" + it.n; const b = it.buyer && caById(s.contacts, it.buyer); const gal = it.gallery && caById(s.contacts, it.gallery); const c = it.cert && caById(s.certs, it.cert);
            return <tr key={it.n}><td className="mono"><b>{it.n}</b></td>
              <td>{can ? <select className="ed-sel" value={it.st} onChange={(e) => upd((w) => { w.eds[gi].items[ii].st = e.target.value; }, "Esemplare " + it.n + ": " + e.target.value)}>{CA_AV.map((x) => <option key={x}>{x}</option>)}</select> : it.st}</td>
              <td className="mono">{caEur(it.price != null ? it.price : g.price)}</td>
              <td>{b ? <button className="lnk" onClick={() => go({ p: "contact", id: b.id })}>{b.name}</button> : gal ? gal.name : <span className="mut">Studio</span>}{it.soldAt && <div className="mut sm">Venduto il {caFmt(it.soldAt)}</div>}</td>
              <td>{c ? <button className="lnk mono" onClick={() => go({ p: "cert", id: c.id })}>{c.id}</button> : <span className="mut">—</span>}{c && <div className="mut sm">{CA_CS[c.status][0]}</div>}</td>
              <td className="pl-act">{it.st === "Disponibile" && caCan(s, "crm") && <CBtn k="sm" onClick={() => setPay(key)}>Link di pagamento</CBtn>}{!c && caCan(s, "prep") && /Venduta|Collezione/.test(it.st) && <CBtn k="sm" onClick={() => go({ p: "issue", wid: a.id, ed: key })}>Emetti certificato</CBtn>}</td></tr>; })}
        </tbody></table></div></div>)}
      {can && (ng ? <div className="ed-new"><CaF l="Formato di produzione" req><input autoFocus value={ng.fmt} onChange={(e) => setNg({ ...ng, fmt: e.target.value })} placeholder="Es. Stampa a pigmenti d'archivio, 60 × 48 cm" /></CaF>
          <div className="ex-g"><CaF l="Tiratura"><input inputMode="numeric" value={ng.size} onChange={(e) => setNg({ ...ng, size: e.target.value.replace(/\D/g, "") })} /></CaF><CaF l="Prove d'artista"><input inputMode="numeric" value={ng.ap} onChange={(e) => setNg({ ...ng, ap: e.target.value.replace(/\D/g, "") })} /></CaF><CaF l="Prezzo per esemplare (€)"><input inputMode="decimal" value={ng.price} onChange={(e) => setNg({ ...ng, price: e.target.value.replace(/[^\d.]/g, "") })} /></CaF></div>
          <p className="mut sm">Verranno creati {Math.max(1, +ng.size || 1)} esemplari numerati e {+ng.ap || 0} prove d'artista. I numeri non possono essere duplicati.</p>
          <div className="ca-nav"><CBtn onClick={() => setNg(null)}>Annulla</CBtn><CBtn k="dark" disabled={!ng.fmt} onClick={addGroup}>Crea edizione</CBtn></div></div>
        : <button className="lnk" onClick={() => setNg({ fmt: "", size: "10", ap: "2", price: a.price ? String(a.price) : "" })}>+ {a.eds ? "Aggiungi un altro formato" : "Definisci un'edizione"}</button>)}
    </section>
    <section className="ex-sec"><h2>Nel catalogo pubblico</h2>
      <div className="ed-sell">{CA_SELL.map(([k, l, d]) => <button key={k} disabled={!can} className={(a.sell || "display") === k ? "on" : ""} onClick={() => upd((w) => { w.sell = k; }, "Opzione di acquisto: " + l)}><i></i><div><b>{l}</b><span>{d}</span></div></button>)}</div>
      <div className="ed-kv"><span>Pubblicata nel catalogo</span><CTg on={!!a.pub} onClick={() => can && upd((w) => { w.pub = !w.pub; })} /></div>
      <div className="ed-kv"><span>Mostra disponibilità e prezzo</span><CTg on={a.sell === "buy" || !!a.showPrice} onClick={() => can && a.sell !== "buy" && upd((w) => { w.showPrice = !w.showPrice; })} /></div>
      <button className="lnk" onClick={() => go({ p: "site", sp: "work", id: a.id })}>Anteprima della pagina pubblica →</button>
    </section>
    {pay && <CaPayModal init={{ wid: a.id, ed: pay }} onClose={() => setPay(null)} />}
  </div>;
}

function CaInventory() {
  const { s, go, mut, say } = useCa(); const [st, setSt] = React.useState(""); const [sr, setSr] = React.useState(""); const [k, setK] = React.useState(""); const [pay, setPay] = React.useState(null);
  const rows = s.works.filter((a) => (!sr || (a.series || []).includes(sr)) && (!k || a.kind === k)).flatMap((a) => a.eds ? caEdAll(a).map((x) => ({ a, x })) : [{ a, x: null }]).filter((r) => !st || (r.x ? r.x.st : r.a.avail) === st);
  const cnt = (v) => s.works.flatMap((a) => a.eds ? caEdAll(a).map((x) => x.st) : [a.avail]).filter((x) => x === v).length;
  return <div className="page">
    <div className="ca-ph"><div><h1>Inventario</h1><p className="mut">Ogni opera unica e ogni singolo esemplare, con stato, prezzo e collezionista.</p></div></div>
    <div className="ca-chips"><button className={!st ? "on" : ""} onClick={() => setSt("")}>Tutti</button>{CA_AV.map((v) => cnt(v) > 0 && <button key={v} className={st === v ? "on" : ""} onClick={() => setSt(v)}>{v}<em>{cnt(v)}</em></button>)}</div>
    <div className="ca-tools"><select value={sr} onChange={(e) => setSr(e.target.value)}><option value="">Tutte le serie</option>{(s.series || []).map((x) => <option key={x.id} value={x.id}>{x.title}</option>)}</select>
      <select value={k} onChange={(e) => setK(e.target.value)}><option value="">Ogni tipo di opera</option>{[...new Set(s.works.map((a) => a.kind).filter(Boolean))].map((x) => <option key={x}>{x}</option>)}</select><span className="mut sm">{rows.length} righe</span></div>
    <div className="ca-tw"><table className="ca-t"><thead><tr><th>Opera</th><th>Esemplare</th><th>Stato</th><th>Prezzo</th><th>Presso / collezionista</th><th></th></tr></thead><tbody>
      {rows.map(({ a, x }) => { const b = x && x.buyer && caById(s.contacts, x.buyer); return <tr key={a.id + (x ? x.key : "")} onClick={() => go({ p: "work", id: a.id, tab: x ? "ed" : "info" })}>
        <td><div className="ca-tc"><div className="ca-th"><CArt a={a} label={false} r={5} /></div><div><b>{a.title}</b><span>{a.year || "s.d."} · {a.kind}</span></div></div></td>
        <td className="mono">{x ? <>{x.n}<div className="mut sm" style={{ fontFamily: "inherit" }}>{x.fmt}</div></> : <span className="mut">Opera unica</span>}</td>
        <td><CPill k={caAvK(x ? x.st : a.avail)}>{x ? x.st : a.avail}</CPill></td><td className="mono">{caEur(x ? x.price : a.price)}</td>
        <td>{b ? b.name : <span className="mut">{x && x.gallery ? (caById(s.contacts, x.gallery) || {}).name : a.loc.d}</span>}</td>
        <td onClick={(e) => e.stopPropagation()}>{(x ? x.st : a.avail) === "Disponibile" && caCan(s, "crm") && <CBtn k="sm" onClick={() => setPay({ wid: a.id, ed: x ? x.key : "" })}>Link di pagamento</CBtn>}</td></tr>; })}
    </tbody></table></div>
    {pay && <CaPayModal init={pay} onClose={() => setPay(null)} />}
  </div>;
}

function CaSeriesList() {
  const { s, go, mut, say } = useCa(); const [f, setF] = React.useState(null); const L = s.series || [];
  const save = () => { const id = "sr-" + Date.now().toString(36); mut((n) => { n.series = [...(n.series || []), { id, title: f.title, from: +f.from || null, to: +f.to || null, desc: f.desc, pub: false, cover: "" }]; caLog(n, "Serie creata: " + f.title); }); setF(null); go({ p: "serie", id }); };
  return <div className="page">
    <div className="ca-ph"><div><h1>Serie e collezioni</h1><p className="mut">I corpi di lavoro dello studio. Un'opera può appartenere a più serie senza duplicare la scheda.</p></div>{caCan(s, "edit") && <CBtn k="dark" onClick={() => setF({ title: "", from: "", to: "", desc: "" })}><CIc.plus /> Nuova serie</CBtn>}</div>
    <div className="sr-grid">{L.map((x, i) => { const W = s.works.filter((a) => (a.series || []).includes(x.id)); const cov = caById(s.works, x.cover) || W[0];
      return <div key={x.id} className="sr-c"><button onClick={() => go({ p: "serie", id: x.id })}><div className="sr-i">{cov ? <CArt a={cov} label={false} r={10} /> : <div className="sr-ph"></div>}</div><b>{x.title}</b><span>{[x.from, x.to && x.to !== x.from ? x.to : x.from && !x.to ? "oggi" : null].filter(Boolean).join(" – ") || "Date da indicare"} · {W.length} opere</span><span>{x.pub ? <CPill k="ok">Pubblica</CPill> : <CPill k="lt">Privata</CPill>}</span></button>
        {caCan(s, "edit") && <div className="sr-o"><button disabled={!i} onClick={() => mut((n) => { const a = n.series; [a[i - 1], a[i]] = [a[i], a[i - 1]]; })} title="Sposta prima">↑</button><button disabled={i === L.length - 1} onClick={() => mut((n) => { const a = n.series; [a[i + 1], a[i]] = [a[i], a[i + 1]]; })} title="Sposta dopo">↓</button></div>}</div>; })}</div>
    {f && <CModal title="Nuova serie" onClose={() => setF(null)} foot={<><CBtn onClick={() => setF(null)}>Annulla</CBtn><CBtn k="dark" disabled={!f.title} onClick={save}>Crea serie</CBtn></>}>
      <CaF l="Titolo" req><input autoFocus value={f.title} onChange={(e) => setF({ ...f, title: e.target.value })} /></CaF>
      <div className="ca-g2"><CaF l="Anno di inizio"><input value={f.from} onChange={(e) => setF({ ...f, from: e.target.value })} /></CaF><CaF l="Anno di fine"><input value={f.to} onChange={(e) => setF({ ...f, to: e.target.value })} placeholder="In corso" /></CaF></div>
      <CaF l="Descrizione"><textarea className="ca-ta" value={f.desc} onChange={(e) => setF({ ...f, desc: e.target.value })} /></CaF></CModal>}
  </div>;
}

function CaSerie() {
  const { s, go, mut, say } = useCa(); const x = (s.series || []).find((y) => y.id === s.route.id); const [pick, setPick] = React.useState(null); const [ed, setEd] = React.useState(null);
  if (!x) return <div className="page"><div className="ca-empty">Serie non trovata.</div></div>;
  const ord = x.order || []; const W = s.works.filter((a) => (a.series || []).includes(x.id)).sort((p, q) => (ord.indexOf(p.id) + 1 || 999) - (ord.indexOf(q.id) + 1 || 999)); const can = caCan(s, "edit");
  const setS = (fn) => mut((n) => fn(n.series.find((y) => y.id === x.id), n));
  const mv = (i, d) => setS((y) => { const o = W.map((a) => a.id); [o[i], o[i + d]] = [o[i + d], o[i]]; y.order = o; });
  return <div className="page">
    <div className="ca-ph"><div><div className="ca-ids"><span>Serie</span><span>{[x.from, x.to].filter(Boolean).join(" – ") || "—"}</span>{x.pub ? <CPill k="ok">Pubblica</CPill> : <CPill k="lt">Privata</CPill>}</div><h1>{x.title}</h1></div>
      {can && <div className="caw-act">{ed ? <><CBtn onClick={() => setEd(null)}>Annulla</CBtn><CBtn k="dark" onClick={() => { setS((y) => Object.assign(y, ed)); setEd(null); say("Serie aggiornata"); }}>Salva</CBtn></> : <><CBtn onClick={() => setEd({ title: x.title, desc: x.desc, from: x.from || "", to: x.to || "" })}>Modifica</CBtn><CBtn k="dark" onClick={() => setPick([])}><CIc.plus /> Aggiungi opere</CBtn></>}</div>}</div>
    <div className="ex-lay"><div className="ex-main">
      <section className="ex-sec"><h2>Descrizione</h2>{ed ? <><CaF l="Titolo"><input value={ed.title} onChange={(e) => setEd({ ...ed, title: e.target.value })} /></CaF><div className="ca-g2"><CaF l="Dal"><input value={ed.from} onChange={(e) => setEd({ ...ed, from: e.target.value })} /></CaF><CaF l="Al"><input value={ed.to} onChange={(e) => setEd({ ...ed, to: e.target.value })} placeholder="In corso" /></CaF></div><textarea className="ca-ta" style={{ minHeight: 140 }} value={ed.desc} onChange={(e) => setEd({ ...ed, desc: e.target.value })} /></> : <div className="ex-text">{x.desc ? <p>{x.desc}</p> : <p className="dr-e">Nessuna descrizione.</p>}</div>}</section>
      <section className="ex-sec"><h2>Opere <em>{W.length} · trascina l'ordine con le frecce</em></h2>
        <div className="sr-list">{W.map((a, i) => <div key={a.id} className="sr-row"><div className="ca-th"><CArt a={a} label={false} r={5} /></div><button className="lnk" onClick={() => go({ p: "work", id: a.id })}><b>{a.title}</b></button><span className="mut sm">{a.year || "s.d."} · {a.kind}</span>
          {can && <span className="sr-o"><button disabled={!i} onClick={() => mv(i, -1)}>↑</button><button disabled={i === W.length - 1} onClick={() => mv(i, 1)}>↓</button><button title="Imposta come copertina" className={x.cover === a.id ? "on" : ""} onClick={() => setS((y) => { y.cover = a.id; })}>★</button><button title="Rimuovi dalla serie" onClick={() => mut((n) => { const w = caById(n.works, a.id); w.series = (w.series || []).filter((z) => z !== x.id); })}>×</button></span>}</div>)}
          {!W.length && <p className="dr-e">Nessuna opera in questa serie.</p>}</div></section>
    </div><aside className="ex-side"><h2>Visibilità</h2><div className="ed-kv"><span>Pubblica nel catalogo</span><CTg on={!!x.pub} onClick={() => can && setS((y) => { y.pub = !y.pub; })} /></div><p className="mut sm">Le serie pubbliche compaiono in automatico nel catalogo, nell'ordine scelto qui.</p><button className="lnk" onClick={() => go({ p: "site", sp: "serie", id: x.id })}>Anteprima pubblica →</button></aside></div>
    {pick && <CModal w={720} title={"Aggiungi opere a " + x.title} onClose={() => setPick(null)} foot={<><CBtn onClick={() => setPick(null)}>Annulla</CBtn><CBtn k="dark" disabled={!pick.length} onClick={() => { mut((n) => pick.forEach((id) => { const w = caById(n.works, id); w.series = [...new Set([...(w.series || []), x.id])]; })); say(pick.length + " opere aggiunte"); setPick(null); }}>Aggiungi {pick.length || ""}</CBtn></>}>
      <div className="ca-pick multi">{s.works.filter((a) => !(a.series || []).includes(x.id)).map((a) => <label key={a.id} className={pick.includes(a.id) ? "on" : ""}><input type="checkbox" checked={pick.includes(a.id)} onChange={() => setPick(pick.includes(a.id) ? pick.filter((z) => z !== a.id) : [...pick, a.id])} /><div className="ca-th lg"><CArt a={a} label={false} r={6} /></div><div><b>{a.title}</b><span>{a.year || "s.d."}</span></div></label>)}</div></CModal>}
  </div>;
}

window.CA_WTABS_PRE = [["ed", "Edizioni e formato"]];
window.CA_SECF = (s, { nAw, crm }) => [
  ["Studio", [["dash", "Panoramica", CIc.home, true], ["works", "Opere", CIc.works, true], ["series", "Serie e collezioni", CIc.frame, true], ["inventory", "Inventario", CaI.doc, true]]],
  ["Business", [["sales", "Vendite e pagamenti", CaI.euro, crm], ["certs", "Certificati", CIc.seal, true, nAw], ["template", "Modello di certificato", CaI.doc, true], ["contacts", "Collezionisti", CIc.users, crm]]],
  ["Documentazione", [["exhibitions", "Mostre", CIc.frame, true], ["biblio", "Pubblicazioni", CaI.doc, true]]],
  ["Presenza pubblica", [["site", "Catalogo pubblico", CIc.globe, true], ["public", "Gestione catalogo", CIc.cog, true]]],
  ["Account", [["settings", "Impostazioni", CIc.cog, true]]]];
Object.assign(window, { caEdAll, caEdFind, caEdLabel, caEdSync, caEdSum, CA_SELL, CaEditions, CaInventory, CaSeriesList, CaSerie });
