1import{v as Ae,j as e,c as ke,r,B as R,S as De,E as Se,z as ps,d as _e,a as Me,h as Je,X as ys,q as vs,M as $t,l as at,F as js,t as Oe,p as Rt,u as Et,e as zt,n as _t,g as ks,C as ws,L as Ns,k as Ss}from"./index-_aijvlUq.js";import{M as Cs,K as Ps,D as Ls}from"./MusicLibraryFilterBar-C3yZnsfl.js";import{u as Is,P as Ds}from"./PageHeader-DCofr6qo.js";import{m as U}from"./musicLibrary-DdhMEkq5.js";import{p as Ue}from"./performances-duTJPchz.js";import{p as Ts}from"./partnerships-B_F3kdIQ.js";import{M as Ie}from"./Menu-CATQC14B.js";import{C as Ke}from"./ConfirmDialog-CODvETNM.js";import{A as As}from"./ActiveFiltersBar-DPDav4h_.js";import{I as se}from"./Input-ysTyZFq5.js";import{u as Fs}from"./useDragReorder-BPTlhWx5.js";import{i as Ct}from"./instruments-CRxWHJ-h.js";import{C as Bs}from"./ChipToggleGroup-DiMa_Ns9.js";import{B as he}from"./Badge-DJIi163x.js";import{I as Os}from"./InstrumentTag-CHdSvMU6.js";import{B as Ms,P as $s,a as Rs,M as Es}from"./MobileMusicDetailSheet-EusJN61d.js";import{a as Ut}from"./Skeleton-B3Wj6cNd.js";import{E as lt}from"./EmptyState-CPGKooqj.js";import{a as zs}from"./EmptyIllustrations-D77xBxjU.js";import{B as Ye}from"./BottomSheet-BiQNSujt.js";import{S as _s,a as Us}from"./SmartImportSheet-D3pCNeZ6.js";import{M as qs}from"./MobileListSkeleton-BxuyWDCs.js";import{I as Ws}from"./InstrumentsFromPhotoModal--KDh5F6z.js";import{d as Pt}from"./exportCsv-CZAUSrIW.js";import{U as Hs}from"./UsageLimitBanner-FQhQBbSE.js";import{T as Vs}from"./Tabs-CGDUdv1I.js";import"./ChipToggle-hmCaOMqs.js";import"./Table-Yng-lqpt.js";import"./SmartImportWizard-C34JU9cR.js";import"./ensembles-WGlB365j.js";import"./WizardShell-BAf42hnX.js";import"./resizeImage-BUqRBCBG.js";import"./CameraCaptureButton-B4WpiVvJ.js";const Be={list(t={}){return Ae.get("/music-loans",{params:t})},create(t){return Ae.post("/music-loans",t)},approve(t,a={}){return Ae.post(`/music-loans/${t}/approve`,a)},activate(t){return Ae.post(`/music-loans/${t}/activate`)},return(t){return Ae.post(`/music-loans/${t}/return`)},decline(t,a={}){return Ae.post(`/music-loans/${t}/decline`,a)}};function Gs({filters:t,onChange:a,stats:l,showForm:c,sort:I,onSortChange:B,piecesCount:A,loading:p,partnerCount:j,partnerNames:n,facetOptions:v,showLibrarianStats:D=!0,kindOptions:L}){const{status:k,inSetlist:x,needsInstruments:z}=t,{sortBy:y,sortDir:b}=I;return e.jsxs(e.Fragment,{children:[l&&D&&e.jsxs("div",{"data-tour":"music-stats",className:`grid gap-3 mb-4 ${(()=>{const C=[l.enriching>0,j!=null,l.needsInstruments>0].filter(Boolean).length;return["grid-cols-3","grid-cols-4","grid-cols-5","grid-cols-6"][Math.min(C,3)]})()}`,children:[[{label:"Total pieces",value:l.total,filter:""},{label:"Checked out",value:l.checkedOut,filter:"checked_out"}].map(({label:C,value:$,filter:_})=>{const f=k===_&&!x;return e.jsxs("button",{type:"button",onClick:()=>{a("inSetlist",!1),a("status",f?"":_)},className:`rounded-xl border px-4 py-3 text-left transition-colors focus:outline-none focus:ring-2 focus:ring-band-500 focus:ring-offset-2 ${f?"bg-band-500 border-band-500 text-white":"bg-white border-gray-200 hover:border-band-300"}`,children:[e.jsx("p",{className:`text-2xl font-bold ${f?"text-white":"text-gray-900"}`,children:$}),e.jsx("p",{className:`text-xs mt-0.5 ${f?"text-white/80":"text-gray-400"}`,children:C})]},C)}),e.jsxs("button",{type:"button",onClick:()=>{a("status",""),a("inSetlist",!x)},className:`rounded-xl border px-4 py-3 text-left transition-colors focus:outline-none focus:ring-2 focus:ring-band-500 focus:ring-offset-2 ${x?"bg-amber-500 border-amber-500 text-white":"bg-white border-gray-200 hover:border-amber-300"}`,children:[e.jsx("p",{className:`text-2xl font-bold ${x?"text-white":"text-gray-900"}`,children:l.inSetlist}),e.jsx("p",{className:`text-xs mt-0.5 ${x?"text-white/80":"text-gray-400"}`,children:"Requested"})]}),l.enriching>0&&e.jsxs("div",{className:"rounded-xl border border-blue-200 bg-blue-50 px-4 py-3 text-left",children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:l.enriching}),e.jsx("p",{className:"text-xs mt-0.5 text-blue-400",children:"Enriching"})]}),l.needsInstruments>0&&e.jsxs("button",{type:"button",onClick:()=>{a("status",""),a("inSetlist",!1),a("needsInstruments",!z)},className:`rounded-xl border px-4 py-3 text-left transition-colors focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 ${z?"bg-amber-500 border-amber-500 text-white":"bg-white border-gray-200 hover:border-amber-300"}`,children:[e.jsx("p",{className:`text-2xl font-bold ${z?"text-white":"text-gray-900"}`,children:l.needsInstruments}),e.jsx("p",{className:`text-xs mt-0.5 ${z?"text-white/80":"text-gray-400"}`,children:"Not yet scanned"})]}),j!=null&&e.jsxs("div",{className:"rounded-xl border border-purple-200 bg-white px-4 py-3 text-left",children:[e.jsx("p",{className:"text-2xl font-bold text-gray-900",children:j}),e.jsx("p",{className:"text-xs mt-0.5 text-gray-400",children:"Partner pieces"})]})]}),e.jsx("div",{"data-tour":"music-filters",className:c?"hidden":"",children:e.jsx(Cs,{showStatus:D,filters:t,onChange:a,classifications:v?.classifications??l?.classifications,themes:v?.themes??l?.themes,grades:v?.grades,partnerNames:n,showClassification:l?.classifications?.length>0,showLastPerformed:!0,showKind:!0,kindOptions:L})}),!p&&A>0&&!c&&e.jsxs("div",{className:"flex items-center gap-1 mb-3 text-xs text-gray-500",children:[e.jsxs("div",{"aria-live":"polite","aria-atomic":"true",className:"mr-2 font-medium text-gray-700",children:[A," result",A!==1?"s":""]}),e.jsx("span",{className:"mr-1",children:"Sort:"}),[{key:"title",label:"Title"},{key:"grade",label:"Grade"},{key:"lastPerformed",label:"Last Performed"},{key:"createdAt",label:"Date Added"}].map(({key:C,label:$})=>{const _=y===C,f=_&&b==="asc"?"desc":"asc";return e.jsxs("button",{type:"button",onClick:()=>B(C,_?f:"asc"),className:`px-2 py-0.5 rounded transition-colors ${_?"bg-band-100 text-band-700 font-semibold":"hover:bg-gray-100 text-gray-500"}`,children:[$,_&&e.jsx("span",{className:"ml-0.5","aria-label":b==="asc"?"sorted ascending":"sorted descending",children:b==="asc"?"â
1":"â"})]},C)})]})]})}const rt=()=>e.jsxs("svg",{className:"animate-spin motion-reduce:!animate-spin h-5 w-5 shrink-0 text-band-600",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"})]}),Ks=()=>e.jsxs("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 20 20","aria-hidden":"true",children:[e.jsx("circle",{cx:"7",cy:"5",r:"1.5"}),e.jsx("circle",{cx:"7",cy:"10",r:"1.5"}),e.jsx("circle",{cx:"7",cy:"15",r:"1.5"}),e.jsx("circle",{cx:"13",cy:"5",r:"1.5"}),e.jsx("circle",{cx:"13",cy:"10",r:"1.5"}),e.jsx("circle",{cx:"13",cy:"15",r:"1.5"})]});let Ys=1;const Pe=t=>({key:`k${Ys++}`,...t});function qt({onCreated:t,onCancel:a,bare:l=!1,initial:c=null}){const I=l?"":"bg-white rounded-xl border border-gray-200 p-6 mb-4",B=ke(o=>o.showError),A=ke(o=>o.showSuccess),[p,j]=r.useState(c?"confirm":"ask"),[n,v]=r.useState(c?.title||""),[D,L]=r.useState(c?.arrangers||""),[k,x]=r.useState(c?.publisher||""),[z,y]=r.useState(c?.classification||""),[b,C]=r.useState(""),[$,_]=r.useState(""),[f,G]=r.useState(!1),[F,P]=r.useState(()=>c?{found:"yes",note:null,sources:[],fromPhoto:!0,filled:[]}:null),[Z,K]=r.useState(()=>(c?.partBooks||[]).map(o=>Pe({rawLabel:o.rawLabel,own:!o.optional,instrumentName:o.instrumentName,isPerformer:o.isPerformer,optional:!!o.optional}))),[ce,ee]=r.useState(()=>(c?.titles||[]).map(o=>Pe(o))),[g,q]=r.useState(""),[E,re]=r.useState(""),[ne,ae]=r.useState(!1),[ue,m]=r.useState(!1),W=r.useRef(null);r.useEffect(()=>{W.current?.scrollIntoView?.({behavior:"smooth",block:"nearest"})},[]);const J=(c?.titles||[]).length,de=(c?.partBooks||[]).length,H=!!c&&(!J||de<3);function we(){return G(!0),P(o=>({...o,fillFailed:!1})),U.bookLookup({title:n.trim()||c.title,arrangers:D.trim()||c.arrangers||"",publisher:k.trim()||c.publisher||""}).then(o=>{const T=[];!J&&(o.titles||[]).length&&(ee(u=>u.length?u:o.titles.map(V=>Pe(V))),T.push("titles")),de<3&&(o.partBooks||[]).length&&(K(u=>{const V=new Set(u.map(ge=>ge.rawLabel.toLowerCase().replace(/\s+/g," ").trim())),me=o.partBooks.filter(ge=>!V.has(String(ge.rawLabel).toLowerCase().replace(/\s+/g," ").trim())).map(ge=>Pe({rawLabel:ge.rawLabel,own:!ge.optional,instrumentName:ge.instrumentName,isPerformer:ge.isPerformer,optional:!!ge.optional}));return[...u,...me]}),T.push("other part books")),x(u=>u||o.publisher||""),y(u=>u||o.classification||""),L(u=>u||o.arrangers||""),C(o.publishedDate||""),_(o.summary||""),P(u=>({...u,filled:T,sources:o.sources||[],fillFailed:T.length===0}))}).catch(()=>P(o=>({...o,fillFailed:!0}))).finally(()=>G(!1))}r.useEffect(()=>{H&&we()},[]);const ie=Fs({items:ce,onReorder:ee,getLabel:o=>o.title||"this title"});async function pe(o,{skipCatalog:T=!1}={}){if(o?.preventDefault?.(),!!n.trim()){G(!0);try{const u=await U.bookLookup({title:n.trim(),arrangers:D.trim(),publisher:k.trim(),...T?{skipCatalog:!0}:{}});v(u.title||n.trim()),L(u.arrangers||D),x(u.publisher||k),y(u.classification||z),C(u.publishedDate||""),_(u.summary||""),K((u.partBooks||[]).map(V=>Pe({rawLabel:V.rawLabel,own:!V.optional,instrumentName:V.instrumentName,isPerformer:V.isPerformer,optional:!!V.optional}))),ee((u.titles||[]).map(V=>Pe(V))),P({found:u.found,note:u.note,sources:u.sources||[],fromCatalog:!!u.fromCatalog}),m(!1),j("confirm")}catch(u){B(u?.message||"The lookup did not work this time. Try again, or type the book in yourself.")}finally{G(!1)}}}function X(){F&&(K([]),ee([]),_(""),C("")),P(null),j("confirm")}function ye(){const o=g.trim();o&&(Z.some(T=>T.rawLabel.toLowerCase()===o.toLowerCase())||K(T=>[...T,Pe({rawLabel:o,own:!0,instrumentName:null,isPerformer:!0})]),q(""))}function Ce(){const o=E.trim();o&&(ee(T=>[...T,Pe({title:o,composers:"",arrangers:"",performanceTime:""})]),re(""))}const w=(o,T,u)=>ee(V=>V.map(me=>me.key===o?{...me,[T]:u}:me)),Q=Z.filter(o=>o.own),Y=ce.filter(o=>String(o.title||"").trim()),le=n.trim()&&!ne&&!(f&&p==="confirm");async function oe(o){if(o.preventDefault(),!!le){ae(!0);try{const T=await U.createBook({title:n.trim(),arrangers:D.trim(),publisher:k.trim(),publishedDate:b.trim(),summary:$.trim(),classification:z||null,partBooks:Q.map(u=>({rawLabel:u.rawLabel}
1)),allPartBooks:Z.map(u=>({rawLabel:u.rawLabel,optional:!!u.optional})),titles:Y.map(u=>({title:u.title.trim(),composers:u.composers||"",arrangers:u.arrangers||"",performanceTime:u.performanceTime||""}))});A(Y.length?`Book added with ${Y.length} ${Y.length===1?"title":"titles"}.`:"Book added. Open it to add its titles."),t?.(T)}catch(T){B(T?.message||Se)}finally{ae(!1)}}}const s=f&&p==="confirm"&&!!F?.fromPhoto,O=ue||p==="confirm"&&!!(D||k)?e.jsxs("div",{className:"max-w-2xl mt-4",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"The arranger and the publisher are on the cover. They help find the right book."}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(se,{label:"Arranger",value:D,onChange:o=>L(o.target.value),maxLength:500}),e.jsx(se,{label:"Publisher",value:k,onChange:o=>x(o.target.value),maxLength:300})]})]}):e.jsx(R,{type:"button",variant:"ghost",size:"md",className:"!px-0 mt-2","aria-expanded":!1,onClick:()=>m(!0),children:"More options"});return p==="ask"?e.jsxs("form",{ref:W,onSubmit:pe,className:I,"data-testid":"new-book-ask",children:[!l&&e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4",children:"New book"}),e.jsx("p",{className:"text-sm text-gray-600 mb-4 max-w-2xl",children:"A book is a collection your band owns as printed part books: one book for each part, the same titles in every book. Type its name and we will look up what is in it."}),e.jsx("div",{className:"max-w-2xl",children:e.jsx(se,{label:"Name of the book",placeholder:"e.g. Classy Classics for Brass Quintet",value:n,onChange:o=>v(o.target.value),maxLength:300,required:!0,autoFocus:!0})}),O,e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2 mt-4",children:[e.jsx(R,{type:"submit",variant:"ai",isLoading:f,disabled:!n.trim(),children:"Look it up"}),e.jsx(R,{type:"button",variant:"ghost",onClick:a,disabled:f,children:"Cancel"}),e.jsx(R,{type:"button",variant:"ghost",className:"ml-auto",onClick:X,disabled:f||!n.trim(),children:"Type it in myself"})]}),f&&e.jsx("p",{className:"text-sm text-gray-600 mt-3","aria-live":"polite",children:"Looking it up. This can take a minute."})]}):e.jsxs("form",{ref:W,onSubmit:oe,className:I,"data-testid":"new-book-confirm",children:[!l&&e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4",children:"New book"}),s&&e.jsxs("div",{role:"status",className:"flex items-start gap-3 rounded-xl border border-band-300 bg-band-50 p-4 mb-4 max-w-2xl","data-testid":"book-filling",children:[e.jsx(rt,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-gray-900",children:"Still working: looking up the rest of this book."}),e.jsx("p",{className:"text-sm text-gray-700",children:"This takes about a minute. The titles and the other part books will appear below when it is done."})]})]}),F&&F.fromPhoto&&e.jsxs("p",{className:"text-sm text-gray-700 mb-4 max-w-2xl","aria-live":"polite","data-testid":"book-from-photo",children:["We read this from your photo. Check it against the cover before you create it.",!f&&F.filled?.length>0&&e.jsxs("span",{className:"block mt-1",children:["The photo did not show the ",F.filled.join(" and the "),", so we looked ",F.filled.length>1?"those":"them"," up. Check them against the cover: a title or the order can be a little different."]}),!f&&F.fillFailed&&e.jsxs("span",{className:"block mt-1","data-testid":"book-fill-failed",children:["We could not look up the rest this time. Try again, or add the titles and part books from the book yourself."," ",e.jsx(R,{type:"button",variant:"ai",size:"md",onClick:we,children:"Try again"})]})]}),F&&F.fromCatalog&&e.jsxs("div",{className:"mb-4 max-w-2xl flex flex-wrap items-center gap-x-3 gap-y-1","aria-live":"polite","data-testid":"book-from-catalog",children:[e.jsx("p",{className:"text-sm text-gray-700 flex-1 min-w-[16rem]",children:"Another band has already added this book, so this is the list they checked. Check it against your cover before you create it."}),e.jsx(R,{type:"button",variant:"ai",size:"md",isLoading:f,onClick:()=>pe(null,{skipCatalog:!0}),children:"Look it up on the web instead"})]}),F&&!F.fromCatalog&&!F.fromPhoto&&F.found!=="no"&&e.jsxs("p",{className:"text-sm text-gray-700 mb-4 max-w-2xl","aria-live":"polite",children:["Here is what we found. Check it against the cover before you create it. A title or the order
1can be a little different, and some titles may be missing.",F.sources.length>0&&e.jsxs("span",{className:"block text-sm text-gray-600 mt-1",children:["Found on ",F.sources.join(", "),"."]})]}),F&&F.found==="no"&&e.jsx("p",{className:"bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-900 p-3 mb-4 max-w-2xl","aria-live":"polite",children:"We could not find what is in this book. Type its part books and titles below from the cover."}),e.jsxs("div",{className:"max-w-2xl",children:[e.jsx(se,{label:"Name of the book",value:n,onChange:o=>v(o.target.value),maxLength:300,required:!0}),e.jsx("div",{className:"mt-3 sm:w-80",children:e.jsx(De,{label:"Classification",hint:"Every title in the book gets it",value:z,onChange:o=>y(o.target.value),options:[{value:"",label:"Select classification"},{value:"concert",label:"Concert Band"},{value:"orchestra",label:"Orchestra"},{value:"marching",label:"Marching Band"},{value:"jazz",label:"Jazz Ensemble"}]})})]}),O,e.jsx("h4",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mt-6 mb-1",children:"Part books"}),e.jsxs("p",{className:"text-sm text-gray-600 mb-2",children:[F&&Z.length>0?F.fromPhoto&&!F.filled?.includes("other part books")?"These are the part books named in your photo. Add any others your band has.":F.fromCatalog?"This lists every part book that comes with the set. Untick any book you donât have. Books sold separately start unticked; tick them if you own them.":"The lookup lists every book the publisher sells. Untick any book you donât have. Books sold separately start unticked; tick them if you own them.":"Add each part book your band has."," ","You can count your copies after it is created."]}),Z.length===0&&!s&&e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"None yet. Add each part book printed on the cover."}),e.jsx("ul",{className:"max-w-2xl",children:Z.map(o=>e.jsx("li",{children:e.jsxs("label",{className:"flex items-center gap-3 min-h-[44px] text-base text-gray-900 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:o.own,onChange:()=>K(T=>T.map(u=>u.key===o.key?{...u,own:!u.own}:u)),className:"h-5 w-5 rounded border-gray-300 text-band-600 focus:ring-band-500"}),e.jsxs("span",{children:[o.rawLabel,o.optional&&e.jsx("span",{className:"text-sm text-gray-600",children:" · sold separately"})]})]})},o.key))}),s&&de<3&&e.jsxs("p",{className:"flex items-center gap-2 text-sm text-gray-700 mt-1 mb-2","data-testid":"book-parts-waiting",children:[e.jsx(rt,{})," Looking up the other part booksâ¦"]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 max-w-2xl mt-1",children:[e.jsx("div",{className:"flex-1 min-w-[12rem]",children:e.jsx(se,{label:"Add a part book",placeholder:"e.g. 2nd Bb Trumpet",value:g,onChange:o=>q(o.target.value),maxLength:200,onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),ye())}})}),e.jsx(R,{type:"button",variant:"secondary",onClick:ye,disabled:!g.trim(),children:"Add part book"})]}),e.jsx("h4",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mt-6 mb-1",children:"Titles in the book"}),e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"In the order the book prints them. Drag a title to move it."}),ce.length===0&&!s&&e.jsx("p",{className:"text-sm text-gray-600 mb-2",children:"None yet. Add each title from the cover or the contents page."}),ce.length===0&&s&&e.jsxs("p",{className:"flex items-center gap-2 text-sm text-gray-700 mb-2","data-testid":"book-titles-waiting",children:[e.jsx(rt,{})," Looking up the titlesâ¦"]}),e.jsx("ol",{className:"space-y-2 max-w-3xl","aria-label":"Titles in book order",children:ce.map((o,T)=>e.jsxs("li",{...ie.tapMode?ie.getRowProps(T):{},draggable:!ie.tapMode,onDragStart:()=>ie.handleDragStart(T),onDragOver:u=>ie.handleDragOver(u,T),onDrop:u=>ie.handleDrop(u,T),onDragEnd:ie.handleDragEnd,className:`flex flex-wrap items-end gap-2 rounded-lg border px-2 py-2 ${ie.picked===T?"ring-2 ring-band-500 bg-band-50 border-band-400":ie.dragOverIndex===T?"border-band-400 bg-band-50":"border-gray-200"}`,children:[e.jsx("span",{className:"shrink-0 text-gray-400 cursor-grab self
1-center",...ie.tapMode?ie.getHandleProps(T):{"aria-hidden":"true"},children:e.jsx(Ks,{})}),e.jsxs("span",{className:"shrink-0 w-6 text-sm text-gray-600 tabular-nums self-center","aria-hidden":"true",children:[T+1,"."]}),e.jsx("div",{className:"flex-1 min-w-[12rem]",children:e.jsx(se,{"aria-label":`Title ${T+1}`,value:o.title,onChange:u=>w(o.key,"title",u.target.value),maxLength:300})}),e.jsx(R,{type:"button",variant:"ghost",size:"md",onClick:()=>ee(u=>u.filter(V=>V.key!==o.key)),"aria-label":`Remove ${o.title||`title ${T+1}`}`,children:"Remove"}),o.composers&&e.jsx("p",{className:"w-full text-sm text-gray-600 pl-12",children:o.composers})]},o.key))}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 max-w-2xl mt-2",children:[e.jsx("div",{className:"flex-1 min-w-[12rem]",children:e.jsx(se,{label:"Add a title",placeholder:"e.g. William Tell Overture",value:E,onChange:o=>re(o.target.value),maxLength:300,onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),Ce())}})}),e.jsx(R,{type:"button",variant:"secondary",onClick:Ce,disabled:!E.trim(),children:"Add title"})]}),e.jsxs("p",{className:"text-sm text-gray-700 mt-6","aria-live":"polite",children:[Q.length," part ",Q.length===1?"book":"books"," · ",Y.length," ",Y.length===1?"title":"titles",". Each title can go on a program like any other piece."]}),f&&e.jsx("p",{className:"text-sm text-gray-700 mt-2","aria-live":"polite",children:"Create is waiting for the lookup to finish."}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(R,{type:"submit",variant:"primary",isLoading:ne,disabled:!le,title:f?"Waiting for the lookup to finish":void 0,children:"Create"}),e.jsx(R,{type:"button",variant:"ghost",onClick:a,disabled:ne,children:"Cancel"}),e.jsx(R,{type:"button",variant:"ghost",className:"ml-auto",onClick:()=>j("ask"),disabled:ne,children:"Back"})]})]})}const Ve=["flute","clarinet","saxophone","double reed","horn","trumpet","trombone","euphonium","tuba","percussion","string","keyboard","vocal"],Js=Array.from({length:11},(t,a)=>1+a*.5),Lt={title:"",composers:"",arrangers:"",grade:"",style:"",classification:"",theme:"",publishedDate:"",ownership:"own",borrowedFrom:"",format:"physical",status:"checked_in",folderNumber:"",performanceTime:"",recordingUrl:"",digitalUrl:"",summary:"",directorsNotes:"",librarianNotes:"",publisher:"",purchaseDate:"",cost:""},Qs={grade:"Grade",style:"Style",classification:"Classification",theme:"Theme",publisher:"Publisher",publishedDate:"Published Date",performanceTime:"Performance Time",summary:"Summary",recordingUrl:"Recording URL"};function It(t){const a={};for(const l of t){const c=l.family??"other";a[c]||(a[c]=[]),a[c].push(l)}return a}function Xs(t){return{title:t.title,composers:t.composers??"",arrangers:t.arrangers??"",grade:t.grade!=null?String(t.grade):"",style:t.style??"",classification:t.classification??"",theme:t.theme??"",publishedDate:t.publishedDate??"",ownership:t.ownership??"own",borrowedFrom:t.borrowedFrom??"",format:t.format??"physical",status:t.status??"checked_in",folderNumber:t.folderNumber??"",performanceTime:t.performanceTime??"",recordingUrl:t.recordingUrl??"",digitalUrl:t.digitalUrl??"",summary:t.summary??"",directorsNotes:t.directorsNotes??"",librarianNotes:t.librarianNotes??"",publisher:t.publisher??"",purchaseDate:t.purchaseDate??"",cost:t.cost!=null?String(t.cost):""}}function Wt({editTarget:t,onSave:a,onCancel:l,onDelete:c,canManage:I,isSaving:B}){const{showSuccess:A,showError:p}=ke(),j=r.useRef(null),[n,v]=r.useState(Lt),[D,L]=r.useState(new Set),[k,x]=r.useState([]),[z,y]=r.useState(!1),[b,C]=r.useState(!1),[$,_]=r.useState(!1),[f,G]=r.useState(null),[F,P]=r.useState([]),[Z,K]=r.useState(!1),[ce,ee]=r.useState(!1),[g,q]=r.useState(null),[E,re]=r.useState(new Set),[ne,ae]=r.useState(!1),ue=r.useRef(null),m=r.useRef(null),W=r.useRef(null);r.useEffect(()=>{if(t){const s=Xs(t);v(s);const N=new Set(t.instruments.map(o=>o.id));L(N),ue.current=s,m.current=N;const O=!!(t.publishedDate||t.publisher||t.purchaseDate||t.cost!=null||t.digitalUrl||t.summary||t.directorsNotes||t.librarianNotes);C(O)}else v(Lt),L(new Set),ue.current=null,m.current=null,C(!1),U.nextFolderNumber().then(s=>{s?.nextNumber&&v(N=>({...N,folderNumber:s.nextNumber}))}).catch(ps("folder-number suggestion; the field stays editable"));G(null),re(new Set),ae(!1),de(),requestAnimationFrame(()=>j.current?.scrollIntoView({behavior:"smooth",block:"start"}))},[t]);function J(s,N){if(!N?.length)return s;const O=new Set(s.map(o=>o.id));return[...s,...N.filter(o=>o&&o.id&&!O.has(o.id))]}async function de(){y(!0);try{const s=await Ct.list("member");x(J(s,t?.instruments))}catch{p("Failed to load instruments")}finally{y(!1)}}function H(s,N){v(O=>({...O,[s]:N}))}function we(s){L(N=>{const O=new Set(N);return O.has(s)?O.delete(s):O.add(s),O})}function ie(s){if(v(N=>({...N,title:s})),q(null),W.current&&clearTimeout(W.current),s.length<3){P([]),K(!1);return}W.current=setTimeout(async()=>{ee(!0);try{const N=await U.masterSearch(s);P(N),K(N.length>0)}catch{P([])}finally{ee(!1)}},300)}async function pe(s){if(K(!1),q(s.id),v(N=>({...N,title:s.title||N.title,composers:s.composers||N.composers||"",arrangers:s.arrangers||N.arrangers||"",grade:s.grade!=null?String(s.grade):N.grade||"",style:s.style||N.style||"",classification:s.classification||N.classification||"",theme:s.theme||N.theme||"",publisher:s.publisher||N.publisher||"",publishedDate:s.publishedDate||N.publishedDate||"",performanceTime:s.performanceTime||N.performanceTime||"",summary:s.summary||N.summary||"",recordingUrl:s.recordingUrl||N.recordingUrl||""})),s.instruments?.length>0)try{const N=await Ct.list("member"),O=J(N,s.instruments);x(O);const o=new Set;for(const T of s.instruments){const u=O.find(V=>V.id===T.id);u&&o.add(u.id)}if(o.size>0&&L(T=>{const u=new Set(T);return o.forEach(V=>u.add(V)),u}),s.featuredInstruments?.length>0){const T=new Set;for(const u of s.featuredInstruments){const V=O.find(me=>me.id===u.id);V&&T.add(V.id)}re(T)}}catch{}(s.publisher||s.publishedDate||s.summary)&&C(!0),A("Populated from master library")}const X=t?.kind==="book";async function ye(){if(n.title.trim()){_(!0),G(null);try{const s=X?await U.bookLookup({title:n.title,arrangers:n.arrangers||"",publisher:n.publisher||"",skipCatalog:!0}):await U.lookup(n.title,n.composers,n.arrangers),N=X?{classification:s.classification||null,publisher:s.publisher||null,publishedDate:s.publishedDate||null,summary:s.summary||null}:{grade:s.grade!=null?String(s.grade):null,style:s.style||null,classification:s.classification||null,theme:s.theme||null,publisher:s.publisher||null,publishedDate:s.publishedDate||null,performanceTime:s.performanceTime||null,summary:s.summary||null,recordingUrl:s.recordingUrl||null},O={},o=[];for(const[T,u]of Object.entries(N)){if(!u)continue;const V=n[T];!V||V===""?O[T]=u:V!==u&&o.push({key:T,label:Qs[T],oldVal:V,newVal:u,accepted:!1})}Object.keys(O).length>0&&v(T=>({...T,...O})),(O.publisher||O.publishedDate||O.summary)&&C(!0),o.length>0?G({changes:o}
1):A(X&&Object.keys(O).length===0?"Nothing new found for this book.":X&&!N.classification?"Details fetched. We could not tell the classification, so choose it yourself, then save.":"Details fetched â review and save")}catch(s){p(s.message||"Fetch failed")}finally{_(!1)}}}function Ce(s){G(O=>{const o=O.changes.map(u=>u.key===s?{...u,accepted:!0}:u);return o.filter(u=>!u.accepted).length===0&&setTimeout(()=>G(null),0),{changes:o}});const N=f.changes.find(O=>O.key===s);N&&H(s,N.newVal)}function w(){v(s=>{const N={};for(const O of f.changes)O.accepted||(N[O.key]=O.newVal);return{...s,...N}}),G(null),A("All changes accepted")}function Q(){G(null),A("Details fetched â review and save")}function Y(s){s.preventDefault(),n.title.trim()&&a({title:n.title.trim(),composers:n.composers||null,arrangers:n.arrangers||null,grade:n.grade?parseFloat(n.grade):null,style:n.style||null,classification:n.classification||null,theme:n.theme||null,publishedDate:n.publishedDate||null,ownership:n.ownership,borrowedFrom:n.ownership==="borrowed"&&n.borrowedFrom||null,format:n.format,status:n.format==="digital"?"checked_in":n.status,folderNumber:n.folderNumber||null,performanceTime:n.performanceTime||null,recordingUrl:n.recordingUrl||null,digitalUrl:n.digitalUrl||null,summary:n.summary||null,directorsNotes:n.directorsNotes||null,librarianNotes:n.librarianNotes||null,publisher:n.publisher||null,purchaseDate:n.purchaseDate||null,cost:n.cost!==""?parseFloat(n.cost):null,instrumentIds:t?.bookId?void 0:Array.from(D),masterMusicId:g||void 0})}const le=!t||(()=>{const s=ue.current;if(!s)return!0;for(const O of Object.keys(s))if(n[O]!==s[O])return!0;const N=m.current;if(N.size!==D.size)return!0;for(const O of D)if(!N.has(O))return!0;return!1})(),oe=It(k);return Ve.filter(s=>oe[s]),Object.keys(oe).filter(s=>!Ve.includes(s)),e.jsxs("div",{ref:j,className:"bg-white rounded-xl border border-gray-200 p-6 mb-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-4",children:t?"Edit Piece":"New Music"}),e.jsxs("div",{className:"flex gap-2 pt-2 mb-4",children:[e.jsx(R,{type:"button",isLoading:B,disabled:!le,size:"sm",onClick:Y,children:t?"Save changes":"Create"}),e.jsx(R,{type:"button",variant:"secondary",size:"sm",onClick:l,children:"Cancel"}),t&&I&&e.jsx(R,{type:"button",variant:"danger",size:"sm",className:"ml-auto",onClick:()=>c(t),children:"Delete"})]}),e.jsxs("form",{onSubmit:Y,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 relative",children:[e.jsx(se,{label:"Title",placeholder:"Symphony No. 5",value:n.title,onChange:s=>ie(s.target.value),onFocus:()=>F.length>0&&K(!0),onBlur:()=>setTimeout(()=>K(!1),200),required:!0}),g&&e.jsx("span",{className:"text-xs text-green-600 mt-1 block",children:"Linked to master library"}),Z&&e.jsx("div",{className:"absolute z-50 left-0 right-0 top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto",children:F.map(s=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 hover:bg-band-50 border-b border-gray-100 last:border-0",onClick:()=>pe(s),children:[e.jsx("div",{className:"font-medium text-sm text-gray-900",children:s.title}),e.jsx("div",{className:"text-xs text-gray-500",children:[s.composers,s.arrangers&&`arr. ${s.arrangers}`,s.grade&&`Grade ${s.grade}`,s.style].filter(Boolean).join(" · ")}),s.verified&&e.jsx("span",{className:"text-xs text-green-600",children:"Verified"})]},s.id))}),ce&&e.jsx("div",{className:"absolute right-3 top-9",children:e.jsx("div",{className:"animate-spin motion-reduce:!animate-spin h-4 w-4 border-2 border-band-500 border-t-transparent rounded-full"})})]}),e.jsx(se,{label:"Composers",placeholder:"Beethoven, Brahms",value:n.composers,onChange:s=>H("composers",s.target.value)}),e.jsx(se,{label:"Arrangers",placeholder:"Smith",value:n.arrangers,onChange:s=>H("arrangers",s.target.value)}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(R,{type:"button",variant:"ai",size:"sm",disabled:!n.title.trim()||$,isLoading:$,onClick:ye,children:"Fetch details"}),e.jsx("p",{role:$?"status":void 0,className:"text-sm text-gray-600 mt-1",children:$?X?"Searching for details. This can take up to a minute.":"Searching for details â this can take up to half a minute.":X?"Searches the web for this bookâs classification, publisher and summary. Every title in the book takes the classification when you save.":"Searches the web for grade, style, publisher, summary, performance time, and recording link."})]}),f&&e.jsxs("div",{className:"sm:col-span-2 rounded-lg border border-amber-200 bg-amber-50 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:"Review changes to existing fields"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",onClick:w,className:"px-2.5 py-1 rounded text-xs font-medium bg-amber-600 text-white hover:bg-amber-700 transition-colors",children:"Accept All"}),e.jsx("button",{type:"button",onClick:Q,className:"px-2.5 py-1 rounded text-xs font-medium border border-amber-300 text-amber-700 hover:bg-amber-100 transition-colors",children:"Dismiss"})]})]}),e.jsx("div",{className:"space-y-2",children:f.changes.map(s=>e.jsx("div",{className:`rounded border px-3 py-2 text-sm ${s.accepted?"border-green-200 bg-green-50":"border-amber-200 bg-white"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs font-medium text-gray-500 mb-1",children:s.label}),e.jsx("p",{className:"text-xs text-gray-400 line-through truncate",children:s.oldVal}),e.jsx("p",{className:"text-xs text-gray-700 truncate",children:s.newVal})]}),s.accepted?e.jsx("span",{className:"shrink-0 text-xs text-green-600 font-medium",children:"Applied"}):e.jsx("button",{type:"button",onClick:()=>Ce(s.key),className:"shrink-0 px-2 py-0.5 rounded text-xs font-medium bg-brand-primary text-white hover:opacity-90 transition-opacity",children:"Accept"})]})},s.key))})]}
1),e.jsx(De,{label:"Grade",value:n.grade,onChange:s=>H("grade",s.target.value),options:[{value:"",label:"Select grade"},...Js.map(s=>({value:String(s),label:`Grade ${s}`}))]}),e.jsx(se,{label:"Style",placeholder:"Classical, March, Balladâ¦",value:n.style,onChange:s=>H("style",s.target.value)}),e.jsx(De,{label:"Classification",value:n.classification,onChange:s=>H("classification",s.target.value),options:[{value:"",label:"Select classification"},{value:"concert",label:"Concert Band"},{value:"orchestra",label:"Orchestra"},{value:"marching",label:"Marching Band"},{value:"jazz",label:"Jazz Ensemble"}]}),e.jsx(se,{label:"Theme",placeholder:"Holiday, Patrioticâ¦",value:n.theme,onChange:s=>H("theme",s.target.value)}),e.jsx(De,{label:"Ownership",value:n.ownership,onChange:s=>H("ownership",s.target.value),options:[{value:"own",label:"Own"},{value:"borrowed",label:"Borrowed"}]}),n.ownership==="borrowed"&&e.jsx(se,{label:"Borrowed From",placeholder:"Name or organization",value:n.borrowedFrom,onChange:s=>H("borrowedFrom",s.target.value)}),e.jsx(De,{label:"Format",value:n.format,onChange:s=>H("format",s.target.value),options:[{value:"physical",label:"Physical (folders)"},{value:"digital",label:"Digital (files / PDFs)"},{value:"both",label:"Both physical and digital"}]}),n.format!=="digital"&&e.jsx(De,{label:"Status",value:n.status,onChange:s=>H("status",s.target.value),options:[{value:"checked_in",label:"Checked In"},{value:"checked_out",label:"Checked Out"}]}),e.jsx(se,{label:"Performance Time",placeholder:"4:30",value:n.performanceTime,onChange:s=>H("performanceTime",s.target.value)}),e.jsx(se,{label:"Folder Number",placeholder:"47",value:n.folderNumber,onChange:s=>H("folderNumber",s.target.value)}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Recording URL"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx("input",{type:"url",placeholder:"https://youtube.com/watch?v=â¦",value:n.recordingUrl,onChange:s=>H("recordingUrl",s.target.value),className:"flex-1 rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-band-400 focus:border-transparent"}),e.jsxs("a",{href:`https://www.youtube.com/results?search_query=${encodeURIComponent([n.title,n.composers,n.arrangers,"concert band"].filter(Boolean).join(" "))}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-300 bg-white text-sm text-gray-600 hover:bg-gray-50 hover:border-gray-400 whitespace-nowrap",title:"Search YouTube for a recording",children:[e.jsx("svg",{className:"h-4 w-4 text-red-500",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"})}),"Search YouTube"]})]})]})]}),e.jsx("div",{children:e.jsxs("button",{type:"button",onClick:()=>C(s=>!s),className:"text-xs text-gray-400 hover:text-gray-600 flex items-center gap-1",children:[e.jsx("span",{children:b?"â²":"â¼"}),b?"Hide advanced fields":"Show advanced fields"]})}),b&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(se,{label:"Published Date",placeholder:"1990",value:n.publishedDate,onChange:s=>H("publishedDate",s.target.value)}),e.jsx(se,{label:"Publisher",placeholder:"Hal Leonard",value:n.publisher,onChange:s=>H("publisher",s.target.value)}),e.jsx(se,{label:"Purchase Date",placeholder:"2023-05-01",value:n.purchaseDate,onChange:s=>H("purchaseDate",s.target.value)}),e.jsx(se,{label:"Cost ($)",type:"number",min:"0",step:"0.01",placeholder:"0.00",value:n.cost,onChange:s=>H("cost",s.target.value)}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(se,{label:"Digital Copy URL",placeholder:"https://â¦",value:n.digitalUrl,onChange:s=>H("digitalUrl",s.target.value)})}),[{key:"summary",label:"Summary",max:1e3},{key:"directorsNotes",label:"Director's Notes",max:2e3},{key:"librarianNotes",label:"Librarian's Notes",max:2e3}].map(({key:s,label:N,max:O})=>{const o=(n[s]||"").length,T=o>=O*.9;return e.jsxs("div",{className:"sm:col-span-2 flex flex-col gap-1",children:[e.jsx("label",{className:"text-sm font-medium text-gray-700",children:N}),e.jsx("textarea",{rows:3,maxLength:O,value:n[s],onChange:u=>H(s,u.target.value),className:"block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-band-500 focus:border-band-500 resize-y"}),T&&e.jsxs("p",{className:`text-xs text-right ${o>=O?"text-red-500":"text-gray-400"}`,children:[o,"/",O]})]},s)})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-sm font-medium text-gray-700",children:"Instruments"}),D.size>0&&!z&&e.jsx("button",{type:"button",onClick:()=>ae(s=>!s),className:"text-xs text-band-600 hover:text-band-700 font-medium",children:ne?"Show selected only":"Show all instruments"})]}),z?e.jsx("p",{className:"text-sm text-gray-400",children:"Loading instrumentsâ¦"}):k.length===0?e.jsx("p",{className:"text-sm text-gray-400",children:"No instruments available."}):(()=>{const N=ne||D.size===0?k:k.filter(u=>
1D.has(u.id)),O=It(N),o=Ve.filter(u=>O[u]),T=Object.keys(O).filter(u=>!Ve.includes(u));return e.jsx(Bs,{groups:[...o,...T].map(u=>({label:u,items:O[u].map(V=>({id:V.id,name:V.name}))})),selectedIds:D,highlightedIds:E,onToggle:we})})(),E.size>0&&e.jsx("p",{className:"text-xs text-gray-400 mt-2",children:"â
= Featured/solo instrument"})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(R,{type:"submit",isLoading:B,disabled:!le,size:"sm",children:t?"Save changes":"Create"}),e.jsx(R,{type:"button",variant:"secondary",size:"sm",onClick:l,children:"Cancel"}),t&&I&&e.jsx(R,{type:"button",variant:"danger",size:"sm",className:"ml-auto",onClick:()=>c(t),children:"Delete"})]})]})]})}const Zs={checked_in:["checked_out"],checked_out:["checked_in"]},Ht={checked_in:"green",checked_out:"yellow"},Vt={checked_in:"Checked In",checked_out:"Checked Out"},Ge={pending_purchase:{color:"amber",label:"Purchase Pending"},pending_delivery:{color:"amber",label:"Awaiting Delivery"},pending_donation:{color:"amber",label:"Donation Incoming"}};function er({pieces:t,loading:a,showForm:l,sort:c,canManage:I,canManagePerformances:B,canManageLoans:A,showStatus:p=!0,onEdit:j,onStatusChange:n,onTogglePerformance:v,onRequestLoan:D,onMarkReceived:L,onOpenCreate:k,onAddInstrumentsFromPhoto:x,onSaveInventory:z,onMarkAudited:y,onCountAsPrinted:b,allPerformances:C,expandedPieces:$,onTogglePiece:_,auditCache:f,partsCache:G,hasActiveFilters:F,inventoryPieceId:P,onBookChanged:Z}){const{sortBy:K,sortDir:ce}=c;if(a)return e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((g,q)=>e.jsx(Ut,{lines:3},q))});if(t.length===0&&!l)return e.jsx(lt,{variant:"illustration",icon:e.jsx(zs,{}),title:F?"No pieces match your filters":"No music in the library yet",description:F?"Try adjusting your filters.":void 0,action:I&&
1!F&&e.jsx(R,{onClick:k,children:"Create first piece"})});const ee=[...t].sort((g,q)=>{let E=g[K]??"",re=q[K]??"";if(K==="grade"&&(E=Number(E)||0,re=Number(re)||0),K==="lastPerformed"){if(!E&&!re)return 0;if(!E)return 1;if(!re)return-1}const ne=typeof E=="number"?E-re:String(E).localeCompare(String(re));return ce==="asc"?ne:-ne});return e.jsx("div",{"data-tour":"music-list",className:"space-y-2",children:ee.map(g=>e.jsxs("div",{"data-piece-id":g.id,className:`bg-white rounded-xl border px-5 py-4 flex flex-col gap-2 cursor-pointer scroll-mt-4 ${P===g.id?"border-band-400 ring-2 ring-band-200":"border-gray-200"}`,role:"button",tabIndex:0,"aria-expanded":$.has(g.id),"aria-label":`View details for ${g.title}`,onClick:()=>_(g.id),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),_(g.id))},children:[e.jsxs("div",{className:"flex items-start gap-3 text-left w-full",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[g.folderNumber&&e.jsxs("span",{className:"inline-flex items-center px-2 py-0.5 rounded border border-gray-300 bg-gray-100 text-gray-900 font-mono font-bold text-sm tabular-nums leading-tight",children:["#",g.folderNumber]}),e.jsx("p",{className:"font-medium text-gray-900",children:g.title}),g.kind==="book"&&e.jsxs(he,{color:"blue",children:["Book · ",g.titleCount??0," ",g.titleCount===1?"title":"titles"]}),g.bookId&&g.bookTitle&&e.jsx("span",{className:"inline-block max-w-[14rem] truncate align-bottom",title:g.bookTitle,children:e.jsxs(he,{color:"gray",children:["In ",g.bookTitle]})}),g.grade!=null&&e.jsxs(he,{color:"gray",children:["Grade ",g.grade]}),p&&g.format!=="digital"&&!g.bookId&&e.jsx(he,{color:Ht[g.status]??"gray",children:Vt[g.status]??g.status}),g.format==="digital"&&e.jsx(he,{color:"blue",children:"Digital"}),g.format==="both"&&e.jsx(he,{color:"blue",children:"Physical + Digital"}),g.ownership==="borrowed"&&e.jsx(he,{color:"yellow",children:"Borrowed"}),Ge[g.acquisitionStatus]&&e.jsx(he,{color:Ge[g.acquisitionStatus].color,children:Ge[g.acquisitionStatus].label}),g.enrichmentStatus==="pending"&&e.jsx(he,{color:"blue",children:"Enriching..."}),g.enrichmentStatus==="processing"&&e.jsx(he,{color:"blue",children:"Enriching..."}),g.enrichmentStatus==="failed"&&e.jsx(he,{color:"red",children:"Enrichment Failed"}),g.isPartner&&e.jsx(he,{color:"purple",children:g.orgName})]}),(g.composers||g.arrangers||g.lastPerformed!==void 0)&&e.jsx("p",{className:"text-sm text-gray-400 mt-0.5",children:[g.composers&&`Composers: ${g.composers}`,g.arrangers&&`Arr: ${g.arrangers}`,g.lastPerformed!==void 0&&(g.lastPerformed?`Last performed: ${_e(g.lastPerformed)}`:"Never performed")].filter(Boolean).join(" · ")})]}),e.jsx("span",{className:"text-gray-300 shrink-0 mt-0.5 text-sm",children:$.has(g.id)?"â²":"â¼"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",onClick:q=>q.stopPropagation(),children:[!g.isPartner&&I&&!g.bookId&&[{status:"checked_in",label:"Check In",cls:"border-green-300 text-green-700 hover:bg-green-50"},{status:"checked_out",label:"Check Out",cls:"border-yellow-300 text-yellow-700 hover:bg-yellow-50"}].filter(q=>Zs[g.status]?.includes(q.status)).map(q=>e.jsx("button",{type:"button",onClick:()=>n(g,q.status),"aria-label":`${q.label} ${g.title}`,className:`px-2.5 py-0.5 rounded-full text-xs font-medium border transition-colors ${q.cls}`,children:q.label},q.status)),g.isPartner&&A&&e.jsx(R,{variant:"secondary",size:"sm",onClick:()=>D(g),children:"Request loan"}),!g.isPartner&&I&&Ge[g.acquisitionStatus]&&L&&e.jsx(R,{variant:"secondary",size:"sm",onClick:()=>L(g),children:"Mark received"}),!g.isPartner&&I&&e.jsxs("div",{className:"flex gap-2 ml-auto shrink-0",children:[!g.hasParts&&!g.bookId&&e.jsx(R,{variant:"secondary",size:"sm",onClick:()=>x(g),children:"Scan instrumentation"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>j(g),children:"Edit"})]})]}),$.has(g.id)&&e.jsx("div",{onClick:q=>q.stopPropagation(),children:e.jsx(tr,{piece:g,auditEntries:f[g.id],partsData:G?.[g.id],canManage:I,onEdit:j,onBookChanged:Z,canManagePerformances:B,allPerformances:C,onTogglePerformance:v,onAddInstrumentsFromPhoto:x,onSaveInventory:z,onMarkAudited:y,onCountAsPrinted:b,startInventory:P===g.id})}),!$.has(g.id)&&g.recordingUrl&&e.jsx("div",{onClick:q=>q.stopPropagation(),children:e.jsx("a",{href:g.recordingUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-band-600 hover:underline",children:"â¶ Recording"})})]},g.id))})}function tr({piece:t,auditEntries:a,partsData:l,canManage:c,onEdit:I,onBookChanged:B,canManagePerformances:A,allPerformances:p,onTogglePerformance:j,onAddInstrumentsFromPhoto:n,onSaveInventory:v,onMarkAudited:D,onCountAsPrinted:L,startInventory:k=!1}){const{canAny:x,roles:z}=Me(),y=x("music:read_full"),b=y||(z||[]).some(f=>f!=="member"),C=Je(f=>f.currentOrg),$=y||C?.membersOpenDigitalCopies===!0,_=[{label:"Style",value:t.style},{label:"Classification",value:t.classification?{concert:"Concert Band",orchestra:"Orchestra",marching:"Marching Band",jazz:"Jazz Ensemble"}[t.classification]:null},{label:"Theme",value:t.theme},{label:"Duration",value:t.performanceTime},{label:"Published",value:t.publishedDate},{label:"Borrowed From",value:t.ownership==="borrowed"?t.borrowedFrom:null},{label:"Format",value:t.format==="digital"?"Digital":t.format==="both"?"Physical + Digital":null},{label:"Publisher",value:t.publisher},{label:"Purchase Date",value:t.purchaseDate},{label:"Cost",value:t.cost!=null?`$${Number(t.cost).toFixed(2)}`:null}].filter(f=>f.value);return e.jsxs("div",{className:"border-t border-gray-100 pt-3 mt-1 space-y-3",children:[_.length>0&&e.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-1",children:[_.map(f=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-400",children:f.label}),e.jsx("dd",{className:"text-sm text-gray-700",children:f.value})]},f.label)),(t.recordingUrl||t.digitalUrl)&&e.jsxs("div",{className:"col-span-2 flex gap-4 flex-wrap mt-0.5",children:[t.recordingUrl&&e.jsx("a",{href:t.recordingUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-band-600 hover:underline",children:"â¶ Recording"}),t.digitalUrl&&$&&e.jsx("a",{href:t.digitalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-band-600 hover:underline",children:"ð Digital Copy"})]})]}),[{label:"Summary",value:t.summary},{label:"Director's Notes",value:y?t.directorsNotes:null}].filter(f=>f.value).map(f=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-400 uppercase tracking-wide mb-0.5",children:f.label}),e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-wrap",children:f.value})]},f.label)),e.jsxs("div",{className:"space-y-1.5",children:[t.instruments.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("h4",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wide",children:["Instruments ",e.jsx("span",{className:"font-normal normal-case tracking-normal",children:"â for matching players"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.instruments.map(f=>e.jsx(Os,{name:f.name,family:f.family},f.id))})]}),!t.isPartner&&c&&n&&e.jsxs("button",{type:"button",onClick:()=>n(t),className:"inline-flex items-center gap-1.5 text-xs font-medium text-gray-500 hover:text-band-700 transition-colors",children:[e.jsxs("svg",{className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.
1664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 13a3 3 0 11-6 0 3 3 0 016 0z"})]}),t.hasParts?"Re-scan instrumentation":"Scan instrumentation"]})]}),t.kind==="book"&&e.jsx("div",{className:"mb-4",children:e.jsx(Ms,{book:t,canManage:c&&!t.isPartner,onEdit:I,onChanged:B,performances:A&&!t.isPartner?p:[],onTogglePerformance:j})}),y&&l?.book&&e.jsxs("p",{className:"text-sm text-gray-700 mb-2","data-testid":"parts-via-book",children:["This title is in ",e.jsx("strong",{children:l.book.title}),". The parts below belong to that book. Count your copies on the book."]}),y&&e.jsx($s,{partsData:l,loading:!l,canManage:c&&!t.isPartner,onSaveInventory:v?f=>v(t.id,f):void 0,onMarkAudited:D?()=>D(t.id):void 0,onCountAsPrinted:L?()=>L(t.id):void 0,autoStart:k}),y&&t.librarianNotes&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-400 uppercase tracking-wide mb-0.5",children:"Librarianâs Notes"}),e.jsx("p",{className:"text-sm text-gray-700 whitespace-pre-wrap",children:t.librarianNotes})]}),b&&(!a||a.length>0)&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-gray-400 uppercase tracking-wide mb-1",children:"History"}),a?e.jsx("ul",{className:"space-y-1",children:a.map(f=>e.jsxs("li",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx(he,{color:Ht[f.action]??"gray",children:Vt[f.action]??f.action}),e.jsx("span",{children:f.performedBy}),e.jsx("span",{className:"text-gray-300",children:"·"}),e.jsx("span",{title:vs(f.performedAt),children:ys(f.performedAt)})]},f.id))}):e.jsx("p",{className:"text-xs text-gray-400",children:"Loadingâ¦"})]}),A&&p.length>0&&t.kind!=="book"&&e.jsx(Rs,{piece:t,allPerformances:p,onTogglePerformance:j})]})}function sr({open:t,onClose:a,onImported:l}){const{showError:c,showSuccess:I}=ke(),[B,A]=r.useState(""),[p,j]=r.useState(""),[n,v]=r.useState(null),[D,L]=r.useState(!1);function k(){A(""),j(""),v(null),L(!1)}function x(b){if(!b)return;const C=new FileReader;C.onload=async $=>{const _=String($.target.result||"");j(_),A(b.name),L(!0);try{const f=await U.importParts(_,!0);v(f?.data?.data||f?.data||f)}catch(f){c(f.message||"Could not read that spreadsheet")}finally{L(!1)}},C.onerror=()=>c("Could not read that file"),C.readAsText(b)}async function z(){L(!0);try{const b=await U.importParts(p,!1),C=b?.data?.data||b?.data||b;I(`${C.appliedCount} count${C.appliedCount===1?"":"s"} saved`),l?.(),k(),a()}catch(b){c(b.message||"Could not save those counts")}finally{L(!1)}}const y=(n?.applied||[]).filter(b=>b.changed);return e.jsx($t,{isOpen:t,onClose:()=>{k(),a()},title:"Import count sheet",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Export the count sheet, fill in the ",e.jsx("strong",{children:"Copies on hand"})," and ",e.jsx("strong",{children:"Stamped"})," ","columns, and bring the same file back here. Nothing is saved until you review what changed."]}),!n&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"inline-flex items-center rounded-md bg-white border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 cursor-pointer",children:D?"Readingâ¦":"Choose a CSV file"}),e.jsx("input",{type:"file",accept:".csv,text/csv",className:"hidden",disabled:D,onChange:b=>x(b.target.files?.[0])})]}),n&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:[e.jsx("span",{className:"font-medium",children:B})," â ",y.length," count",y.length===1?"":"s"," would change",n.unmatchedCount>0&&`, ${n.unmatchedCount} row${n.unmatchedCount===1?"":"s"} matched nothing`,"."]}),y.length>0&&e.jsx("div",{className:"border border-gray-200 rounded-lg max-h-56 overflow-y-auto",children:e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 text-xs uppercase tracking-wide text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2",children:"Piece"}),e.jsx("th",{className:"text-left px-3 py-2",children:"Part"}),e.jsx("th",{className:"text-left px-3 py-2",children:"Change"})]})}),e.jsx("tbody",{children:y.map((b,C)=>e.jsxs("tr",{className:"border-t border-gray-100",children:[e.jsx("td",{className:"px-3 py-1.5 text-gray-700",children:b.title}),e.jsx("td",{className:"px-3 py-1.5 text-gray-700",children:b.rawLabel}),e.jsxs("td",{className:"px-3 py-1.5 text-gray-500",children:[b.from.copiesOnHand??"uncounted"," â ",e.jsx("span",{className:"text-gray-900 font-medium",children:b.to.copiesOnHand??"uncounted"})]})]},C))})]})}),n.unmatchedCount>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3 max-h-40 overflow-y-auto",children:[e.jsx("p",{className:"text-sm text-amber-900 font-medium mb-1",children:"These rows were skipped"}),e.jsx("ul",{className:"text-xs text-amber-800 space-y-0.5",children:n.unmatched.slice(0,25).map((b,C)=>e.jsxs("li",{children:[b.rawLabel||"(no part)"," â ",b.reason]},C))}),e.jsx("p",{className:"text-xs text-amber-700 mt-2",children:"Nothing is created from a spreadsheet â add the piece or the part first, then re-import."})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(R,{type:"button",onClick:z,isLoading:D,disabled:y.length===0,children:["Save ",y.length," count",y.length===1?"":"s"]}),e.jsx(R,{type:"button",variant:"secondary",onClick:k,children:"Choose a different file"})]})]})]})})}function rr({filters:t,targetPerformanceId:a,targetTitle:l,onMentions:c}){const{showError:I}=ke(),[B,A]=r.useState(!1),[p,j]=r.useState([]),[n,v]=r.useState(""),[D,L]=r.useState(!1),k=r.useRef(null);r.useEffect(()=>{k.current?.scrollTo({top:k.current.scrollHeight,behavior:"smooth"})},[p,D]);async function x(){const y=n.trim();if(!y||D)return;const b=[...p,{role:"user",content:y}];j(b),v(""),L(!0);try{const C=await U.assistantChat({messages:b,filters:{search:t?.search||void 0,classification:t?.classification||void 0,theme:t?.theme||void 0,grade:t?.grade||void 0,lastPerformed:t?.lastPerformed||void 0},targetPerformanceId:a||void 0});j($=>[...$,{role:"assistant",content:C.reply}]),Array.isArray(C.mentionedPieceIds)&&c?.(C.mentionedPieceIds)}catch(C){j(p),v(y),I(C.message||"The assistant couldn't answer that â try again.")}finally{L(!1)}}const z=[t?.classification,t?.theme,t?.grade?`grade ${t.grade}`:null,t?.lastPerformed==="never"?"never performed":t?.lastPerformed?`played within ${parseInt(t.lastPerformed,10)}
1y`:null].filter(Boolean);return B?e.jsxs("div",{className:"bg-white rounded-xl border border-gray-200 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-100",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-700",children:"Program assistant"}),e.jsxs("span",{className:"text-xs text-gray-400 truncate",children:[l?`planning ${l}`:"no concert picked",z.length>0?` · ${z.join(" · ")}`:" · whole library"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[p.length>0&&e.jsx("button",{type:"button",onClick:()=>{j([]),v("")},disabled:D,className:"text-sm font-medium text-band-600 hover:text-band-700 disabled:opacity-50",children:"New conversation"}),e.jsx("button",{type:"button",onClick:()=>A(!1),className:"text-sm font-medium text-gray-400 hover:text-gray-600",children:"Close"})]})]}),e.jsxs("div",{ref:k,className:"max-h-80 overflow-y-auto px-4 py-3 space-y-3",children:[p.length===0&&e.jsx("p",{className:"text-sm text-gray-400",children:"Ask in plain language â âgive me three festive closers we havenât played in yearsâ, âwhat would open this concert well?â, âanything the librarian flagged as missing parts?â Your current filters and the concert youâre planning travel with every question."}),p.map((y,b)=>e.jsx("div",{className:y.role==="user"?"flex justify-end":"flex justify-start",children:e.jsx("div",{className:`rounded-xl px-3 py-2 text-sm whitespace-pre-wrap max-w-[85%] ${y.role==="user"?"bg-band-500 text-white":"bg-gray-50 border border-gray-200 text-gray-800"}`,children:y.content})},b)),D&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"rounded-xl px-3 py-2 text-sm bg-gray-50 border border-gray-200 text-gray-400",children:"Thinking through your libraryâ¦"})})]}),e.jsxs("div",{className:"flex gap-2 px-4 py-3 border-t border-gray-100",children:[e.jsx("input",{type:"text",value:n,onChange:y=>v(y.target.value),onKeyDown:y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),x())},placeholder:"Ask about your libraryâ¦",className:"flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-band-500 focus:border-band-500"}),e.jsx(R,{variant:"ai",size:"sm",onClick:x,isLoading:D,disabled:!n.trim(),children:"Send"})]})]}):e.jsx("div",{className:"mb-4",children:e.jsx(R,{variant:"ai",size:"sm",onClick:()=>A(!0),children:"Ask the program assistant"})})}const Dt=18;function Gt(t){if(!t||typeof t!="string")return 0;const a=t.split(":").map(Number);return a.some(Number.isNaN)?0:a.length===2?a[0]*60+a[1]:a.length===3?a[0]*3600+a[1]*60+a[2]:0}function ar(t){if(!t)return null;const a=new Date(`${String(t).slice(0,10)}T00:00:00`);if(Number.isNaN(a.getTime()))return null;const l=new Date;return(l.getFullYear()-a.getFullYear())*12+(l.getMonth()-a.getMonth())}const Tt=t=>String(t||"").toLowerCase().replace(/[^a-z0-9]/g,""),nr={title:t=>String(t.title||"").toLowerCase(),composers:t=>String(t.composers||"").toLowerCase()||null,grade:t=>t.grade!=null&&t.grade!==""?Number(t.grade):null,classification:t=>t.classification||null,theme:t=>String(t.theme||"").toLowerCase()||null,performanceTime:t=>Gt(t.performanceTime)||null,lastPerformed:t=>t.lastPerformed||null,book:t=>t.bookTitle?`${String(t.bookTitle).toLowerCase()} | ${String(t.bookNumber??9999).padStart(4,"0")}`:null};function ir(t,a,l){if(!a)return t;const c=nr[a];if(!c)return t;const I=l==="desc"?-1:1;return[...t].sort((B,A)=>{const p=c(B),j=c(A);return p===null&&j===null?0:p===null?1:j===null?-1:p<j?-1*I:p>j?1*I:0})}function lr({pieces:t,allPerformances:a,onTogglePerformance:l,onEdit:c,filters:I}){const B=at(),A=r.useMemo(()=>(a||[]).filter(m=>!m.cancelledAt&&(!m.performanceDate||m.performanceDate>=B)).sort((m,W)=>(m.performanceDate||"9999").localeCompare(W.performanceDate||"9999")),[a,B]),p=I?.kind==="book",[j,n]=r.useState(""),v=A.find(m=>m.id===j)||null,[D,L]=r.useState("title"),[k,x]=r.useState("asc");function z(m){D===m?x(W=>W==="asc"?"desc":"asc"):(L(m),x("asc"))}const y=!p&&D==="book"?"title":D,b=r.useMemo(()=>ir(t,y,k),[t,y,k]),C=p&&!["search","grade","classification","theme","ownership","lastPerformed"].some(m=>I?.[m]),[$,_]=r.useState(null),f=r.useMemo(()=>
1{if(!$)return b;const m=new Map($.map((W,J)=>[W,J]));return t.filter(W=>m.has(W.id)).sort((W,J)=>m.get(W.id)-m.get(J.id))},[$,b,t]),G=$?$.length-f.length:0,[F,P]=r.useState([]),[Z,K]=r.useState(null);r.useEffect(()=>{if(!j){P([]);return}let m=!0;return Ue.getSetlist(j).then(W=>{m&&P(W||[])}).catch(()=>{m&&P([])}),()=>{m=!1}},[j]);const ce=r.useRef(new Set),[ee,g]=r.useState(!1);r.useEffect(()=>{v?.publishedAt&&!ce.current.has(v.id)?(ce.current.add(v.id),g(!0)):g(!1)},[j]);const q=r.useMemo(()=>new Set(F.map(m=>m.musicId)),[F]),E=r.useMemo(()=>{const m=new Map;for(const W of F){const J=Tt(W.title);J&&m.set(J,(m.get(J)||0)+1)}return m},[F]),re=F.reduce((m,W)=>m+Gt(W.performanceTime),0),ne=Math.round(re/60),ae=v?.totalPerformanceMinutes||null;async function ue(m){if(!v||Z)return;const W=q.has(m.id);K(m.id);try{await l(m,v,W);const J=await Ue.getSetlist(v.id).catch(()=>null);J&&P(J)}finally{K(null)}}return e.jsxs("div",{children:[e.jsxs("div",{className:"sticky top-0 z-10 bg-white rounded-xl border border-gray-200 p-4 mb-4 flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Planning for"}),e.jsx(De,{placeholder:"Pick a concertâ¦",options:A.map(m=>({value:m.id,label:`${m.title}${m.performanceDate?` · ${_e(m.performanceDate)}`:""}`})),value:j,onChange:m=>n(m.target.value),className:"w-80"})]}),v&&e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-600 ml-auto",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-gray-900",children:F.length})," piece",F.length===1?"":"s"]}),e.jsx("span",{className:"text-gray-300",children:"·"}),e.jsxs("span",{children:[e.jsx("strong",{className:"text-gray-900",children:ne})," min of music",ae?e.jsxs("span",{className:"text-gray-400",children:[" / ",ae," min program"]}):null]}),ae&&ne>ae&&e.jsx(he,{color:"red",children:"over time"}),v.performanceTime&&e.jsxs("span",{className:"text-gray-400",children:["· downbeat ",js(v.performanceTime)]})]})]}),e.jsx(rr,{filters:I,targetPerformanceId:j||null,targetTitle:v?.title||null,onMentions:m=>_(m.length>0?m:null)}),$&&e.jsxs("div",{className:"mb-4 p-3 bg-violet-50 border border-violet-200 rounded-lg text-sm text-violet-800 flex items-center gap-3 flex-wrap",children:[e.jsxs("span",{children:["Showing the ",e.jsx("strong",{children:f.length})," piece",f.length===1?"":"s"," from the assistantâs answer, in its suggested order.",G>0&&` ${G} more mentioned but outside your current filters.`]}),e.jsx("button",{type:"button",onClick:()=>_(null),className:"font-medium text-violet-700 hover:text-violet-900 underline",children:"Show all pieces"})]}),ee&&v&&e.jsxs("div",{className:"mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800",children:[e.jsx("strong",{children:v.title})," is published â members can see its setlist, so additions and removals here are visible to them immediately."]}),v?e.jsxs("div",{className:"bg-white rounded-xl border border-gray-200 overflow-x-auto",children:[e.jsxs("table",{className:"min-w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-200 text-left text-xs font-semibold text-gray-500 uppercase tracking-wide",children:[[{key:"title",label:"Title"},...p?[{key:"book",label:"Book"}]:[],{key:"composers",label:"Composer"},{key:"grade",label:"Grade"},{key:"classification",label:"Classification"},{key:"theme",label:"Theme"},{key:"performanceTime",label:"Length"},{key:"lastPerformed",label:"Last Performed"}].map(m=>e.jsx("th",{className:"px-3 py-2 whitespace-nowrap",children:e.jsxs("button",{type:"button",onClick:()=>z(m.key),"aria-sort":y===m.key?k==="asc"?"ascending":"descending":void 0,className:`uppercase tracking-wide font-semibold hover:text-band-600 transition-colors ${y===m.key?"text-band-600":""}`,children:[m.label,y===m.key&&e.jsx("span",{className:"ml-1",children:k==="asc"?"â²":"â¼"})]})},m.key)),e.jsx("th",{className:"px-3 py-2 w-36"}),e.jsx("th",{className:"px-3 py-2 w-8"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:f.map(m=>{const W=q.has(m.id),J=ar(m.lastPerformed),de=J!==null&&J<Dt,H=!W&&(E.get(Tt(m.title))||0)>0;return e.jsxs("tr",{className:`[content-visibility:auto] ${W?"bg-band-50/40":""}`,children:[e.jsxs("td",{className:"px-3 py-2 max-w-xs",children:[m.recordingUrl?e.jsx("a",{href:m.recordingUrl,target:"_blank",rel:"noreferrer",className:"font-medium text-band-600 hover:text-band-700",children:m.title}):e.jsx("span",{className:"font-medium text-gray-900",children:m.title}),!p&&m.bookTitle&&e.jsxs("span",{className:"block text-sm text-gray-600",children:["In ",m.bookTitle]}),H&&e.jsx("span",{className:"ml-2 inline-block text-[11px] font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-full px-2 py-0.5 align-middle",title:"A piece with this title is already on this program â check it isn't a second arrangement of the same work.",children:"similar title on program"})]}),p&&e.jsx("td",{className:"px-3 py-2 text-gray-600 max-w-[12rem]",children:m.bookTitle||"â"}),e.jsx("td",{className:"px-3 py-2 text-gray-600 whitespace-nowrap",children:m.composers||"â"}),e.jsx("td",{className:"px-3 py-2 text-gray-600",children:m.grade||"â"}),e.jsx("td",{className:"px-3 py-2 text-gray-600 capitalize",children:m.classification||"â"}),e.jsx("td",{className:"px-3 py-2 text-gray-600",children:m.theme||"â"}),e.jsx("td",{className:"px-3 py-2 text-gray-500 tabular-nums",children:m.performanceTime||"â"}),e.jsx("td",{className:"px-3 py-2 whitespace-nowrap",children:m.lastPerformed?de?e.jsxs("span",{className:"inline-block text-[11px] font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-full px-2 py-0.5",title:`Performed within the last ${Dt} months â recently familiar to your audience.`,children:[_e(m.lastPerformed)," · ",J===0?"this month":`${J} mo ago`]}
1):e.jsx("span",{className:"text-gray-500",children:_e(m.lastPerformed)}):e.jsx("span",{className:"text-gray-300",children:"never"})}),e.jsx("td",{className:"px-3 py-2",children:m.isPartner?e.jsx("span",{className:"text-xs text-gray-400 whitespace-nowrap",title:"A partner band's piece. Ask to borrow it from the Library tab.",children:m.orgName?`${m.orgName}'s`:"Partner band's"}):e.jsx("button",{type:"button",onClick:()=>ue(m),disabled:Z===m.id,className:`rounded-full font-medium border px-3 py-1 text-xs transition-colors disabled:opacity-50 ${W?"border-band-500 bg-band-500 text-white hover:bg-band-600":"border-gray-300 bg-white text-gray-700 hover:border-band-400 hover:text-band-600"}`,children:W?"â On program":"Add"})}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("button",{type:"button",onClick:()=>c(m),title:"Edit piece details",className:"text-gray-300 hover:text-band-600 transition-colors",children:e.jsx("svg",{className:"h-4 w-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.8,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L6.832 19.82a4.5 4.5 0 01-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 011.13-1.897L16.862 4.487z"})})})})]},m.id)})})]}),t.length===0&&e.jsx(lt,{size:"compact",title:C?"No music in books yet.":p?"No music in books matches the current filters.":"No pieces match the current filters."})]}):e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 p-12 text-center text-sm text-gray-500",children:"Pick the concert you're planning â then every row below becomes a one-click add. Your library filters above (theme, grade, classification) work here too."})]})}function or(t){if(!t)return"";const[a,l,c]=t.split("-");return new Date(Number(a),Number(l)-1,Number(c)).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",year:"numeric"})}function cr(t){if(!t)return null;const[a,l,c]=t.split("-"),I=new Date(Number(a),Number(l)-1,Number(c)),B=new Date;return B.setHours(0,0,0,0),Math.round((I-B)/864e5)}function nt({type:t,onStatusChange:a}){const{showError:l,showSuccess:c}=ke(),{canFully:I}=Me(),B=I("music:update"),[A,p]=r.useState(null),[j,n]=r.useState(null),v=r.useCallback(async()=>{try{const L=await U.queue(t);p(Array.isArray(L)?L:[])}catch{l(Oe("music queue")),p([])}},[t,l]);r.useEffect(()=>{p(null),v()},[v]);async function D(L,k,x){if(!j){n(L.id);try{await U.setStatus(L.id,k),c(x),await v(),a?.()}catch(z){l(z?.message||Se)}finally{n(null)}}}return A===null?e.jsx("p",{className:"text-sm text-gray-400 py-6 text-center",children:"Loadingâ¦"}):A.length===0?e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 p-10 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:t==="requested"?"No requests to fill â every piece for an upcoming concert is either checked out or not yet on a setlist.":"Nothing checked out right now."})}):e.jsx("div",{className:"space-y-4",children:A.map(L=>{const k=L.performance,x=k?cr(k.performanceDate):null,z=x!=null&&x<=7?"text-red-600":x!=null&&x<=21?"text-amber-600":"text-gray-500";return e.jsxs("section",{className:"bg-white rounded-xl border border-gray-200 overflow-hidden",children:[e.jsxs("header",{className:"px-5 py-3 bg-gray-50 border-b border-gray-200 flex flex-wrap items-baseline justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 truncate",children:k?.title??"No performance assigned"}),k?.performanceDate&&e.jsxs("p",{className:`text-xs ${z}`,children:[or(k.performanceDate),x!=null&&x>=0&&` · ${x===0?"today":x===1?"in 1 day":`in ${x} days`}`,x!=null&&x<0&&` · ${Math.abs(x)} ${Math.abs(x)===1?"day":"days"} ago`]})]}),e.jsxs("span",{className:"text-xs text-gray-500 shrink-0",children:[L.items.length," ",L.items.length===1?"piece":"pieces"]})]}),e.jsx("ul",{className:"divide-y divide-gray-100",children:L.items.map(y=>{const b=y.piece,C=j===b.id;return e.jsxs("li",{className:"px-5 py-3 flex items-center gap-3",children:[b.folderNumber?e.jsxs("span",{className:"shrink-0 inline-flex items-center justify-center min-w-[3rem] px-2 py-1 rounded border border-gray-300 bg-gray-100 text-gray-900 font-mono font-bold text-sm tabular-nums leading-tight",children:["#",b.folderNumber]}):e.jsx("span",{className:"shrink-0 inline-flex items-center justify-center min-w-[3rem] px-2 py-1 rounded border border-dashed border-gray-200 text-gray-300 font-mono text-xs leading-tight","aria-label":"No folder number assigned",children:"â"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-gray-900 truncate",children:b.title}),e.jsxs("p",{className:"text-xs text-gray-500 truncate",children:[[b.composers,b.arrangers&&`arr. ${b.arrangers}
1`].filter(Boolean).join(" · ")||"â",b.format==="digital"&&e.jsx("span",{className:"ml-2 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-indigo-100 text-indigo-700",children:"DIGITAL"})]})]}),B&&(t==="requested"?e.jsx(R,{variant:"primary",size:"sm",isLoading:C,onClick:()=>D(b,"checked_out",`Checked out "${b.title}"`),children:"Check out"}):e.jsx(R,{variant:"secondary",size:"sm",isLoading:C,onClick:()=>D(b,"checked_in",`Checked in "${b.title}"`),children:"Mark returned"}))]},y.performanceMusicId??b.id)})})]},k?.id??"__none__")})})}const At={checked_in:{bg:"var(--bb-success-soft)",fg:"var(--bb-success-ink)",label:"Available"},checked_out:{bg:"var(--bb-warning-soft)",fg:"var(--bb-warning-ink)",label:"Checked out"},overdue:{bg:"var(--bb-danger-soft)",fg:"var(--bb-danger-ink)",label:"Overdue"}},it={digital:{bg:"var(--bb-info-soft)",fg:"var(--bb-info-ink)",label:"Digital"},both:{bg:"var(--bb-info-soft)",fg:"var(--bb-info-ink)",label:"Physical + Digital"}};function dr(t){return t.format==="digital"?it.digital:t.format==="both"?it.both:At[t.status]||At.checked_in}function Ft(t){const a=[],l=t.composer||t.composers;return l&&a.push(l),t.arrangers&&a.push(`arr. ${t.arrangers}`),t.grade!=null&&t.grade!==""&&a.push(`Grade ${t.grade}`),a.join(" · ")}function ur({piece:t,onSelect:a,showLibrarianChips:l=!0}){const c=l?dr(t):it[t.format==="both"?"both":t.format==="digital"?"digital":""]||null;return e.jsx("li",{"data-testid":"mobile-music-card","data-piece-id":t.id,style:{background:"var(--bb-surface)"},children:e.jsxs("div",{onClick:()=>a?.(t),style:{display:"flex",alignItems:"center",gap:"var(--bb-space-3)",minHeight:68,padding:"12px var(--bb-space-4)",background:"var(--bb-surface)",borderTop:"1px solid var(--bb-border-soft)",cursor:"pointer"},children:[t.folderNumber?e.jsx(mr,{number:t.folderNumber}):e.jsx(hr,{}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:16,fontWeight:600,color:"var(--bb-fg)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"},children:t.title||"Untitled"}),t.ownership==="borrowed"&&e.jsx(Fe,{bg:"var(--bb-warning-soft)",fg:"var(--bb-warning-ink)",children:"Borrowed"}),t.bookId&&t.bookTitle&&e.jsxs(Fe,{bg:"var(--bb-surface-2, #f3f4f6)",fg:"var(--bb-fg-muted, #4b5563)",children:["In ",t.bookTitle]}),t.kind==="book"&&e.jsxs(Fe,{bg:"var(--bb-info-soft, #e0f2fe)",fg:"var(--bb-info-ink, #075985)",children:["Book · ",t.titleCount??0," ",t.titleCount===1?"title":"titles"]})]}),Ft(t)&&e.jsx("div",{style:{marginTop:2,fontSize:13,color:"var(--bb-fg-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ft(t)}),l&&t.hasParts===!1&&e.jsx("div",{style:{marginTop:6},children:e.jsx(Fe,{bg:"var(--bb-ai-soft)",fg:"var(--bb-ai-ink)",children:"Not yet scanned"})}),(t.enrichmentStatus==="pending"||t.enrichmentStatus==="processing")&&e.jsx("div",{style:{marginTop:6},children:e.jsx(Fe,{bg:"var(--bb-ai-soft)",fg:"var(--bb-ai-ink)",children:"⨠Enrichingâ¦"})})]}),e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"var(--bb-space-2)",flexShrink:0},children:c&&e.jsx(Fe,{bg:c.bg,fg:c.fg,children:c.label})})]})})}function Fe({bg:t,fg:a,children:l}){return e.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:"var(--bb-radius-pill)",background:t,color:a,fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:l})}function mr({number:t}){return e.jsxs("div",{"aria-label":`Folder number ${t}`,style:{minWidth:44,height:36,padding:"0 8px",borderRadius:"var(--bb-radius-md)",background:"var(--bb-surface-sunken)",border:"1px solid var(--bb-border-soft)",color:"var(--bb-fg)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontVariantNumeric:"tabular-nums",fontSize:14,fontWeight:700,lineHeight:1,letterSpacing:"-0.01em"},children:["#",t]})}function hr(){return e.jsx("div",{"aria-hidden":"true",style:{width:36,height:36,borderRadius:"var(--bb-radius-pill)",background:"var(--bb-surface-sunken)",color:"var(--bb-fg-muted)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.75,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 19V6l12-3v13M9 19a2 2 0 11-4 0 2 2
10 014 0zm12 0a2 2 0 11-4 0 2 2 0 014 0z"})})})}function gr({isOpen:t,onClose:a,piece:l=null,onSaved:c}){const I=Je(b=>b.currentOrg?.id),{showSuccess:B,showError:A}=ke(),{canFully:p}=Me(),j=p("music:create"),[n,v]=r.useState(!1),[D,L]=r.useState(!1),[k,x]=r.useState(null);async function z(b,{force:C=!1}={}){v(!0);try{if(l){const $=await U.update(l.id,b);B("Piece updated"),c?.($,"edit")}else{const $=await U.create({...b,orgId:I},{force:C});B("Piece added"),c?.($,"create")}a?.()}catch($){if($.code==="DUPLICATE"&&$.existing){x({payload:b,existing:$.existing});return}A($.message||Se)}finally{v(!1)}}async function y(){try{await U.remove(l.id),B("Piece deleted"),L(!1),c?.(null,"delete"),a?.()}catch(b){L(!1),A(b.message||Rt)}}return e.jsxs(e.Fragment,{children:[e.jsx(Ke,{isOpen:D,onClose:()=>L(!1),onConfirm:y,title:"Delete Piece",message:`Delete "${l?.title}"? This cannot be undone.`,confirmLabel:"Delete"}),e.jsx(Ke,{isOpen:!!k,onClose:()=>x(null),onConfirm:()=>{const{payload:b}=k;x(null),z(b,{force:!0})},title:"Possible duplicate",message:k?`"${k.existing.title}"${k.existing.composers?` by ${k.existing.composers}`:""}${k.existing.folderNumber?` (folder #${k.existing.folderNumber})`:""} is already in your library. Add this piece anyway?`:"",confirmLabel:"Add Anyway",cancelLabel:"Cancel",confirmVariant:"primary",primaryAction:"cancel"}),e.jsx(Ye,{isOpen:t,onClose:a,title:l?"Edit piece":"New music",children:t&&e.jsx("div",{style:{padding:"var(--bb-space-3)"},children:e.jsx(Wt,{editTarget:l,canManage:j,isSaving:n,onSave:z,onCancel:a,onDelete:()=>L(!0)},l?.id||"new")})})]})}const br=[{value:"checked_in",label:"Available"},{value:"checked_out",label:"Checked out"}],fr=Array.from({length:11},(t,a)=>1+a*.5),Bt={concert:"Concert Band",orchestra:"Orchestra",marching:"Marching Band",jazz:"Jazz Ensemble"},xr=[{value:"own",label:"Own"},{value:"borrowed",label:"Borrowed"}];function pr({isOpen:t,onClose:a,filters:l,classifications:c,onApply:I,showStatus:B=!0}){const[A,p]=r.useState(l.status||""),[j,n]=r.useState(!!l.inSetlist),[v,D]=r.useState(l.grade||""),[L,k]=r.useState(l.classification||""),[x,z]=r.useState(l.ownership||""),[y,b]=r.useState(l.kind||"");r.useEffect(()=>{t&&(p(l.status||""),n(!!l.inSetlist),D(l.grade||""),k(l.classification||""),z(l.ownership||""),b(l.kind||""))},[t,l.status,l.inSetlist,l.grade,l.classification,l.ownership,l.kind]);function C(){I?.({status:A,inSetlist:j,grade:v,classification:L,ownership:x,kind:y}),a?.()}function $(){p(""),n(!1),D(""),k(""),z(""),I?.({status:"",inSetlist:!1,grade:"",classification:"",ownership:"",kind:""}),a?.()}function _(P){p(P),P&&n(!1)}function f(){n(!0),p("")}const G=(A?1:0)+(j?1:0)+(v?1:0)+(L?1:0)+(x?1:0)+(y?1:0),F=c&&c.length>0?c:Object.keys(Bt);return e.jsx(Ye,{isOpen:t,onClose:a,title:"Filter music",children:e.jsxs("div",{style:{padding:"var(--bb-space-4)"},children:[B&&e.jsxs(ze,{label:"Status",children:[e.jsx(je,{selected:!A&&!j,onClick:()=>{p(""),n(!1)},label:"All"}),e.jsx(je,{selected:j,onClick:f,label:"Requested"}),br.map(P=>e.jsx(je,{selected:A===P.value&&!j,onClick:()=>_(P.value),label:P.label},P.value))]}),e.jsxs(ze,{label:"Grade",children:[e.jsx(je,{selected:!v,onClick:()=>D(""),label:"All grades"}),fr.map(P=>e.jsx(je,{selected:v===String(P),onClick:()=>D(String(P)),label:`${P}`},P))]}),e.jsxs(ze,{label:"Classification",children:[e.jsx(je,{selected:!L,onClick:()=>k(""),label:"All"}),F.map(P=>e.jsx(je,{selected:L===P,onClick:()=>k(P),label:Bt[P]||P},P))]}),e.jsx(ze,{label:"Pieces or books",children:Ps.map(P=>e.jsx(je,{selected:y===P.value,onClick:()=>b(P.value),label:P.label},P.value||"all"))}),e.jsxs(ze,{label:"Ownership",children:[e.jsx(je,{selected:!x,onClick:()=>z(""),label:"All"}),xr.map(P=>e.jsx(je,{selected:x===P.value,onClick:()=>z(P.value),label:P.label},P.value))]}),e.jsxs("div",{style:{display:"flex",gap:"var(--bb-space-3)",marginTop:"var(--bb-space-5)"},children:[e.jsx("button",{type:"button","data-testid":"mobile-music-filter-clear",onClick:$,style:{flex:1,minHeight:48,padding:"12px 16px",border:"1px solid var(--bb-border)",borderRadius:"var(--bb-radius-md)",background:"var(--bb-surface)",color:"var(--bb-fg-body)",fontFamily:"inherit",fontSize:15,fontWeight:600,cursor:"pointer"},children:"Clear all"}),e.jsxs("button",{type:"button","data-testid":"mobile-music-filter-appl
1y",onClick:C,style:{flex:2,minHeight:48,padding:"12px 16px",border:"none",borderRadius:"var(--bb-radius-md)",background:"var(--bb-primary)",color:"#fff",fontFamily:"inherit",fontSize:15,fontWeight:600,cursor:"pointer"},children:["Apply",G>0?` (${G})`:""]})]})]})})}function ze({label:t,children:a}){return e.jsxs("div",{style:{marginBottom:"var(--bb-space-4)"},children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--bb-fg-muted)",marginBottom:6},children:t}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:a})]})}function je({selected:t,onClick:a,label:l}){return e.jsx("button",{type:"button",onClick:a,style:{minHeight:44,padding:"0 14px",fontSize:13,fontWeight:600,borderRadius:"var(--bb-radius-pill)",border:"1px solid",borderColor:t?"var(--bb-primary)":"var(--bb-border-soft)",background:t?"var(--bb-primary)":"var(--bb-surface)",color:t?"#fff":"var(--bb-fg-body)",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:l})}function yr(){const t=Et(),[a,l]=zt(),{currentOrg:c}=Je(),{showError:I,showSuccess:B}=ke(),{canFully:A,canAny:p}=Me(),j=A("music:create"),n=p("music:read_full"),[v,D]=r.useState([]),[L,k]=r.useState(!0),[x,z]=r.useState(""),[y,b]=r.useState(!1),[C,$]=r.useState(!1),[_,f]=r.useState(!1),[G,F]=r.useState(!1),P=_t(),[Z,K]=r.useState(null);r.useEffect(()=>{const w=P.state?.newBook;w&&(K(w),F(!0),t(P.pathname+P.search,{replace:!0,state:null}))},[P.state]);const[ce,ee]=r.useState(null),[g,q]=r.useState(!1),[E,re]=r.useState({status:"",inSetlist:!1,grade:"",classification:"",ownership:"",kind:""}),[ne,ae]=r.useState(null),[ue,m]=r.useState(!1),[W,J]=r.useState(null);function de(){c?.id&&(k(!0),U.list(c.id,{light:!0,includeBooks:"true"}).then(w=>{const Q=Array.isArray(w)?w:w?.items||w?.pieces||[];D(Q);const Y=a.get("highlight");if(Y){const le=Q.find(oe=>oe.id===Y);le&&(m(a.get("inventory")==="1"),ae(le)),a.delete("highlight"),a.delete("inventory"),l(a,{replace:!0})}}).catch(()=>I(Oe("music library"))).finally(()=>k(!1)))}function H(){c?.id&&U.stats(c.id).then(J).catch(()=>{})}r.useEffect(()=>{de(),H()},[c?.id]);async function we(w,Q){try{const Y=await U.setStatus(w.id,Q);D(le=>le.map(oe=>oe.id===w.id?{...oe,...Y}:oe)),ae(le=>le&&le.id===w.id?{...le,...Y}:le),B(Q==="checked_in"?"Checked in.":"Checked out."),H()}catch(Y){I(Y?.message||Se)}}const ie=x.trim().toLowerCase(),pe=v.filter(w=>E.status&&w.status!==E.status||E.grade&&String(w.grade??"")!==E.grade||E.classification&&w.classification!==E.classification||E.ownership&&w.ownership!==E.ownership||E.kind==="book"&&w.kind!=="book"?!1:ie?[w.title,w.composer,w.composers,w.arrangers,w.style,w.theme,w.folderNumber].filter(Boolean).join(" ").toLowerCase().includes(ie):!0),X=(E.kind?1:0)+(E.status?1:0)+(E.inSetlist?1:0)+(E.grade?1:0)+(E.classification?1:0)+(E.ownership?1:0),ye=E.inSetlist?"requested":E.status==="checked_out"?"checked_out":null,Ce=[...new Set(v.map(w=>w.classification).filter(Boolean))].sort();return e.jsxs("div",{children:[e.jsx("form",{onSubmit:w=>w.preventDefault(),style:{padding:"var(--bb-space-3) var(--bb-space-4) var(--bb-space-2)",background:"var(--bb-bg)"},children:e.jsxs("div",{style:{position:"relative"},children:[e.jsx(vr,{}),e.jsx("input",{type:"search",value:x,onChange:w=>z(w.target.value),placeholder:"Search title, composer, folder #","aria-label":"Search music by title, composer, or folder number",style:{width:"100%",padding:"12px 14px 12px 38px",fontSize:15,borderRadius:"var(--bb-radius-md)",border:"1px solid var(--bb-border-soft)",background:"var(--bb-surface)",color:"var(--bb-fg)",outline:"none"}})]})}),n&&e.jsxs("div",{style:{display:"flex",gap:"var(--bb-space-2)",padding:"0 var(--bb-space-4) var(--bb-space-2)",overflowX:"auto",WebkitOverflowScrolling:"touch",background:"var(--bb-bg)"},children:[e.jsx(Ot,{label:"Requested",count:W?.inSetlist,active:!!E.inSetlist,accent:"amber",onClick:()=>re(w=>({...w,inSetlist:!w.inSetlist,status:w.inSetlist?w.status:""}))}),e.jsx(Ot,{label:"Checked out",count:W?.checkedOut,active:E.status==="checked_out",accent:"primary",onClick:()=>re(w=>({...w,status:w.status==="checked_out"?"":"checked_out",inSetlist:!1}))})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:"var(--bb-space-2)",padding:"0 var(--bb-space-4) var(--bb-space-3)",background:"var(--bb-bg)"},children:[e.jsxs("button",{type:"button","data-testid":"mobile-music-filter-open","aria-label":"Filter music",onClick:()=>q(!0),style:{flexShrink:0,width:44,height:44,position:"relative",borderRadius:"var(--bb-radius-pill)",border:"1px solid var(--bb-border-soft)",background:"var(--bb-surface)",color:X>0?"var(--bb-primary)":"var(--bb-fg-muted)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:[e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.75,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4h18M6 12h12M10 20h4"})}),X>0&&e.jsx("span",{"aria-hidden":"true",style:{position:"absolute",top:2,right:2,minWidth:18,height:18,padding:"0 5px",borderRadius:"var(--bb-radius-pill)",background:"var(--bb-primary)",color:"#fff",fontSize:10,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center"},children:X})]}),j&&e.jsx("button",{type:"button","data-testid":"mobile-music-smart-import","aria-label":"Smart Import music",onClick:()=>b(!0),style:{flexShrink:0,width:44,height:44,borderRadius:"var(--bb-radius-pill)",border:"none",background:"var(--bb-ai)",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(_s,{size:22})}),j&&e.jsx("button",{type:"button","data-testid":"mobile-music-add","aria-label":"Add music or a book",onClick:()=>f(!0),style:{flexShrink:0,width:44,height:44,borderRadius:"var(--bb-radius-pill)",border:"none",background:"var(--bb-primary)",color:"#fff",fontSize:22,lineHeight:1,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:"+"})]}),e.jsx(Us,{isOpen:y,onClose:()=>b(!1),mode:"music",onCompleted:()=>{de(),H()}}),e.jsx(Es,{piece:ne,isOpen:!!ne,startInventory:ue,onClose:()=>{ae(null),m(!1)},onEdit:async w=>{ae(null);let Q=w;try{const Y=await U.getById(w.id);Y&&(Q=Y)}catch{}ee(Q)},onStatusChange:we,onPieceUpdated:w=>{if(!w?.id){de();return}D(Q=>Q.map(Y=>Y.id===w.id?{...Y,...w}:Y)),ae(Q=>Q&&Q.id===w.id?{...Q,...w}:Q)}}),e.jsx(pr,{showStatus:n,isOpen:g,onClose:()=>q(!1),filters:E,classifications:Ce,onApply:re}),e.jsx(Ye,{isOpen:_,onClose:()=>f(!1),title:"Add to the library",children:e.jsxs("div",{"data-testid":"mobile-music-add-choice",style:{display:"flex",flexDirection:"column",gap:"var(--bb-space-3)",padding:"var(--bb-space-2) 0 var(--bb-space-4)"},children:[e.jsx(R,{variant:"primary",size:"lg",className:"w-full",onClick:()=>{f(!1),$(!0)},children:"New music"}),e.jsx("p",{style:{margin:0,fontSize:14,color:"var(--bb-fg-muted)"},children:"One piece, with its own set of parts."}),e.jsx(R,{variant:"secondary",size:"lg",className:"w-full",onClick:()=>{f(!1),F(!0)},children:"New book"}),e.jsx("p",{style:{margin:0,fontSize:14,color:"var(--bb-fg-muted)"},children:"A collection: one printed book for each part, the same titles in every book."})]})}),e.jsx(Ye,{isOpen:G,onClose:()=>{F(!1),K(null)},title:"New book",fullHeight:!0,children:G&&e.jsx(qt,{bare:!0,initial:Z,onCancel:()=>{F(!1),K(null)},onCreated:w=>{F(!1),K(null),de(),H(),w?.id&&ae(w)}},Z?.title||"blank")}),e.jsx(gr,{isOpen:C||!!ce,piece:ce,onClose:()=>{$(!1),ee(null)},onSaved:()=>de()}),ye?e.jsx("div",{style:{padding:"0 var(--bb-space-4) var(--bb-space-4)"},children:e.jsx(nt,{type:ye,onStatusChange:()=>{de(),H()}})}
1):L?e.jsx(qs,{variant:"music",count:5}):pe.length===0?e.jsxs("div",{style:{margin:"var(--bb-space-4)",padding:"var(--bb-space-6)",background:"var(--bb-surface)",border:"1px solid var(--bb-border-soft)",borderRadius:"var(--bb-radius-lg)",textAlign:"center"},children:[e.jsx("p",{style:{color:"var(--bb-fg)",fontSize:15,fontWeight:600,margin:0},children:"No pieces match."}),e.jsx("p",{style:{color:"var(--bb-fg-muted)",fontSize:13,margin:"4px 0 0 0"},children:x||X>0?"Try a different search or clear some filters.":"Create the first piece to get started."}),j&&!x&&X===0&&e.jsx("div",{style:{marginTop:"var(--bb-space-4)"},children:e.jsx(R,{onClick:()=>t("/music?new=true"),children:"Create first piece"})})]}):e.jsx("ul",{"data-testid":"mobile-music-list",style:{listStyle:"none",margin:0,padding:0,background:"var(--bb-surface)"},children:pe.map(w=>e.jsx(ur,{piece:w,onSelect:ae,showLibrarianChips:n},w.id))})]})}function Ot({label:t,count:a,active:l,accent:c,onClick:I}){const B=c==="amber"?{activeBg:"#b45309",activeFg:"#fff",activeBorder:"#b45309",idleFg:"#92400e",idleBorder:"rgba(180, 83, 9, 0.35)"}:{activeBg:"var(--bb-primary)",activeFg:"#fff",activeBorder:"var(--bb-primary)",idleFg:"var(--bb-primary)",idleBorder:"rgba(13, 148, 136, 0.35)"};return e.jsxs("button",{type:"button",onClick:I,style:{flex:"0 0 auto",minHeight:44,padding:"6px 14px",fontSize:13,fontWeight:600,borderRadius:"var(--bb-radius-pill)",border:"1px solid",borderColor:l?B.activeBorder:B.idleBorder,background:l?B.activeBg:"var(--bb-surface)",color:l?B.activeFg:B.idleFg,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6,whiteSpace:"nowrap"},"aria-pressed":l,children:[t,typeof a=="number"&&e.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:20,height:20,padding:"0 6px",fontSize:11,fontWeight:700,borderRadius:999,background:l?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.06)",color:"inherit"},children:a})]})}function vr(){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"var(--bb-fg-subtle)",strokeWidth:2,"aria-hidden":"true",style:{position:"absolute",left:12,top:12},children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}const jr={requested:"yellow",approved:"blue",active:"green",returned:"gray",declined:"red"},kr={requested:"Requested",approved:"Approved",active:"Active",returned:"Returned",declined:"Declined"};function wr({loans:t,loading:a,orgId:l,canManageLoans:c,onAction:I}){if(a)return e.jsx("div",{className:"space-y-2",children:Array.from({length:4}).map((p,j)=>e.jsx(Ut,{lines:2},j))});const B=t.filter(p=>p.lendingOrgId===l),A=t.filter(p=>p.borrowingOrgId===l);return t.length===0?e.jsx(lt,{card:!0,title:"No loan requests yet."}):e.jsxs("div",{className:"space-y-6",children:[B.length>0&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3",children:"Incoming (you are lending)"}),e.jsx("div",{className:"space-y-2",children:B.map(p=>e.jsx(Mt,{loan:p,direction:"incoming",canManage:c,onAction:I}
1,p.id))})]}),A.length>0&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3",children:"Outgoing (you are borrowing)"}),e.jsx("div",{className:"space-y-2",children:A.map(p=>e.jsx(Mt,{loan:p,direction:"outgoing",canManage:c,onAction:I},p.id))})]})]})}function Mt({loan:t,direction:a,canManage:l,onAction:c}){const I=a==="incoming"?t.borrowingOrg:t.lendingOrg;return e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.musicTitle}),t.musicComposers&&e.jsx("p",{className:"text-xs text-gray-500",children:t.musicComposers}),e.jsxs("p",{className:"text-xs text-gray-400 mt-0.5",children:[a==="incoming"?"From":"To",": ",I?.name||"Unknown",t.expectedReturnDate&&` · Return by ${_e(t.expectedReturnDate)}`]}),t.requestNotes&&e.jsx("p",{className:"text-xs text-gray-500 mt-1 bg-gray-50 rounded p-1.5",children:t.requestNotes}),t.lenderNotes&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1 bg-blue-50 rounded p-1.5",children:["Lender: ",t.lenderNotes]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(he,{color:jr[t.status],children:kr[t.status]}),l&&a==="incoming"&&t.status==="requested"&&e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"primary",size:"sm",onClick:()=>c(t.id,"approve"),children:"Approve"}),e.jsx(R,{variant:"ghost",size:"sm",onClick:()=>c(t.id,"decline"),children:"Decline"})]}),l&&a==="incoming"&&t.status==="approved"&&e.jsx(R,{variant:"primary",size:"sm",onClick:()=>c(t.id,"activate"),children:"Activate"}),l&&t.status==="active"&&e.jsx(R,{variant:"secondary",size:"sm",onClick:()=>c(t.id,"return"),children:"Mark returned"})]})]})})}function Nr({piece:t,onClose:a}){const{showSuccess:l,showError:c}=ke(),[I,B]=r.useState({requestNotes:"",expectedReturnDate:""}),[A,p]=r.useState(!1);async function j(){p(!0);try{await Be.create({musicId:t.id,requestNotes:I.requestNotes||void 0,expectedReturnDate:I.expectedReturnDate||void 0}),l("Loan request sent"),a()}catch(n){c(n.response?.data?.error?.message||"Failed to request loan")}finally{p(!1)}}return e.jsx($t,{isOpen:!0,onClose:a,title:"Request Loan",size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.title}),t.composers&&e.jsx("p",{className:"text-xs text-gray-500",children:t.composers}),e.jsxs("p",{className:"text-xs text-purple-600 mt-1",children:["From: ",t.orgName]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Expected return date"}),e.jsx(se,{type:"date",value:I.expectedReturnDate,onChange:n=>B(v=>({...v,expectedReturnDate:n.target.value}))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notes (optional)"}),e.jsx("textarea",{className:"w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent",rows:3,maxLength:500,value:I.requestNotes,onChange:n=>B(v=>({...v,requestNotes:n.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(R,{variant:"secondary",onClick:a,children:"Cancel"}),e.jsx(R,{variant:"primary",onClick:j,isLoading:A,children:"Submit request"})]})]})})}function na(){Is();const t=Et(),{currentOrg:a}=Je(),{showSuccess:l,showError:c}=ke(),{canFully:I,canAny:B}=Me(),A=I("music:create"),p=I("performance:update"),j=B("loan:manage"),n=B("music:read_full"),{roles:v}=Me(),D=n||(v||[]).some(i=>i!=="member"),L=B("loan:list"),k=ks(),[x,z]=zt(),[y,b]=r.useState([]),[C,$]=r.useState(!0),[_,f]=r.useState(!1),[G,F]=r.useState(null),[P,Z]=r.useState(!1),K=_t(),[ce,ee]=r.useState(null);r.useEffect(()=>{const i=K.state?.newBook;!i||k||(ee(i),f(!1),Z(!0),t(K.pathname+K.search,{replace:!0,state:null}))},[K.state]);const[g,q]=r.useState(!1),[E,re]=r.useState("title"),[ne,ae]=r.useState("asc"),[ue,m]=r.useState(null),[W,J]=r.useState(new Set),[de,H]=r.useState({}),[we,ie]=r.useState(null),[pe,X]=r.useState({}),[ye,Ce]=r.useState([]),[w,Q]=r.useState(!1),[Y,le]=r.useState(null),[oe,s]=r.useState(null),[N,O]=r.useState(()=>x.get("search")??""),[o,T]=r.useState(()=>n?x.get("status")??"":""),[u,V]=r.useState(()=>x.get("grade")??""),[me,ge]=r.useState(()=>x.get("classification")??""),[Le,ot]=r.useState(()=>x.get("theme")??""),[be,ct]=r.useState(()=>x.get("ownership")??""),[$e,dt]=r.useState(()=>n&&x.get("inSetlist")==="true"),[Re,Qe]=r.useState(()=>n&&x.get("needsInstruments")==="true"),[qe,ut]=r.useState(""),[Ee,mt]=r.useState(()=>x.get("lastPerformed")??""),[Kt,ht]=r.useState(!1),[We,Yt]=r.useState(!1),[Jt,Qt]=r.useState(!1),[Xt,Zt]=r.useState([]),[xe,es]=r.useState("library"),[ts,ss]=r.useState([]),[rs,gt]=r.useState(!1),[bt,ft]=r.useState(null),[Xe,xt]=r.useState(null),Ze=xe==="director"?"":qe,He={search:N,kind:qe,status:o,grade:u,classification:me,theme:Le,ownership:be,inSetlist:$e,needsInstruments:Re,lastPerformed:Ee},pt=!!(N||qe||o||u||me||Le||be||Ee||$e||Re),Te=(()=>
1{if(!Ee)return y;if(Ee==="never")return y.filter(S=>!S.lastPerformed);const i=parseInt(Ee,10);if(!i)return y;const h=new Date;h.setFullYear(h.getFullYear()-i);const d=ws(h);return y.filter(S=>S.lastPerformed&&String(S.lastPerformed).slice(0,10)>=d)})(),et=Te.filter(i=>i.kind!=="book"&&(qe!=="book"||i.bookId));function as(){ut(""),O(""),T(""),V(""),ge(""),ot(""),ct(""),dt(!1),Qe(!1),mt("")}r.useEffect(()=>{a&&fe()},[a]),r.useEffect(()=>{a&&p&&Ue.list(a.id).then(Ce).catch(()=>c(Oe("performances")))},[a,p]);const[ns,is]=r.useState(null);r.useEffect(()=>{if(!a)return;const i=be.startsWith("partner:");try{U.filterOptions({search:N||void 0,status:o||void 0,grade:u||void 0,classification:me||void 0,theme:Le||void 0,ownership:be&&!i?be:void 0}).then(is).catch(()=>{})}catch{}},[a,N,o,u,me,Le,be]),r.useEffect(()=>{a&&Ne()},[a,N,Ze,o,u,me,Le,be,$e,Re,We]),r.useEffect(()=>{const i=x.get("highlight");if(!i||C||y.length===0||!y.find(M=>M.id===i))return;J(M=>new Set(M).add(i)),x.get("inventory")==="1"&&ie(i);const d=x.get("inventory")==="1",S=M=>requestAnimationFrame(()=>
1{const te=document.querySelector(`[data-piece-id="${i}"]`);te?.scrollIntoView&&te.scrollIntoView({behavior:"smooth",block:M})});S(d?"start":"center"),St(i).then(()=>{d&&S("start")}),x.delete("highlight"),x.delete("inventory"),z(x,{replace:!0})},[C,y]);const tt=r.useRef(ue?.enriching);r.useEffect(()=>{if(!ue?.enriching){tt.current>0&&Ne(),tt.current=0;return}tt.current=ue.enriching;const i=setInterval(()=>{fe()},3e4);return()=>clearInterval(i)},[ue?.enriching]),r.useEffect(()=>{a&&B("partnership:list")&&Ts.list().then(i=>{const h=(i||[]).filter(S=>S.status==="active");Qt(h.length>0);const d=h.map(S=>(S.requestingOrgId===a.id?S.partnerOrg:S.requestingOrg)?.name).filter(Boolean);Zt([...new Set(d)])}).catch(()=>{})},[a]);async function fe(){try{m(await U.stats(a.id))}catch{}}const yt=r.useRef(0);async function Ne(){const i=++yt.current;$(!0);try{const h={};N&&(h.search=N),o&&(h.status=o),u&&(h.grade=u),me&&(h.classification=me),Le&&(h.theme=Le);const d=be.startsWith("partner:");be&&!d&&(h.ownership=be),$e&&(h.inSetlist="true"),Re&&(h.needsInstruments="true"),(We||d)&&(h.includePartners="true"),h.includeBooks="true",Ze&&(h.kind=Ze);let S=await U.list(a.id,h);if(d){const M=be.slice(8);S=S.filter(te=>te.isPartner&&te.orgName===M)}if(i!==yt.current)return;b(S)}catch{c(Oe("music library"))}finally{$(!1)}}async function vt(){gt(!0);try{ss(await Be.list())}catch{c(Oe("loans"))}finally{gt(!1)}}const ls=r.useCallback((i,h)=>{({search:O,kind:ut,status:T,grade:V,classification:ge,theme:ot,ownership:ct,inSetlist:dt,needsInstruments:Qe,lastPerformed:mt})[i]?.(h)},[]);function os(){const i=at(),h=a?.shortName||"band";Pt(`music-library-${h}-${i}.csv`,["BSB ID","Folder #","Title","Composer","Arranger","Grade","Style","Classification","Theme","Publisher","Duration","Status","Format","Ownership","Summary","Director's Notes","Librarian Notes","Recording URL","Digital URL"],Te.map(d=>[d.id,d.folderNumber||"",d.title,d.composers||"",d.arrangers||"",d.grade||"",d.style||"",d.classification||"",d.theme||"",d.publisher||"",d.performanceTime||"",d.status||"",d.format||"",d.ownership||"",d.summary||"",d.directorsNotes||"",d.librarianNotes||"",d.recordingUrl||"",d.digitalUrl||""]))}function st(){f(!1),F(null),Z(!1)}function cs(i){Z(!1),Ne(),fe(),i?.id&&Nt(i.id)}async function jt(i){let h=i;try{const d=await U.getById(i.id);d&&(h=d)}catch{}F(h),f(!0)}async function kt(i,{force:h=!1}={}){q(!0);try{if(G){const d=await U.update(G.id,i);b(S=>S.map(M=>M.id===G.id?{...M,...d}:M)),l("Piece updated"),G.kind==="book"&&Ne()}else{const d=await U.create({...i,orgId:a.id},{force:h});b(S=>[...S,d].sort((M,te)=>M.title.localeCompare(te.title))),l("Piece added")}fe(),st()}catch(d){if(d.code==="DUPLICATE"&&d.existing){s({payload:i,existing:d.existing});return}c(d.message||Se)}finally{q(!1)}}async function ds(i,h){try{const d=await U.setStatus(i.id,h),S=o&&d.status!==o,M=$e&&d.status!==i.status;S||M?(b(te=>te.filter(ve=>ve.id!==i.id)),J(te=>{const ve=new Set(te);return ve.delete(i.id),ve})):b(te=>te.map(ve=>ve.id===i.id?{...ve,...d}:ve)),l(`${i.title} â ${h==="checked_in"?"Checked In":"Checked Out"}`),fe(),H(te=>({...te,[i.id]:null})),D&&U.getAudit(i.id).then(te=>H(ve=>({...ve,[i.id]:te}))).catch(()=>{})}catch(d){c(d.message||Se)}}async function us(i){try{const h=await U.markReceived(i.id);b(d=>d.map(S=>S.id===i.id?{...S,...h}:S)),l(`${i.title} â Received. Ready for circulation.`),fe()}catch(h){c(h.message||Se)}}async function wt(i,h,d){try{if(d){await Ue.removeFromSetlist(h.id,i.id);const S=i.performanceIds.filter(M=>M!==h.id);b(M=>M.map(te=>te.id===i.id?{...te,performanceIds:S}:te))}else await Ue.addToSetlist(h.id,i.id),b(S=>S.map(M=>M.id===i.id?{...M,performanceIds:[...new Set([...M.performanceIds??[],h.id])]}:M));return fe(),!0}catch(S){return c(S.message||Se),!1}}async function Nt(i){const h=!W.has(i);J(d=>{const S=new Set(d);return S.has(i)?S.delete(i):S.add(i),S}),!h&&i===we&&ie(null),h&&await St(i)}async function St(i){const h=y.find(d=>d.id===i);if(h&&h.summary===void 0)try{const d=await U.getById(i);d&&b(S=>S.map(M=>M.id===i?{...M,summary:d.summary??null,directorsNotes:d.directorsNotes??null,librarianNotes:d.librarianNotes??null,theme:d.theme??null}:M))}catch{}if(D&&!de[i])try{H(S=>
1({...S,[i]:null}));const d=await U.getAudit(i);H(S=>({...S,[i]:d}))}catch{c(Oe("history"))}if(n&&!pe[i])try{const d=await U.getParts(i);X(S=>({...S,[i]:d?.data?.data||d?.data||d}))}catch{}}async function ms(){try{const i=await U.exportParts(),h=(i?.data?.data||i?.data||i)?.rows||[];if(h.length===0){c("No parts to export yet â scan a piece first.");return}const d=at(),S=a?.slug||"org";Pt(`count-sheet-${S}-${d}.csv`,["BSB ID","Title","Folder #","Part","Instrument","Copies on hand","Counted on","Stamped","Set of","Condition","Notes"],h.map(M=>[M.musicId,M.title,M.folderNumber,M.rawLabel,M.partName||"",M.copiesOnHand??"",M.copiesCountedAt?String(M.copiesCountedAt).slice(0,10):"",M.stamped?"yes":"",M.setCount??"",M.condition,M.notes])),l(`Exported ${h.length} parts`)}catch(i){c(i.message||"Could not export parts")}}async function hs(i,h){try{const d=await U.setPartInventory(i,h),S=d?.data?.data||d?.data||d;X(M=>({...M,[i]:S})),l(h.length===1?"Count saved":`${h.length} counts saved`)}catch(d){c(d.message||"Could not save the counts")}}async function gs(i){try{const h=await U.countAsPrinted(i),d=h?.data?.data||h?.data||h;X(M=>({...M,[i]:d}));const S=d?.skipped?.length||0;l(`${d?.counted??0} part${d?.counted===1?"":"s"} counted as printed and the set marked checked${S?` â ${S} with no printed count left uncounted`:""}`)}catch(h){c(h.message||"Could not record the counts")}}async function bs(i){try{const h=await U.markPartsAudited(i),d=h?.data?.data||h?.data||h;X(S=>({...S,[i]:d})),l("Set marked as checked")}catch(h){c(h.message||"Could not record the check")}}async function fs(){try{await U.remove(Y.id),b(i=>i.filter(h=>h.id!==Y.id)),fe(),Q(!1),le(null),st(),l("Piece deleted")}catch(i){c(i.message||Rt)}}async function xs(i,h,d={}){try{h==="approve"?await Be.approve(i,d):h==="activate"?await Be.activate(i):h==="return"?await Be.return(i):h==="decline"&&await Be.decline(i,d),l(`Loan ${h}d successfully`),vt()}catch(S){c(S.response?.data?.error?.message||Se)}}return k?e.jsx(yr,{}):e.jsxs("div",{children:[e.jsx(Ke,{isOpen:w,onClose:()=>{Q(!1),le(null)},onConfirm:fs,title:"Delete Piece",message:`Delete "${Y?.title}"? This cannot be undone.`,confirmLabel:"Delete"}),e.jsx(Ke,{isOpen:!!oe,onClose:()=>s(null),onConfirm:()=>{const{payload:i}=oe;s(null),kt(i,{force:!0})},title:"Possible duplicate",message:oe?`"${oe.existing.title}"${oe.existing.composers?` by ${oe.existing.composers}`:""}${oe.existing.folderNumber?` (folder #${oe.existing.folderNumber})`:""} is already in your library. Add this piece anyway?`:"",confirmLabel:"Add Anyway",cancelLabel:"Cancel",confirmVariant:"primary",primaryAction:"cancel"}),e.jsx(Ds,{title:"Music Library",breadcrumbs:[{label:"Home",to:"/"},{label:"Music Library"}],actions:!_&&!P?e.jsxs(e.Fragment,{children:[A&&e.jsxs(Ie,{align:"right",menuId:"music-library-more",trigger:e.jsx(R,{variant:"ghost",size:"md",className:"min-h-[2.75rem]",children:"More"}),children:[e.jsxs(Ie.Section,{label:"Library",children:[y.length>0?e.jsx(Ie.Item,{onClick:os,children:"Export library"}):null,e.jsx(Ie.Item,{onClick:()=>t("/music/health"),children:"Library Health"})]}),e.jsxs(Ie.Section,{label:"Count sheet",children:[e.jsx(Ie.Item,{onClick:ms,children:"Export count sheet"}),e.jsx(Ie.Item,{onClick:()=>ht(!0),children:"Import count sheetâ¦"})]})]}),A&&e.jsx(Ns,{to:"/import/music",children:e.jsx(R,{variant:"ai",children:"Smart Import"})}),A&&e.jsx(R,{variant:"ghost",onClick:()=>{F(null),f(!1),ee(null),Z(!0)},children:"New book"}),A&&e.jsx(R,{"data-tour":"music-add-btn",onClick:()=>{F(null),f(!0)},children:"New music"})]}):null}),e.jsx(sr,{open:Kt,onClose:()=>ht(!1),onImported:()=>{X({}),Ne()}}),e.jsx(Sr,{}),(L||p)&&e.jsxs("div",{className:"mb-4",children:[e.jsx(Vs,{className:"mb-3",ariaLabel:"Music library views",tabs:[{key:"library",label:"Library"},...p?[{key:"director",label:"Director view"}]:[],...L?[{key:"loans",label:"Loans"}]:[]],value:xe,onChange:i=>{es(i),i==="loans"&&vt()}}),xe==="library"&&Jt&&e.jsxs("label",{className:"flex justify-end items-center gap-2 text-sm text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:We,onChange:i=>Yt(i.target.checked),className:"rounded border-gray-300 text-band-500 focus:ring-band-500"}),"Include partner libraries"]})]}),bt&&e.jsx(Nr,{piece:bt,onClose:()=>ft(null)}),xe==="loans"&&L&&e.jsx(wr,{loans:ts,loading:rs,orgId:a?.id,canManageLoans:j,onAction:xs}),(xe==="library"||xe==="director")&&e.jsxs(e.Fragment,{children:[e.jsx(Gs,{filters:He,onChange:ls,stats:ue,showForm:_,showLibrarianStats:n,kindOptions:xe==="director"?Ls:void 0,facetOptions:ns,sort:{sortBy:E,sortDir:ne},onSortChange:(i,h)=>{re(i),ae(h)},piecesCount:xe==="director"?et.length:Te.length,loading:C,partnerCount:We||be.startsWith("partner:")?Te.filter(i=>i.isPartner).length:void 0,partnerNames:Xt}),pt&&e.jsx(As,{count:xe==="director"?et.length:Te.length,onClear:as}),P&&e.jsx(qt,{initial:ce,onCreated:i=>{ee(null),cs(i)},onCancel:()=>{ee(null),Z(!1)}},ce?.title||"blank"),_&&e.jsx(Wt,{editTarget:G,onSave:kt,onCancel:st,onDelete:i=>{le(i),Q(!0)},canManage:A,isSaving:g}),!_&&xe==="director"&&e.jsx(lr,{pieces:et,allPerformances:ye,onTogglePerformance:wt,onEdit:jt,filters:He}),!_&&xe==="library"&&(He.inSetlist?e.jsx(nt,{type:"requested",onStatusChange:()=>{Ne(),fe()}}):He.status==="checked_out"?e.jsx(nt,{type:"checked_out",onStatusChange:()=>{Ne(),fe()}}):P?null:e.jsx(er,{pieces:Te,loading:C,showForm:_,sort:{sortBy:E,sortDir:ne},onBookChanged:()=>{Ne(),fe()},canManage:A,canManagePerformances:p,canManageLoans:j,showStatus:n,onEdit:jt,onStatusChange:ds,onTogglePerformance:wt,onRequestLoan:ft,onMarkReceived:us,onAddInstrumentsFromPhoto:xt,onSaveInventory:hs,onMarkAudited:bs,onCountAsPrinted:gs,onOpenCreate:()=>{F(null),f(!0)},allPerformances:ye,expandedPieces:W,onTogglePiece:Nt,auditCache:de,partsCache:pe,hasActiveFilters:pt,inventoryPieceId:we}))]}),Xe&&e.jsx(Ws,{piece:Xe,onClose:()=>xt(null),onSaved:()=>{const i=Xe.id;X(h=>({...h,[i]:null})),U.getParts(i).then(h=>X(d=>({...d,[i]:h?.data?.data||h?.data||h}
1))).catch(()=>X(h=>{const d={...h};return delete d[i],d})),Ne(),fe(),Re&&y.filter(h=>h.enrichmentStatus==="complete_no_instruments").length<=1&&Qe(!1)}})]})}function Sr(){const t=Ss(a=>a.getMetric("musicPieces"));return t?e.jsx(Hs,{metricName:"Music pieces",current:t.current,limit:t.limit}):null}export{na as MusicLibraryPage};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.