1import{v as pe,c as se,r as n,j as e,M as de,B as d,I as Ht,S as he,w as cs,G as nt,E as K,t as ce,q as ds,h as Ue,z as jt,ak as We,al as He,y as ze,d as ve,l as Qt,s as kt,a as Jt,p as it,g as us,e as ms,L as Na}from"./index-_aijvlUq.js";import{u as gs}from"./useDragReorder-BPTlhWx5.js";import{e as M}from"./equipment-BFd-7mSR.js";import{v as Gt}from"./venues-DxAiztOL.js";import{I as Q}from"./Input-ysTyZFq5.js";import{m as $a}from"./members-I3UAoZ9P.js";import{A as ps}from"./AgreementVersionHistory-BzxnBiqA.js";import{i as hs}from"./instruments-CRxWHJ-h.js";import{P as xs}from"./PageHeader-DCofr6qo.js";import{C as Qe}from"./ConfirmDialog-CODvETNM.js";import{A as bs}from"./ActiveFiltersBar-DPDav4h_.js";import{C as Yt}from"./CameraCaptureButton-B4WpiVvJ.js";import{d as ys}from"./exportCsv-CZAUSrIW.js";import{B as fe}from"./Badge-DJIi163x.js";import{B as Ia}from"./BottomSheet-BiQNSujt.js";import{p as za,a as Nt,i as Te,d as je,b as ye,c as Je,e as Le,g as fs,m as vs,f as js}from"./stockInventory-CSFNe4Se.js";import{M as wa}from"./MobileListSkeleton-BxuyWDCs.js";import{E as Ie}from"./EmptyState-CPGKooqj.js";import{M as Ce}from"./Menu-CATQC14B.js";import{T as ks}from"./Tabs-CGDUdv1I.js";import"./downscaleImage-qyGK-a3D.js";const Pe={list(a){return pe.get("/equipment-categories",{params:{orgId:a}})},create(a){return pe.post("/equipment-categories",a)},update(a,l){return pe.put(`/equipment-categories/${a}`,l)},reorder(a){return pe.put("/equipment-categories/reorder",{orderedCategoryIds:a})},remove(a){return pe.delete(`/equipment-categories/${a}`)}},Ca={list(a={}){return pe.get("/equipment-loans",{params:a})},create(a){return pe.post("/equipment-loans",a)},approve(a,l={}){return pe.post(`/equipment-loans/${a}/approve`,l)},activate(a){return pe.post(`/equipment-loans/${a}/activate`)},return(a){return pe.post(`/equipment-loans/${a}/return`)},decline(a,l={}){return pe.post(`/equipment-loans/${a}/decline`,l)}};function Ns(a){const l=new Set((a.missingAccessories||[]).map(o=>String(o.name).toLowerCase()));return{included:String(a.accessories||"").split(/[,\n;]+/).map(o=>o.trim()).filter(Boolean).filter(o=>!l.has(o.toLowerCase())),missing:(a.missingAccessories||[]).map(o=>o.name)}}function Ta({item:a,items:l=[],activeLoans:i={},isOpen:o,onClose:g,onSaved:A,product:k=null,onBuyInstead:y}){const{showError:v,showSuccess:j}=se(),[h,q]=n.useState([]),[f,w]=n.useState(""),[r,x]=n.useState([]),[C,E]=n.useState(""),[R,c]=n.useState(""),[N,F]=n.useState(!1),[_,z]=n.useState(""),[O,$]=n.useState(""),[X,m]=n.useState(""),[P,I]=n.useState("email"),[T,Y]=n.useState(null),[ee,te]=n.useState(!1);n.useEffect(()=>{o&&(w(""),E(""),c(""),F(!1),z(""),$(""),m(""),I("email"),Y(null),x(a&&a.id?[a]:[]),$a.list({limit:500}).then(L=>{const J=Array.isArray(L)?L:L?.members||[];q(J.filter(ae=>ae.memberStatus!=="retired"))}).catch(()=>q([])))},[o,a]);const re=new Set(r.map(L=>L.id)),ne=l.filter(L=>!re.has(L.id)&&L.loanable!==!1&&(i[L.id]||[]).length<(L.quantity||1)),ie=L=>L.variantLabel?`${L.name} · ${L.variantLabel}`:L.name,Se=r.length>0&&r.every(L=>L.kind==="stock"),le=Se&&r.length===1&&k&&y,Re=r.some(L=>L.agreementRequired!==!1);async function ue(){if(!f){v("Pick a member first");return}if(!r.length){v("Add at least one item to the loan");return}if(N&&!_.trim()){v("Guardian name is required for a borrower under 18");return}if(N&&!O.trim()&&!X.trim()){v("Add a guardian email or phone â either one works");return}if(N&&P==="email"&&!O.trim()){v('No guardian email â switch to "Paper" to print the agreement for in-person signing');return}te(!0);try{const L=await M.checkoutBatch({memberId:f,equipmentIds:r.map(ae=>ae.id),expectedReturnDate:C||null,notes:R.trim()||null,guardianName:N?_.trim():null,guardianEmail:N&&O.trim()||null,guardianPhone:N&&X.trim()||null,agreementDelivery:P}),J=r.length>1?`${r.length} items checked out`:"Checked out";if(P==="paper"&&L?.agreementRequired){j(`${J} â print the agreement for signing`),Y(L);return}j(L?.agreementRequired?L?.guardianEmail?`${J} â loan agreement emailed to the guardian for signing`:`${J} â loan agreement emailed to the member for signing`:J),A?.()}catch(L){v(L?.message||K)}finally{te(!1)}}return T?e.jsx(de,{isOpen:o,onClose:g,title:"Check out equipment",size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg text-sm text-green-800 p-3",children:["Checked out. Print the agreement, have it signed in person, then use",e.jsx("span",{className:"font-semibold",children:" Record signed paper copy"})," on the loan when the sheet comes back."]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(d,{type:"button",onClick:()=>Ht(`/app/api/v1/equipment/loans/${T.id}/agreement-print`),children:"Print agreement"}),e.jsx(d,{type:"button",variant:"ghost",onClick:()=>A?A():g(),children:"Done"})]})]})}):e.jsx(de,{isOpen:o,onClose:g,title:"Check out equipment",size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Loan items"}),r.length===0&&e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"No items yet â add the first one below."}),e.jsx("div",{className:"space-y-1.5",children:r.map(L=>{const J=Ns(L);return e.jsxs("div",{className:"flex items-start gap-2 bg-gray-50 border border-gray-200 rounded-lg p-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-gray-800",children:ie(L)}),J.included.length>0&&e.jsxs("div",{className:"text-xs text-gray-500",children:["With: ",J.included.join(", ")
1]}),J.missing.length>0&&e.jsxs("div",{className:"text-xs text-amber-700",children:["Not included (missing): ",J.missing.join(", ")]})]}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",className:"text-red-600 shrink-0",onClick:()=>x(ae=>ae.filter(me=>me.id!==L.id)),children:"Remove"})]},L.id)})}),e.jsx("div",{className:"mt-2",children:e.jsx(he,{value:"",onChange:L=>{const J=l.find(ae=>ae.id===L.target.value);J&&x(ae=>[...ae,J])},placeholder:ne.length?"Add an itemâ¦":"No more items available",options:ne.map(L=>({value:L.id,label:ie(L)}))})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Member"}),e.jsx(he,{value:f,onChange:L=>w(L.target.value),placeholder:"Select memberâ¦",options:h.map(L=>({value:L.id,label:`${L.firstName} ${L.lastName}`}))})]}),Re&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Loan agreement signing"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"radio",name:"agreement-delivery",checked:P==="email",onChange:()=>I("email"),className:"mt-0.5 h-4 w-4 border-gray-300 text-band-600 focus:ring-band-500"}),e.jsxs("span",{children:["Email a signing link ",e.jsx("span",{className:"text-xs text-gray-500",children:"â no login needed, takes a minute"})]})]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"radio",name:"agreement-delivery",checked:P==="paper",onChange:()=>I("paper"),className:"mt-0.5 h-4 w-4 border-gray-300 text-band-600 focus:ring-band-500"}),e.jsxs("span",{children:["Paper â print and sign in person ",e.jsx("span",{className:"text-xs text-gray-500",children:"â no email sent"})]})]})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:L=>F(L.target.checked),className:"h-4 w-4 rounded border-gray-300 text-band-600 focus:ring-band-500"}),"Borrower is under 18"]}),N&&e.jsxs("div",{className:"space-y-3 bg-gray-50 border border-gray-200 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-gray-500",children:P==="paper"?"The guardian is responsible for this loan â they sign the printed agreement in person.":"The guardian is responsible for this loan â they receive the agreement email and sign it."}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Guardian name"}),e.jsx(Q,{value:_,onChange:L=>
1z(L.target.value),maxLength:200})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Guardian email ",P==="paper"&&e.jsx("span",{className:"normal-case font-normal",children:"(or phone below)"})]}),e.jsx(Q,{type:"email",value:O,onChange:L=>$(L.target.value),maxLength:320})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Guardian phone ",P==="email"&&e.jsx("span",{className:"normal-case font-normal",children:"(optional)"})]}),e.jsx(Q,{value:X,onChange:L=>m(cs(L.target.value)),placeholder:"(555)555-5555"})]})]}),Se?e.jsx("p",{className:"text-sm text-gray-500",children:"Theirs for as long as they are a member. No due date."}):e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Expected return ",e.jsx("span",{className:"normal-case font-normal",children:"(optional)"})]}),e.jsx(Q,{type:"date",value:C,onChange:L=>E(L.target.value)})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Notes ",e.jsx("span",{className:"normal-case font-normal",children:"(optional)"})]}),e.jsx(Q,{value:R,onChange:L=>c(L.target.value),placeholder:"e.g. taken home for the season",maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[le&&!N&&e.jsxs(d,{type:"button",variant:"primary",disabled:ee,onClick:()=>{if(!f){v("Pick a member first");return}y(r[0],f),g()},children:["Buy now · ",nt(k.priceCents),"â¦"]}),e.jsx(d,{type:"button",variant:le&&!N?"secondary":"primary",onClick:ue,isLoading:ee,children:r.length>1?`Check out ${r.length} items`:le?"Loan for now":"Check out"}),le&&N&&e.jsxs(d,{type:"button",variant:"secondary",disabled:ee,onClick:()=>{if(!f){v("Pick a member first");return}y(r[0],f),g()},children:["Buy now · ",nt(k.priceCents),"â¦"]}),e.jsx(d,{type:"button",variant:"ghost",onClick:g,children:"Cancel"})]})]})})}function ws(a,l){if(a?.accessoriesOut)return String(a.accessoriesOut).split(/[,\n;]+/).map(o=>o.trim()).filter(Boolean).slice(0,30);const i=new Set((l?.missingAccessories||[]).map(o=>String(o.name).toLowerCase()));return String(l?.accessories||"").split(/[,\n;]+/).map(o=>o.trim()).filter(Boolean).filter(o=>!i.has(o.toLowerCase())).slice(0,30)}function Ma({loan:a,item:l,isOpen:i,onClose:o,onSaved:g}){const{showError:A,showSuccess:k}=se(),[y,v]=n.useState("good"),[j,h]=n.useState([]),[q,f]=n.useState(""),[w,r]=n.useState(""),[x,C]=n.useState(!1);n.useEffect(()=>{i&&(v("good"),f(""),r(""),h(ws(a,l).map(R=>({name:R,returned:!0}))))},[i,a,l]);async function E(){C(!0);try{await M.returnLoan(a.id,{conditionIn:y,accessories:j.length?j:null,notes:q.trim()||null,repairNotes:y==="needs_repair"&&w.trim()||null});const R=j.filter(N=>!N.returned),c=[];R.length&&c.push(`${R.length} accessor${R.length===1?"y":"ies"} still out`),y==="needs_repair"&&c.push("item flagged for repair"),k(c.length?`Return accepted â ${c.join(" · ")}`:"Return accepted â thank-you email sent to the member"),g?.()}catch(R){A(R?.message||K)}finally{C(!1)}}return a?e.jsx(de,{isOpen:i,onClose:o,title:`Check in â ${l?.name||"instrument"}`,size:"sm",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:["Returning from ",e.jsxs("span",{className:"font-semibold text-gray-800",children:[a.firstName," ",a.lastName]}),a.checkedOutAt?e.jsxs("span",{className:"text-gray-400",children:[" · out since ",String(a.checkedOutAt).slice(0,10)]}):null]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Condition on return"}),e.jsx("div",{className:"flex gap-2",children:[["good","Good"],["fair","Fair"],["needs_repair","Needs repair"]].map(([R,c])=>e.jsx(d,{type:"button",size:"sm",variant:y===R?"primary":"secondary",onClick:()=>v(R),children:c},R))}),y==="needs_repair"&&e.jsxs("div",{className:"mt-2",children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Describe repair needs"}),e.jsx("textarea",{value:w,rows:2,maxLength:1e3,onChange:R=>r(R.target.value),placeholder:"e.g. sticky valve, missing water key",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Flags this item as needing repair in the inventory and adds this note to its record."})]})]}),j.length>0&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Accessories returned"}),e.jsx("p",{className:"text-xs text-gray-400 mb-2",children:"Uncheck anything that didnât come back."}
1),e.jsx("div",{className:"space-y-1.5",children:j.map((R,c)=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:R.returned,onChange:N=>h(F=>F.map((_,z)=>z===c?{..._,returned:N.target.checked}:_)),className:"h-4 w-4 rounded border-gray-300 text-band-600 focus:ring-band-500"}),e.jsx("span",{className:R.returned?"":"text-red-700",children:R.name})]},c))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Comments ",e.jsx("span",{className:"normal-case font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:q,rows:2,maxLength:1e3,onChange:R=>f(R.target.value),placeholder:"e.g. small dent on the bell â flagged for repair",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{type:"button",onClick:E,isLoading:x,children:"Accept return"}),e.jsx(d,{type:"button",variant:"ghost",onClick:o,children:"Cancel"})]})]})}):null}function Cs({isOpen:a,onClose:l}){const{showError:i,showSuccess:o}=se(),[g,A]=n.useState(!0),[k,y]=n.useState(""),[v,j]=n.useState(""),[h,q]=n.useState([]),[f,w]=n.useState(!0),[r,x]=n.useState(!1),[C,E]=n.useState(null);n.useEffect(()=>{a&&(A(!0),Promise.resolve().then(()=>M.getLoanAgreement()).then(c=>{y(c.title||""),j(c.bodyText||""),q(Array.isArray(c.clauses)?c.clauses:[]),w(c.active!==!1),E({version:c.version,updatedAt:c.updatedAt,title:c.title})}).catch(()=>{i(ce("loan agreement")),l?.()}).finally(()=>A(!1)))},[a]);async function R(){x(!0);try{const c=await M.updateLoanAgreement({title:k.trim()||void 0,bodyText:v.trim()||void 0,clauses:h.map(N=>N.trim()).filter(Boolean),active:f});o(C&&c?.version>C.version?`Loan agreement saved as v${c.version} â anyone who signs from now on sees this wording`:"Loan agreement saved"),l?.()}catch(c){i(c?.message||K)}finally{x(!1)}}return e.jsx(de,{isOpen:a,onClose:l,title:"Loan agreement",size:"lg",children:g?e.jsx("p",{className:"text-sm text-gray-400",children:"Loadingâ¦"}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-gray-600 bg-amber-50 border border-amber-200 rounded-lg p-3",children:"When this agreement is active, every member checkout emails the borrower a no-login link showing the item details, their member record info, and these checkboxes. Signing approves the loan and notifies the equipment manager."}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:c=>w(c.target.checked),className:"h-4 w-4 rounded border-gray-300 text-band-600 focus:ring-band-500"}),"Require a signed agreement for every loan"]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Title"}),e.jsx(Q,{value:k,onChange:c=>y(c.target.value),maxLength:200})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:"Intro statement"}),e.jsx("textarea",{value:v,onChange:c=>j(c.target.value),rows:3,maxLength:5e3,className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1",children:["Agreement checkboxes ",e.jsx("span",{className:"normal-case font-normal",children:"(the borrower must check every one)"})]}),e.jsx("div",{className:"space-y-2",children:h.map((c,N)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("textarea",{value:c,rows:2,maxLength:300,onChange:F=>q(_=>_.map((z,O)=>O===N?F.target.value:z)),className:"w-full flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",className:"text-red-600 shrink-0",onClick:()=>q(F=>F.filter((_,z)=>z!==N)),children:"Remove"})]},N))}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",className:"mt-2",onClick:()=>q(c=>[...c,""]),children:"Add checkbox"})]}),C?.version&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("span",{className:"text-xs text-gray-500",children:["Current wording: v",C.version,C.updatedAt?` · last edited ${ds(C.updatedAt)}`:""]}),e.jsx(ps,{load:()=>M.getLoanAgreementVersions(),currentVersion:C.version,currentTitle:C.title,reloadKey:C.version})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{type:"button",onClick:R,isLoading:r,children:"Save changes"}),e.jsx(d,{type:"button",variant:"ghost",onClick:l,children:"Cancel"}),e.jsx(d,{type:"button",variant:"ghost",className:"ml-auto",onClick:()=>Ht("/app/api/v1/equipment/loan-agreement/print-blank"),children:"Print blank form"})]})]})})}const Ss=[{value:"new",label:"New"},{value:"excellent",label:"Excellent"},{value:"very_good",label:"Very Good"},{value:"good",label:"Good"},{value:"fair",label:"Fair"},{value:"used",label:"Used"},{value:"poor",label:"Poor"},{value:"needs_repair",label:"Needs Repair"}],Sa=a=>a!=null?ze(String(Math.round(a/100))):"",Aa=a=>{const l=String(a??"").replace(/[^0-9]/g,"");return l?Number(l)*100:null};function As({isOpen:a,item:l,createMode:i=!1,categories:o=[],stockGroups:g=[],onClose:A,onSaved:k}){const{showSuccess:y,showError:v}=se(),[j,h]=n.useState(!1),q=Ue(m=>m.currentOrg?.id),[f,w]=n.useState([]);n.useEffect(()=>{q&&Gt.list(q).then(m=>w(Array.isArray(m)?m:[])).catch(jt("storage-location picker; the sheet still saves"))},[q]);const[r,x]=n.useState({}),[C,E]=n.useState([]),R=[...o,...C.filter(m=>!o.some(P=>P.id===m.id))],[c,N]=n.useState(null),F=Ue(m=>m.currentOrg?.id);async function _(){const m=(c||"").trim();if(m)try{const P=await Pe.create({orgId:F,name:m});E(I=>[...I,P]),x(I=>({...I,categoryId:P.id})),N(null)}catch(P){v(P?.message||K)}}n.useEffect(()=>{if(!a)return;const m=l||{};x({kind:m.kind||"item",variantLabel:m.variantLabel||"",minStock:m.minStock??"",agreementRequired:m.agreementRequired!==!1,loanable:m.loanable!==!1,stockGroup:m.stockGroup||"",unitsPerPack:m.unitsPerPack??"",reorderSource:m.reorderSource||"",reorderUrl:m.reorderUrl||"",name:m.name||"",categoryId:m.categoryId||"",quantity:m.quantity??1,condition:m.condition||"good",ownership:m.ownership||"own",borrowedFrom:m.borrowedFrom||"",storageLocation:m.storageLocation||"",storageVenueId:m.storageVenueId||"",makeModel:m.makeModel||"",serialNumber:m.serialNumber||"",estimatedValue:m.kind==="stock"&&m.estimatedValueCents!=null?We(String(za(m.estimatedValueCents,m.unitsPerPack))):Sa(m.estimatedValueCents),valueAsOf:m.valueAsOf||"",originalPrice
1:Sa(m.originalPriceCents),source:m.source||"",acquiredAt:m.acquiredAt||"",inventoryTag:m.inventoryTag||"",needsRepair:m.needsRepair===!0,repairNotes:m.repairNotes||"",accessories:m.accessories||"",description:m.description||"",notes:m.notes||""})},[a,l?.id]);const z=m=>P=>{const I=P.target.type==="checkbox"?P.target.checked:P.target.value;x(T=>({...T,[m]:I}))},O=!!String(r.serialNumber||"").trim(),$=r.kind==="stock";async function X(m){if(m.preventDefault(),!(!i&&!l?.id)){if(!String(r.name||"").trim()){v("Name is required.");return}if(!j){h(!0);try{const P={kind:$?"stock":"item",variantLabel:$&&String(r.variantLabel||"").trim()||null,minStock:$&&String(r.minStock??"").trim()!==""?parseInt(r.minStock,10):null,agreementRequired:$?r.agreementRequired===!0:!0,loanable:$?r.loanable!==!1:!0,stockGroup:$&&r.stockGroup||null,unitsPerPack:$&&String(r.unitsPerPack??"").trim()!==""?parseInt(r.unitsPerPack,10):null,reorderSource:$&&String(r.reorderSource||"").trim()||null,reorderUrl:$&&String(r.reorderUrl||"").trim()||null,valueAsOf:$?null:r.valueAsOf.trim()||null,originalPriceCents:$?null:Aa(r.originalPrice),source:$?null:r.source.trim()||null,acquiredAt:$?null:r.acquiredAt||null,condition:$?"good":r.condition,name:r.name.trim(),categoryId:r.categoryId||null,quantity:O?1:parseInt(r.quantity,10)||0,ownership:r.ownership,borrowedFrom:r.ownership==="borrowed"&&r.borrowedFrom.trim()||null,storageLocation:r.storageLocation.trim()||null,storageVenueId:r.storageVenueId||null,makeModel:$?null:r.makeModel.trim()||null,serialNumber:$?null:r.serialNumber.trim()||null,estimatedValueCents:$?Nt(He(r.estimatedValue),r.unitsPerPack):Aa(r.estimatedValue),inventoryTag:r.inventoryTag.trim()||null,needsRepair:r.needsRepair===!0,repairNotes:r.repairNotes.trim()||null,accessories:r.accessories.trim()||null,description:r.description.trim()||null,notes:r.notes.trim()||null};if(i)for(const T of Object.keys(P))P[T]===null&&delete P[T];const I=i?await M.create(P):await M.update(l.id,P);y(i?"Equipment added":"Equipment updated"),k?.(I)}catch(P){v(P?.message||K)}finally{h(!1)}}}}return!l&&!i?null:e.jsx(Ia,{isOpen:a,onClose:A,title:i?"New equipment":`Edit ${l.name}`,children:e.jsxs("form",{onSubmit:X,style:{padding:"var(--bb-space-4)"},children:[e.jsx(G,{label:"What is it",children:e.jsxs("select",{value:r.kind||"item",onChange:z("kind"),style:U,"aria-label":"What is it",children:[e.jsx("option",{value:"item",children:"Instrument or item (one record each)"}),e.jsx("option",{value:"stock",children:"Stock in quantity (shirts by size, stand lights)"})]})}),$&&g.length>0&&e.jsx(G,{label:"Part of",children:e.jsxs("select",{value:r.stockGroup||"",onChange:m=>{const P=m.target.value;x(I=>({...I,stockGroup:P,name:P||I.name}))},style:U,children:[e.jsx("option",{value:"",children:"A new item"}),g.map(m=>e.jsx("option",{value:m.name,children:`${m.name} (${m.rows.length} ${m.rows.length===1?"size":"sizes"})`},m.key))]})}),e.jsx(G,{label:"Name",required:!0,children:e.jsx("input",{type:"text",value:r.name||"",onChange:z("name"),required:!0,readOnly:$&&!!r.stockGroup,style:{...U,...$&&r.stockGroup?{background:"var(--bb-surface-sunken)"}:{}},placeholder:$?"e.g. Band polo":void 0})}),$&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[e.jsxs(G,{label:"Size or variant",children:[e.jsx("input",{type:"text",value:r.variantLabel||"",onChange:z("variantLabel"),placeholder:"e.g. XL",style:U}),e.jsx("p",{style:Ge,children:"Leave blank for one size."})]}),e.jsxs(G,{label:"Reorder at or below",children:[e.jsx("input",{type:"number",min:"0",inputMode:"numeric",value:r.minStock??"",onChange:z("minStock"),placeholder:"e.g. 3",style:U}),e.jsx("p",{style:Ge,children:"Leave blank for no reminder."})]})]}),e.jsxs(G,{label:"Category",children:[e.jsxs("select",{value:r.categoryId||"",onChange:m=>{if(m.target.value==="__new__"){N("");return}z("categoryId")(m)},style:U,children:[e.jsx("option",{value:"",children:"â None â"}),R.map(m=>e.jsx("option",{value:m.id,children:m.name},m.id)),e.jsx("option",{value:"__new__",children:"+ Add new categoryâ¦"})]}),c!==null&&e.jsxs("div",{style:{display:"flex",gap:8,marginTop:8},children:[e.jsx("input",{type:"text",autoFocus:!0,value:c,placeholder:"New category name","aria-label":"New category name",onChange:m=>N(m.target.value),style:U}),e.jsx(d,{type:"button",size:"sm",onClick:_,children:"Add"}),e.jsx(d,{type:"button",size:"sm",variant:"ghost",onClick:()=>N(null),children:"Cancel"})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[$&&!i?e.jsxs(G,{label:"On hand",children:[e.jsx("div",{style:{fontSize:14,padding:"8px 0"},children:`In stock ${Math.max(0,(Number(l?.quantity)||0)-(Number(l?.onLoan)||0))} of ${Number(l?.quantity)||0}`}),e.jsx("p",{style:Ge,children:"Use Receive, Adjust count or Write off on the item to change it."})]}):e.jsxs(G,{label:$?"Quantity on hand":"Quantity",children:[e.jsx("input",{type:"number",min:"0",disabled:O,value:O?1:r.quantity??1,onChange:z("quantity"),style:{...U,opacity:O?.6:1}}),O&&e.jsx("p",{style:Ge,children:"One record per serial number."})]}),!$&&e.jsx(G,{label:"Condition",children:e.jsx("select",{value:r.condition||"good",onChange:z("condition"),style:U,children:Ss.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})})]}),!$&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[e.jsx(G,{label:"Make / Model",children:e.jsx("input",{type:"text",value:r.makeModel||"",onChange:z("makeModel"),placeholder:"e.g. Selmer",style:U})}),e.jsx(G,{label:"Serial number",children:e.jsx("input",{type:"text",value:r.serialNumber||"",onChange:z("seri
1alNumber"),style:U})})]}),$&&e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"var(--bb-space-2)",fontSize:14,marginBottom:"var(--bb-space-2)",minHeight:44},children:[e.jsx("input",{type:"checkbox",checked:r.loanable!==!1,onChange:z("loanable")}),"Members can borrow this"]}),$&&r.loanable!==!1&&e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"var(--bb-space-2)",fontSize:14,marginBottom:"var(--bb-space-3)",minHeight:44},children:[e.jsx("input",{type:"checkbox",checked:r.agreementRequired===!0,onChange:z("agreementRequired")}),"Ask for the loan agreement at checkout"]}),e.jsxs(G,{label:"Storage location",children:[e.jsxs("select",{value:r.storageVenueId||"",onChange:z("storageVenueId"),style:U,children:[e.jsx("option",{value:"",children:"â None â"}),f.map(m=>e.jsx("option",{value:m.id,children:m.name},m.id))]}),r.storageLocation&&!r.storageVenueId&&e.jsxs("div",{style:{fontSize:11,color:"var(--bb-fg-muted)",marginTop:4},children:["Legacy text: ",r.storageLocation]})]}),$&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[e.jsxs(G,{label:(parseInt(r.unitsPerPack,10)||1)>1?`What you pay for a pack of ${parseInt(r.unitsPerPack,10)}`:"What you pay per unit",children:[e.jsx("input",{type:"text",inputMode:"numeric",value:r.estimatedValue??"",onChange:m=>x(P=>({...P,estimatedValue:We(m.target.value)})),placeholder:"$31.00",style:U}),(parseInt(r.unitsPerPack,10)||1)>1&&He(r.estimatedValue)!=null&&e.jsxs("p",{style:Ge,children:["That is ",We(String(Nt(He(r.estimatedValue),r.unitsPerPack)))," each."]})]}),e.jsxs(G,{label:"Units per pack",children:[e.jsx("input",{type:"number",min:"1",inputMode:"numeric",value:r.unitsPerPack??"",onChange:z("unitsPerPack"),placeholder:"e.g. 10",style:U}),e.jsx("p",{style:Ge,children:"A box of reeds; blank for one at a time."})]}),e.jsx(G,{label:"Where to reorder",children:e.jsx("input",{type:"text",value:r.reorderSource||"",onChange:z("reorderSource"),placeholder:"e.g. Amazon",style:U})}),e.jsx(G,{label:"Reorder link",children:e.jsx("input",{type:"url",value:r.reorderUrl||"",onChange:z("reorderUrl"),placeholder:"https://â¦",style:U})})]}),!$&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[e.jsx(G,{label:"Estimated value",children:e.jsx("input",{type:"text",inputMode:"numeric",value:r.estimatedValue||"",onChange:m=>x(P=>({...P,estimatedValue:ze(m.target.value)})),placeholder:"e.g. $100",style:U})}),e.jsx(G,{label:"Value as of",children:e.jsx("input",{type:"text",value:r.valueAsOf||"",onChange:z("valueAsOf"),placeholder:"e.g. 2026",style:U})}),e.jsx(G,{label:"Original price",children:e.jsx("input",{type:"text",inputMode:"numeric",value:r.originalPrice||"",onChange:m=>x(P=>({...P,originalPrice:ze(m.target.value)})),style:U})}),e.jsx(G,{label:"Date acquired",children:e.jsx("input",{type:"date",value:r.acquiredAt||"",onChange:z("acquiredAt"),style:U})})]}),!$&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--bb-space-3)"},children:[e.jsx(G,{label:"Source (donor or vendor)",children:e.jsx("input",{type:"text",value:r.source||"",onChange:z("source"),style:U})}),e.jsx(G,{label:"Inventory tag",children:e.jsx("input",{type:"text",value:r.inventoryTag||"",onChange:z("inventoryTag"),style:U})})]}),e.jsx(G,{label:"Ownership",children:e.jsxs("select",{value:r.ownership||"own",onChange:z("ownership"),style:U,children:[e.jsx("option",{value:"own",children:"Own"}),e.jsx("option",{value:"borrowed",children:"Borrowed"})]})}),r.ownership==="borrowed"&&e.jsx(G,{label:"Borrowed from",children:e.jsx("input",{type:"text",value:r.borrowedFrom||"",onChange:z("borrowedFrom"),style:U})}),e.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"var(--bb-space-2)",padding:"var(--bb-space-3)",border:"1px solid var(--bb-border-soft)",borderRadius:"var(--bb-radius-md)",marginBottom:"var(--bb-space-3)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:r.needsRepair===!0,onChange:z("needsRepair"),style:{marginTop:2,width:18,height:18}}),e.jsx("span",{style:{fontSize:14,color:"var(--bb-fg-body)"},children:"Needs repair"})]}),r.needsRepair&&e.jsx(G,{label:"Describe repair needs",children:e.jsx("textarea",{value:r.repairNotes||"",onChange:z("repairNotes"),placeholder:"e.g. sticky valve, missing water key",rows:2,style:{...U,resize:"vertical"}})}),e.jsx(G,{label:"Accessories",children:e.jsx("textarea",{value:r.accessories||"",onChange:z("accessories"),placeholder:"e.g. Artley case, cleaning rod",rows:2,style:{...U,resize:"vertical"}})}),e.jsx(G,{label:"Description",children:e.jsx("textarea",{value:r.description||"",onChange:z("description"),rows:2,style:{...U,resize:"vertical"}})}),e.jsx(G,{label:"Notes",children:e.jsx("textarea",{value:r.notes||"",onChange:z("notes"),rows:2,style:{...U,resize:"vertical"}})}),e.jsxs("div",{style:{display:"flex",gap:"var(--bb-space-3)",marginTop:"var(--bb-space-5)"},children:[e.jsx("button",{type:"button",onClick:A,disabled:j,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:j?"wait":"pointer"},children:"Cancel"}),e.jsx("button",{type:"submit",disabled:j,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:j?"wait":"pointer"},children:j?"Savingâ¦":"Save changes"})]})]})})}function G({label:a,required:l,children:i}){return e.jsxs("div",{style:{marginBottom:"var(--bb-space-3)"},children:[e.jsxs("label",{style:{display:"block",fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--bb-fg-muted)",marginBottom:6},children:[a,l&&e.jsx("span",{style:{color:"var(--bb-danger)",marginLeft:2}
1,"aria-hidden":!0,children:"*"})]}),i]})}const U={width:"100%",minHeight:44,padding:"10px 12px",fontSize:15,borderRadius:"var(--bb-radius-md)",border:"1px solid var(--bb-border-soft)",background:"var(--bb-surface)",color:"var(--bb-fg)",fontFamily:"inherit"},Ge={margin:"6px 0 0",fontSize:12,color:"var(--bb-fg-subtle)"},Ps=864e5;function yt(a,l){const i=new Date(`${String(a).slice(0,10)}T00:00:00`),o=new Date(`${String(l).slice(0,10)}T00:00:00`);return Number.isNaN(i.getTime())||Number.isNaN(o.getTime())?null:Math.round((o-i)/Ps)}function Ls(){const a=new Date;return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}function Rs(a,{today:l=Ls()}={}){const i=a.some(r=>r.agreementRequired),o=a.map(r=>r.agreementCompletedAt).filter(Boolean).sort()[0]||null,g=a.map(r=>r.checkedOutAt).filter(Boolean).sort()[0]||null,A=a.map(r=>r.expectedReturnDate).filter(Boolean).sort()[0]||null,k=a.map(r=>r.reminderSentAt).filter(Boolean).sort().pop()||null,y=i&&!o,v=i&&o?o:g,j=A?yt(l,A):null,h=A!=null&&j<0,q=A!=null&&!h&&j<=5;let f=null;if(A&&v&&!y){const r=Math.max(1,yt(v,A)??1),x=yt(v,l)??0;f=Math.min(100,Math.max(0,Math.round(x/r*100)))}const w=y&&(yt(g,l)??0)>=5;return{required:i,signedAt:o,checkedOutAt:g,due:A,reminderSentAt:k,awaiting:y,overdue:h,dueSoon:q,daysLeft:j,pct:f,staleUnsigned:w}}function qs({state:a,alarm:l}){return a==="done"?e.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full bg-green-600",children:e.jsx("svg",{className:"h-2.5 w-2.5 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}):a==="current"?e.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-amber-500 ring-4 ring-amber-100 motion-safe:animate-pulse",children:e.jsx("svg",{className:"h-3 w-3 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6l3 2"})})}):e.jsx("span",{className:`inline-block h-4 w-4 rounded-full bg-white border-2 ${l?"border-red-400":"border-gray-300"}`})}function $s({kind:a,pct:l}){if(a==="done")return e.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-green-500"});if(a==="plain")return e.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-gray-200"});const i=a==="fill-late"?"bg-red-600":a==="fill-soon"?"bg-amber-500":"bg-teal-500";return e.jsx("div",{className:"relative flex-1 h-1.5 rounded-full bg-gray-200 overflow-hidden",children:e.jsx("div",{className:`absolute inset-y-0 left-0 rounded-full ${i}`,style:{width:`${l}%`}})})}const _t="w-28 shrink-0";function Ea({group:a,canManage:l,onCheckin:i,onNudge:o,onExtend:g,onPaper:A,onSell:k}){const y=a.map(c=>c.loan),v=y[0],j=a.map(c=>c.item).filter(Boolean),h=Rs(y),q=a.length>1,f=j.length>0&&j.every(c=>c?.kind==="stock"),w=v.guardianName||v.guardianEmail||null,r=[{key:"out",label:"Checked out",state:"done",caption:ve(String(h.checkedOutAt||"").slice(0,10))}];h.required&&r.push({key:"sign",label:h.awaiting?w?"Waiting for guardian":"Waiting for signature":w?"Signed by guardian":"Signed",state:h.awaiting?"current":"done",caption:h.awaiting?v.guardianName&&!v.guardianEmail?"Sign in person":"Not yet signed":ve(String(h.signedAt).slice(0,10))}),r.push({key:"ret",label:"Returned",state:"future",alarm:h.overdue,caption:f&&!h.due?"While a member":h.due?h.overdue?`Overdue by ${Math.abs(h.daysLeft)} ${Math.abs(h.daysLeft)===1?"day":"days"}`:h.dueSoon?h.daysLeft===0?"Due today":`Due in ${h.daysLeft} ${h.daysLeft===1?"day":"days"}`:`Due ${ve(h.due)}`:"No due date set",captionClass:h.overdue?"text-red-700 font-bold":h.dueSoon?"text-amber-700 font-semibold":h.due||f?"text-gray-400":"text-gray-400 italic"});const x=[];for(let c=0;c<r.length-1;c++){const N=c===r.length-2,F=r[c].state==="done",_=r[c+1].state==="done";F&&_?x.push({kind:"done"}):N&&h.due&&!h.awaiting?x.push({kind:h.overdue?"fill-late":h.dueSoon?"fill-soon":"fill-ok",pct:h.overdue?100:h.pct}):x.push({kind:"plain"})}const C=h.overdue?"border-l-4 border-l-red-500":h.dueSoon||h.staleUnsigned?"border-l-4 border-l-amber-400":"";let E=null;l&&o&&(h.staleUnsigned&&!(v.guardianName&&!v.guardianEmail)?E=e.jsx(d,{size:"sm",variant:"warning",onClick:()=>o(v,"agreement"),children:"Send a signing reminderâ¦"}):(h.dueSoon||h.overdue)&&!h.awaiting&&(E=h.reminderSentAt?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-gray-500",children:[e.jsx("svg",{className:"h-3.5 w-3.5 text-green-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),"Reminder sent ",ve(String(h.reminderSentAt).slice(0,10))]}),e.jsx(d,{size:"sm",variant:"ghost",onClick:()=>o(v,"extension"),children:"Send another reminderâ¦"})]}):e.jsx(d,{size:"sm",variant:h.overdue?"danger":"warning",onClick:()=>o(v,"extension"),children:"Ask about an extensionâ¦"})));const R=l&&h.awaiting?e.jsxs(e.Fragment,{children:[e.jsx(d,{size:"sm",variant:"secondary",onClick:()=>Ht(`/app/api/v1/equipment/loans/${v.id}/agreement-print`),children:"Print agreement"}),e.jsx(d,{size:"sm",variant:"secondary",onClick:()=>A&&A(v),children:"Record signed paper copy"})]}):null;return e.jsxs("div",{className:`bg-white rounded-xl border border-gray-200 p-4 sm:p-5 ${C}`,children:[e.jsxs("div",{className:"font-medium text-gray-900",children:[j[0]?j[0].variantLabel?`${j[0].name} · ${j[0].variantLabel}`:j[0].name:"Equipment",q&&e.jsxs("span",{className:"ml-1.5 text-sm font-normal text-gray-500",children:["· ",a.length," items"]})]}),e.jsxs("div",{className:"text-sm text-gray-500 mt-0.5",children:[v.firstName," ",v.lastName,w&&e.jsxs("span",{className:"text-gray-400",children:[" · Guardian: ",v.guardianName||v.guardianEmail]})]}),q&&e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:a.map(({loan:c,item:N})=>e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fe,{color:"gray",children:N?N.variantLabel?`${N.name} · ${N.variantLabel}`:N.name:"Item"}),l&&N&&e.jsx(d,{size:"sm",variant:"ghost",onClick:()=>i(c,N),children:"Mark returnedâ¦"})]},c.id))}),e.jsxs("div",{className:"mt-4 mb-1",children:[e.jsx("div",{className:"flex items-end",children:r.map(c=>e.jsx("div",{className:`${_t} text-center text-xs font-medium ${c.state==="current"?"text-amber-700":c.state==="done"?"text-gray-700":"text-gray-500"}`,children:c.label},c.key)).reduce((c,N,F)=>F===0?[N]:[...c,e.jsx("div",{className:"flex-1"},`sp${F}`),N],[])}),e.jsx("div",{className:"flex items-center mt-1.5",children:r.map(c=>e.jsx("div",{className:`${_t} flex justify-center`,children:e.jsx(qs,{state:c.state,alarm:c.alarm})},c.key)).reduce((c,N,F)=>F===0?[N]:[...c,e.jsx($s,{...x[F-1]},`seg${F}`),N],[])}),e.jsx("div",{className:"flex items-start mt-1",children:r.map(c=>e.jsx("div",{className:`${_t} text-center text-[11px] ${c.captionClass||"text-gray-400"}`,children:c.caption}
1,c.key)).reduce((c,N,F)=>F===0?[N]:[...c,e.jsx("div",{className:"flex-1"},`cp${F}`),N],[])})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[E,R,l&&g&&!f&&e.jsx(d,{size:"sm",variant:"ghost",onClick:()=>g(v),children:h.due?"Extend loanâ¦":"Set a due dateâ¦"}),!q&&l&&f&&k&&j[0]&&e.jsx(d,{size:"sm",variant:"secondary",onClick:()=>k(v,j[0]),children:"Sold to memberâ¦"}),!q&&l&&j[0]&&e.jsx(d,{size:"sm",variant:"ghost",className:"ml-auto",onClick:()=>i(v,j[0]),children:"Mark returnedâ¦"})]})]})}function Oa({isOpen:a,target:l,onClose:i,onSent:o}){const{showSuccess:g,showError:A}=se(),[k,y]=n.useState(!1),[v,j]=n.useState(!1),[h,q]=n.useState(""),[f,w]=n.useState(""),r=l?.kind||"extension",x=l?.loan?.id;n.useEffect(()=>{!a||!x||(y(!0),q(""),w(""),M.remindPreview(x,r).then(E=>{q(E?.subject||""),w(E?.message||"")}).catch(()=>A("Couldnât load the message. Close and try again.")).finally(()=>y(!1)))},[a,x,r]);async function C(){j(!0);try{r==="agreement"?await M.resendLoanAgreement(x,{message:f}):await M.remindLoan(x,{message:f}),g(r==="agreement"?"Signing reminder sent.":"Check-in email sent."),o()}catch(E){A(E.message||K)}finally{j(!1)}}return e.jsx(de,{isOpen:a,onClose:i,title:r==="agreement"?"Send a signing reminder":"Check in with the borrower",size:"lg",children:k?e.jsx("p",{className:"text-sm text-gray-400 py-6 text-center",children:"Preparing the messageâ¦"}):e.jsxs("div",{className:"space-y-3",children:[h&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold uppercase tracking-wide text-gray-400 mb-1",children:"Subject"}),e.jsx("p",{className:"text-sm text-gray-700",children:h})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold uppercase tracking-wide text-gray-400 mb-1",children:"Message"}),e.jsx("textarea",{value:f,onChange:E=>w(E.target.value),rows:9,className:"w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:r==="agreement"?"The item details and the signing button are attached below your message automatically.":"Sent with your email as the reply-to, so their answer comes straight to you."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{variant:"primary",size:"sm",isLoading:v,disabled:!f.trim(),onClick:C,children:"Send"}),e.jsx(d,{variant:"secondary",size:"sm",type:"button",onClick:i,children:"Cancel"})]})]})})}function Da({isOpen:a,target:l,onClose:i,onSaved:o}){const{showSuccess:g,showError:A}=se(),[k,y]=n.useState(!1),[v,j]=n.useState(""),h=l?.loan,q=!!h?.expectedReturnDate,f=!!h?.batchId;n.useEffect(()=>{a&&j(h?.expectedReturnDate||"")},[a,h?.expectedReturnDate]);async function w(r){y(!0);try{await M.extendLoan(h.id,{expectedReturnDate:r}),g(r?`Due date set to ${r}.`:"Due date removed â open-ended loan."),o()}catch(x){A(x.message||K)}finally{y(!1)}}return e.jsx(de,{isOpen:a,onClose:i,title:q?"Extend the loan":"Set a due date",size:"sm",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-semibold uppercase tracking-wide text-gray-400 mb-1",children:"Due back"}),e.jsx(Q,{type:"date",value:v,onChange:r=>j(r.target.value)}),f&&e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Applies to every item in this loan."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{variant:"primary",size:"sm",isLoading:k,disabled:!v,onClick:()=>w(v),children:"Save changes"}),e.jsx(d,{variant:"secondary",size:"sm",type:"button",onClick:i,children:"Cancel"}),q&&e.jsx(d,{variant:"ghost",size:"sm",type:"button",className:"ml-auto",isLoading:k,onClick:()=>w(null),children:"Remove due date"})]})]})})}const Is=[{value:"",label:"Condition unchanged"},{value:"new",label:"New"},{value:"excellent",label:"Excellent"},{value:"very_good",label:"Very Good"},{value:"good",label:"Good"},{value:"fair",label:"Fair"},{value:"used",label:"Used"},{value:"poor",label:"Poor"}],wt=()=>Qt();function zs(a){const l=parseFloat(String(a).replace(/[$,]/g,""));return Number.isFinite(l)?Math.round(l*100):null}function Fa({isOpen:a,item:l,onClose:i,onSaved:o}){const{showSuccess:g,showError:A}=se(),[k,y]=n.useState(!1),[v,j]=n.useState(""),[h,q]=n.useState(wt()),[f,w]=n.useState("");n.useEffect(()=>{a&&(j(""),q(wt()),w(l?.repairNotes||""))},[a,l]);async function r(){y(!0);try{await M.createRepair(l.id,{vendor:v||null,sentAt:h||null,description:f||null}),g("Sent for repair."),o()}catch(x){A(x.message||K)}finally{y(!1)}}return l?e.jsx(de,{isOpen:a,onClose:i,title:`Send for repair â ${l.name}`,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Q,{label:"Repair shop / vendor",value:v,onCh
1ange:x=>j(x.target.value),placeholder:"e.g. Music & Arts, Denver"}),e.jsx(Q,{label:"Date sent",type:"date",value:h,onChange:x=>q(x.target.value)}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"What needs fixing"}),e.jsx("textarea",{value:f,onChange:x=>w(x.target.value),rows:3,className:"w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"The item shows as At repair until you mark it repaired."}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{onClick:r,isLoading:k,children:"Send for repair"}),e.jsx(d,{variant:"secondary",type:"button",onClick:i,children:"Cancel"})]})]})}):null}function Va({isOpen:a,item:l,onClose:i,onSaved:o}){const{showSuccess:g,showError:A}=se(),[k,y]=n.useState(!1),[v,j]=n.useState(wt()),[h,q]=n.useState(""),[f,w]=n.useState(""),[r,x]=n.useState(""),C=l?.openRepair;n.useEffect(()=>{a&&(j(wt()),q(""),w(""),x(""))},[a,l]);async function E(){y(!0);try{const R={returnedAt:v||null,costCents:zs(h),outcomeNotes:f||null,condition:r||null};C?await M.completeRepair(C.id,R):await M.createRepair(l.id,R),g("Marked repaired."),o()}catch(R){A(R.message||K)}finally{y(!1)}}return l?e.jsx(de,{isOpen:a,onClose:i,title:`Mark repaired â ${l.name}`,children:e.jsxs("div",{className:"space-y-4",children:[C&&e.jsxs("p",{className:"text-sm text-gray-500",children:["Out for repair",C.vendor?` at ${C.vendor}`:"",C.sentAt?` since ${String(C.sentAt).slice(0,10)}`:"","."]}),e.jsx(Q,{label:"Date repaired",type:"date",value:v,onChange:R=>j(R.target.value)}),e.jsx(Q,{label:"Cost (optional)",value:h,onChange:R=>q(R.target.value),placeholder:"$0.00"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"What was done (optional)"}),e.jsx("textarea",{value:f,onChange:R=>w(R.target.value),rows:2,className:"w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-band-500 focus:border-band-500"})]}),e.jsx(he,{label:"Condition after repair",value:r,onChange:R=>x(R.target.value),options:Is}),e.jsx("p",{className:"text-xs text-gray-500",children:"This clears the needs-repair flag; what was wrong stays on the repair record below the item."}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{onClick:E,isLoading:k,children:"Mark repaired"}),e.jsx(d,{variant:"secondary",type:"button",onClick:i,children:"Cancel"})]})]})}):null}const Pa=a=>a==null?null:`$${(a/100).toFixed(2)}`;function Ts({equipmentId:a,refreshToken:l}){const[i,o]=n.useState(void 0);return n.useEffect(()=>{let g=!1;return M.repairs(a).then(A=>{g||o(Array.isArray(A)?A:[])}).catch(()=>{g||o([])}),()=>{g=!0}},[a,l]),!i||i.length===0?null:e.jsxs("div",{className:"mt-3 text-sm",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Repair history"}),e.jsx("div",{className:"mt-1 space-y-1.5",children:i.map(g=>e.jsxs("div",{className:"text-xs text-gray-500",children:[g.returnedAt?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-gray-700 font-medium",children:["Repaired ",String(g.returnedAt).slice(0,10)]}),g.sentAt&&e.jsxs(e.Fragment,{children:[" · sent ",String(g.sentAt).slice(0,10)]}),g.vendor&&e.jsxs(e.Fragment,{children:[" · ",g.vendor]}),Pa(g.costCents)&&e.jsxs(e.Fragment,{children:[" · ",Pa(g.costCents)]})]}):e.jsxs("span",{className:"text-amber-700 font-medium",children:["Out for repair",g.vendor?` â ${g.vendor}`:"",g.sentAt?` since ${String(g.sentAt).slice(0,10)}`:""]}),g.description&&e.jsx("div",{className:"text-gray-400 italic mt-0.5",children:g.description}),g.outcomeNotes&&e.jsx("div",{className:"text-gray-400 mt-0.5",children:g.outcomeNotes})]},g.id))})]})}const La={received:{title:"Receive",verb:"Received",hint:"Units added to the box (a delivery, a donation).",label:"How many arrived"},adjusted:{title:"Adjust count",verb:"Adjusted",hint:"A recount. Enter the difference: 3 for three more than the page shows, -2 for two fewer.",label:"Difference"},lost:{title:"Write off",verb:"Written off",hint:"Units gone for good (lost, worn out, given away).",label:"How many"},sold:{title:"Record sales",verb:"Sold",hint:"Sold at the door or outside the ledger. This keeps the count honest; book the money under Payments.",label:"How many sold"}};function Ba({isOpen:a,onClose:l,item:i,kind:o="received",onDone:g}){const{showSuccess:A,showError:k}=se(),[y,v]=n.useState(""),[j,h]=n.useState(""),[q,f]=n.useState(!1),[w,r]=n.useState(!1),x=o==="received"&&Number(i?.unitsPerPack)>1?Number(i.unitsPerPack):null,C=La[o]||La.received;function E(){v(""),h(""),r(!1),l()}async function R(){const c=parseInt(y,10);if(!Number.isInteger(c)||c===0){k("Enter a count");return}if(o!=="adjusted"&&c<0){k("Enter a positive count");return}const N=x&&w?c*x:c,F=x&&w?[`${c} ${c===1?"pack":"packs"} of ${x}
1`,j.trim()].filter(Boolean).join(" · "):j.trim()||null;f(!0);try{const _=o==="sold"?await M.doorSales(i.id,{count:N,reason:F}):await M.recordMovement(i.id,{kind:o,count:N,reason:F});A(`${C.verb} ${Math.abs(N)} · ${Te(_)}`),g?.(_),E()}catch(_){k(_?.message||K)}finally{f(!1)}}return i?e.jsx(de,{isOpen:a,onClose:E,title:`${C.title} â ${je(i)}`,size:"sm",footer:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{type:"button",onClick:R,isLoading:q,children:C.title}),e.jsx(d,{type:"button",variant:"ghost",onClick:E,children:"Cancel"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600",children:[C.hint," ",e.jsxs("span",{className:"text-gray-400",children:[Te(i)," now."]})]}),x&&e.jsx(he,{label:"Count in",value:w?"packs":"units",onChange:c=>r(c.target.value==="packs"),options:[{value:"units",label:"Single units"},{value:"packs",label:`Packs of ${x}`}]}),e.jsx(Q,{label:x&&w?"How many packs arrived":C.label,type:"number",inputMode:"numeric",min:o==="adjusted"?void 0:1,value:y,onChange:c=>v(c.target.value),autoFocus:!0}),e.jsx(Q,{label:"Reason (optional)",value:j,onChange:c=>h(c.target.value),maxLength:300,placeholder:o==="received"?"e.g. order from Lands End":o==="lost"?"e.g. torn, discarded":o==="sold"?"e.g. Fall concert table":"e.g. recount at inventory day"})]})}):null}function _a({isOpen:a,onClose:l,item:i}){const{showError:o}=se(),[g,A]=n.useState(null);if(n.useEffect(()=>{if(!a||!i?.id)return;let y=!0;return M.listMovements(i.id).then(v=>{y&&A(Array.isArray(v)?v:[])}).catch(()=>{y&&(A([]),o(ce("stock history")))}),()=>{y=!1}},[a,i?.id]),!i)return null;const k=y=>y.kind==="received"?"Received":y.kind==="lost"?"Written off":y.kind==="sold"?"Sold":y.kind==="refunded"?"Refunded":"Adjusted";return e.jsxs(de,{isOpen:a,onClose:l,title:`History â ${je(i)}`,size:"md",footer:e.jsx("div",{className:"flex gap-2",children:e.jsx(d,{type:"button",variant:"ghost",onClick:l,children:"Close"})}),children:[e.jsxs("p",{className:"text-sm text-gray-500 mb-3",children:[Te(i),"."]}),g==null?e.jsx("p",{className:"text-sm text-gray-400",children:"Loadingâ¦"}):g.length===0?e.jsx(Ie,{size:"compact",title:"No movements recorded yet."}):e.jsx("ul",{className:"divide-y divide-gray-100 text-sm",children:g.map(y=>e.jsxs("li",{className:"py-2 flex items-start gap-3",children:[e.jsx("span",{className:`tabular-nums font-semibold w-12 text-right shrink-0 ${y.count<0?"text-red-700":"text-gray-900"}`,children:y.count>0?`+${y.count}`:y.count}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"text-gray-800",children:k(y)}),y.memberName&&e.jsxs("span",{className:"text-gray-700",children:[" to ",y.memberName]}),y.reason&&e.jsxs("span",{className:"text-gray-500",children:[" · ",y.reason]}),e.jsxs("span",{className:"block text-xs text-gray-400",children:[ve(String(y.createdAt||"").slice(0,10)),y.recordedBy?` · recorded by ${y.recordedBy}`:""]})]})]},y.id))})]})}const Ms=[{value:"cash",label:"Cash, paid now"},{value:"check",label:"Check, paid now"},{value:"later",label:"Later â bill them, they pay online or by check"}];function Ga({isOpen:a,onClose:l,item:i,product:o,loan:g=null,memberId:A="",onDone:k}){const{showSuccess:y,showError:v}=se(),[j,h]=n.useState([]),[q,f]=n.useState(""),[w,r]=n.useState("cash"),[x,C]=n.useState(""),[E,R]=n.useState(""),[c,N]=n.useState(""),[F,_]=n.useState("1"),[z,O]=n.useState(!1);n.useEffect(()=>{a&&(g||$a.list({limit:500}).then(I=>{const T=Array.isArray(I)?I:I?.members||[];h(T.filter(Y=>Y.memberStatus!=="retired"))}).catch(()=>h([])))},[a,g]);function $(){f(""),r("cash"),C(""),R(""),N(""),_("1"),l()}const X=g?g.memberId:q||A,m=g?`${g.firstName} ${g.lastName}`:null;async function P(){if(!X){v("Pick the member");return}if(w==="check"&&!x.trim()){v("Enter the check number");return}const I=g?1:parseInt(F,10)||0;if(!g&&(I<1||I>(i.inStock||0))){v(`Enter how many, up to the ${i.inStock||0} in stock`);return}O(!0);try{const T={memberId:X,method:w,quantity:I,checkNumber:x.trim()||null,receivedAt:E||null,note:c.trim()||null},Y=g?await M.sellFromLoan(g.id,T):await M.sell(i.id,T),ee=m||j.find(ne=>ne.id===X)?.firstName||"member",te=I>1?`${I} à ${je(i)}`:je(i),re=nt(o.priceCents*I);y(w==="later"?`${te} sold to ${ee} · ${re} owed`:`${te} sold to ${ee} · ${re} ${w}`),k?.(Y),$()}catch(T){v(T?.message||K)}finally{O(!1)}}return!i||!o?null:e.jsx(de,{isOpen:a,onClose:$,title:g?`Sold to member â ${je(i)}`:`Sell to member â ${je(i)}`,size:"sm",footer:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{type:"button",onClick:P,isLoading:z,children:w==="later"?"Record sale and bill":"Record sale"}),e.jsx(d,{type:"button",variant:"ghost",onClick:$,children:"Cancel"})]}),children:e.jsxs("div",{className:"space-y-4",children:[i.photoUrl&&e.jsx("img",{src:i.photoUrl,alt:"",className:"w-full max-h-40 object-contain rounded-lg border border-gray-200 bg-gray-50"}),e.jsxs("p",{className:"text-sm text-gray-600",children:[o.name," · ",e.jsx("span",{className:"font-semibold text-gray-900",children:nt(o.priceCents)}),!g&&(parseInt(F,10)||0)>1?e.jsxs("span",{className:"font-semibold text-gray-900",children:[" à ",parseInt(F,10)," = ",nt(o.priceCents*parseInt(F,10))]}):"",g?e.jsxs("span",{className:"text-gray-400",children:[" · out with ",m," since ",ve(String(g.checkedOutAt||"").slice(0,10)),"; the loan closes and the count is unchanged."]}):e.jsxs("span",{className:"text-gray-400",children:[" · ",Te(i),"."]})]}),!g&&e.jsx(Q,{label:"How many",type:"number",min:1,max:i.inStock||
11,inputMode:"numeric",value:F,onChange:I=>_(I.target.value),hint:`${i.inStock||0} in stock`}),!g&&e.jsx(he,{label:"Member",value:q||A,onChange:I=>f(I.target.value),placeholder:"Select memberâ¦",options:j.map(I=>({value:I.id,label:`${I.firstName} ${I.lastName}`}))}),e.jsx(he,{label:"How they pay",value:w,onChange:I=>r(I.target.value),options:Ms}),w==="check"&&e.jsx(Q,{label:"Check number",value:x,onChange:I=>C(I.target.value),maxLength:40}),w!=="later"&&e.jsx(Q,{label:"Date received",type:"date",value:E,onChange:I=>R(I.target.value),max:Qt(),hint:"Leave blank for today"}),e.jsx(Q,{label:"Note (optional)",value:c,onChange:I=>N(I.target.value),maxLength:500})]})})}const Ua={new:{bg:"var(--bb-success-soft)",fg:"var(--bb-success-ink)",label:"New"},excellent:{bg:"var(--bb-success-soft)",fg:"var(--bb-success-ink)",label:"Excellent"},very_good:{bg:"var(--bb-success-soft)",fg:"var(--bb-success-ink)",label:"Very good"},used:{bg:"var(--bb-surface-sunken)",fg:"var(--bb-fg-muted)",label:"Used"},good:{bg:"var(--bb-success-soft)",fg:"var(--bb-success-ink)",label:"Good"},fair:{bg:"var(--bb-warning-soft)",fg:"var(--bb-warning-ink)",label:"Fair"},poor:{bg:"var(--bb-warning-soft)",fg:"var(--bb-warning-ink)",label:"Poor"},needs_repair:{bg:"var(--bb-danger-soft)",fg:"var(--bb-danger-ink)",label:"Needs repair"}};function Ut(a,l=!1){return a==null?null:"$"+(a/100).toLocaleString("en-US",l?{minimumFractionDigits:2}:{maximumFractionDigits:0})}function Es(){const a=Ue(b=>b.currentOrg?.id),l=kt(Ue(b=>b.currentOrg?.planTier),"equipmentLoans"),i=kt(Ue(b=>b.currentOrg?.planTier),"payments"),[o,g]=n.useState([]),[A,k]=n.useState(null);n.useEffect(()=>{a&&Promise.resolve().then(()=>M.stockGroups()).then(b=>g(Array.isArray(b)?b:[])).catch(jt("stock groups are decoration on the list"))},[a]);const{showError:y,showSuccess:v}=se(),{canFully:j}=Jt(),h=j("equipment:create"),[q,f]=n.useState([]),[w,r]=n.useState([]),[x,C]=n.useState(!0),[E,R]=n.useState(""),[c,N]=n.useState(""),[F,_]=n.useState(!1),[z,O]=n.useState(null),[$,X]=n.useState(null),[m,P]=n.useState(!1),[I,T]=n.useState("inventory"),[Y,ee]=n.useState([]),[te,re]=n.useState(null),[ne,ie]=n.useState(null),[Se,le]=n.useState(null),[Re,ue]=n.useState(null),[L,J]=n.useState(null),[ae,me]=n.useState(null),[lt,ke]=n.useState(null);function qe(){return M.list(a,{}).then(b=>{const V=Array.isArray(b)?b:[];return f(V),O(W=>W?V.find(oe=>oe.id===W.id)||W:null),V}).catch(()=>y(ce("equipment")))}function xe(){return M.activeLoans().then(b=>ee(Array.isArray(b)?b:[])).catch(()=>y(ce("loans")))}n.useEffect(()=>{a&&(C(!0),Promise.all([M.list(a,{}).catch(()=>[]),Pe.list(a).catch(()=>[]),M.activeLoans().catch(()=>[])]).then(([b,V,W])=>{f(Array.isArray(b)?b:[]),r(Array.isArray(V)?V:[]),ee(Array.isArray(W)?W:[])}).catch(()=>y(ce("equipment"))).finally(()=>C(!1)))},[a]);const Me={};for(const b of Y)(Me[b.equipmentId]||=[]).push(b);const Ee=(()=>{const b=new Map;for(const V of Y){const W=V.batchId||V.id;b.has(W)||b.set(W,[]),b.get(W).push({loan:V,item:q.find(oe=>oe.id===V.equipmentId)||null})}return[...b.values()]})(),Ye=E.trim().toLowerCase(),Oe=q.filter(b=>c&&b.categoryId!==c||F&&b.needsRepair!==!0?!1:Ye?[b.name,b.storageVenueName,b.storageLocation,b.categoryName,b.makeModel,b.serialNumber,b.inventoryTag].filter(Boolean).join(" ").toLowerCase().includes(Ye):!0);return e.jsxs("div",{children:[e.jsxs("div",{role:"tablist","aria-label":"Equipment views",style:{display:"flex",flexWrap:"wrap",gap:6,padding:"var(--bb-space-3) var(--bb-space-4) 0",background:"var(--bb-bg)"},children:[e.jsx(rt,{active:I==="inventory",onClick:()=>T("inventory"),label:"Inventory"}),e.jsx(rt,{active:I==="loans",onClick:()=>T("loans"),label:`Loans${Ee.length?` (${Ee.length})`:""}`}),h&&e.jsxs("span",{style:{marginLeft:"auto",display:"flex",gap:6},children:[I==="inventory"&&e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>P(!0),children:"New item"}),l&&e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>re({}),children:"New loanâ¦"})]})]}),I==="inventory"&&e.jsxs(e.Fragment,{children:[e.jsx("form",{onSubmit:b=>b.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(Fs,{}),e.jsx("input",{type:"search",value:E,onChange:b=>R(b.target.value),placeholder:"Search name, make, serial","aria-label":"Search equipment",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"}})]})}),(w.length>
10||q.some(b=>b.needsRepair))&&e.jsxs("div",{role:"tablist","aria-label":"Filter equipment",style:{display:"flex",gap:6,padding:"0 var(--bb-space-4) var(--bb-space-3)",overflowX:"auto",background:"var(--bb-bg)"},children:[e.jsx(rt,{active:!c,onClick:()=>N(""),label:"All"}),w.map(b=>e.jsx(rt,{active:c===b.id,onClick:()=>N(b.id),label:b.name},b.id)),e.jsx(rt,{active:F,onClick:()=>_(b=>!b),label:"Needs repair",danger:!0})]}),x?e.jsx(wa,{variant:"music",count:4}):Oe.length===0?e.jsx("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",color:"var(--bb-fg-muted)"},children:E||c||F?"No equipment matches.":"No equipment tracked yet."}):e.jsx("ul",{"data-testid":"mobile-equipment-list",style:{listStyle:"none",margin:0,padding:0,background:"var(--bb-surface)"},children:Oe.map(b=>e.jsx(Os,{item:b,onLoan:(Me[b.id]||[]).length>0,onOpen:()=>O(b)},b.id))})]}),I==="loans"&&e.jsxs("div",{style:{padding:"var(--bb-space-3) var(--bb-space-4)"},children:[!l&&e.jsx("p",{style:{fontSize:"var(--bb-text-sm)",color:"var(--bb-fg-muted)",marginBottom:"var(--bb-space-3)"},children:"Checking instruments out to members, with an online or paper agreement, is on the Complete plan. Anything already checked out stays here and can still be marked returned."}),x?e.jsx(wa,{variant:"music",count:3}):Ee.length===0?e.jsx("div",{style:{padding:"var(--bb-space-6)",background:"var(--bb-surface)",border:"1px solid var(--bb-border-soft)",borderRadius:"var(--bb-radius-lg)",textAlign:"center",color:"var(--bb-fg-muted)"},children:"Nothing checked out to members."}):e.jsx("div",{className:"space-y-3",children:Ee.map(b=>e.jsx(Ea,{group:b,canManage:h,onCheckin:(V,W)=>ie({loan:V,item:W}),onNudge:l?(V,W)=>le({loan:V,kind:W}):void 0,onExtend:l?V=>ue({loan:V}):void 0,onPaper:V=>J({loan:V}),onSell:i&&ye(o,b[0].item)?(V,W)=>k({item:W,loan:V,product:ye(o,W)}):void 0},b[0].loan.batchId||b[0].loan.id))})]}),z&&e.jsx(Ds,{item:z,loans:Me[z.id]||[],onClose:()=>O(null),onEdit:()=>X(z),onCheckout:l?b=>re(b):void 0,onCheckin:(b,V)=>ie({loan:b,item:V}),onRepairSend:b=>me(b),onRepairDone:b=>ke(b),onStockChanged:b=>{qe(),xe(),b?.id&&O(b)},product:i?ye(o,z):null,onSell:b=>k({item:b,product:ye(o,b)})}),e.jsx(Ga,{isOpen:!!A,onClose:()=>k(null),item:A?.item,product:A?.product,loan:A?.loan||null,onDone:()=>{qe(),xe(),O(null)}}),e.jsx(As,{isOpen:!!$||m,item:$,createMode:m,categories:w,stockGroups:o,onClose:()=>{X(null),P(!1)},onSaved:b=>{m?f(V=>[b,...V]):(f(V=>V.map(W=>W.id===b.id?b:W)),O(V=>V&&V.id===b.id?b:V)),X(null),P(!1)}}),e.jsx(Ta,{item:te&&te.id?te:null,items:q,activeLoans:Me,isOpen:!!te,onClose:()=>re(null),onSaved:()=>{re(null),xe()}}),e.jsx(Ma,{loan:ne?.loan,item:ne?.item,isOpen:!!ne,onClose:()=>ie(null),onSaved:()=>{ie(null),xe(),qe()}}),e.jsx(Oa,{isOpen:!!Se,target:Se,onClose:()=>le(null),onSent:()=>{le(null),xe()}}),e.jsx(Da,{isOpen:!!Re,target:Re,onClose:()=>ue(null),onSaved:()=>{ue(null),xe()}}),e.jsx(Qe,{isOpen:!!L,title:"Record Signed Paper Copy",message:"Mark this loan agreement as signed on paper? This completes the whole loan (every item on it), exactly like an online signature â keep the signed sheet in your files.",confirmLabel:"Record signature",onConfirm:async()=>{try{await M.recordPaperSignature(L.loan.id),v("Paper signature recorded â loan approved"),J(null),xe()}catch(b){y(b.message||K)}},onClose:()=>J(null)}),e.jsx(Fa,{isOpen:!!ae,item:ae,onClose:()=>me(null),onSaved:()=>{me(null),qe()}}),e.jsx(Va,{isOpen:!!lt,item:lt,onClose:()=>ke(null),onSaved:()=>{ke(null),qe()}})]})}function rt({active:a,onClick:l,label:i,danger:o=!1}){const g=o?"var(--bb-danger)":"var(--bb-primary)";return e.jsx("button",{type:"button",role:"tab","aria-selected":a,onClick:l,style:{flex:"0 0 auto",minHeight:44,padding:"0 16px",fontSize:13,fontWeight:600,borderRadius:"var(--bb-radius-pill)",border:"1px solid",borderColor:a?g:"var(--bb-border-soft)",background:a?g:"var(--bb-surface)",color:a?"#fff":o?"var(--bb-danger-ink)":"var(--bb-fg-muted)",cursor:"pointer",display:"inline-flex",alignItems:"center",fontFamily:"inherit"},children:i})}function Os({item:a,onOpen:l,onLoan:i=!1}
1){const o=Ua[a.condition]||{bg:"var(--bb-surface-sunken)",fg:"var(--bb-fg-muted)",label:a.condition||"â"};return e.jsx("li",{style:{borderTop:"1px solid var(--bb-border-soft)"},children:e.jsxs("button",{type:"button",onClick:l,style:{width:"100%",textAlign:"left",display:"flex",alignItems:"center",gap:"var(--bb-space-3)",minHeight:68,padding:"12px var(--bb-space-4)",background:"none",border:"none",cursor:"pointer",fontFamily:"inherit"},children:[a.photoUrl&&e.jsx("img",{src:a.photoUrl,alt:"",style:{width:40,height:40,borderRadius:"var(--bb-radius-md)",objectFit:"cover",border:"1px solid var(--bb-border-soft)",flexShrink:0}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:15,fontWeight:600,color:"var(--bb-fg)"},children:je(a)}),e.jsxs("div",{style:{marginTop:2,fontSize:12,color:"var(--bb-fg-muted)",display:"flex",flexWrap:"wrap",gap:10},children:[a.categoryName&&e.jsx("span",{children:a.categoryName}),Je(a)?e.jsx("span",{children:Te(a)}):e.jsxs("span",{children:["Qty ",a.quantity]}),(a.storageVenueName||a.storageLocation)&&e.jsxs("span",{children:["· ",a.storageVenueName||a.storageLocation]}),a.makeModel&&e.jsxs("span",{children:["· ",a.makeModel]}),a.estimatedValueCents!=null&&e.jsxs("span",{children:["· ",Ut(a.estimatedValueCents)]})]})]}),Je(a)&&Le(a).lowStock&&e.jsx("span",{"aria-label":"Reorder",style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:"var(--bb-radius-pill)",background:"var(--bb-warning-soft)",color:"var(--bb-warning-ink)",fontSize:11,fontWeight:600,whiteSpace:"nowrap",flexShrink:0},children:"Reorder"}),i&&!Je(a)&&e.jsx("span",{"aria-label":"On loan",style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:"var(--bb-radius-pill)",background:"var(--bb-primary-soft, var(--bb-surface-sunken))",color:"var(--bb-primary)",fontSize:11,fontWeight:600,whiteSpace:"nowrap",flexShrink:0},children:"On loan"}),a.needsRepair&&e.jsx("span",{"aria-label":"Needs repair",title:a.repairNotes||"Needs repair",style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:"var(--bb-radius-pill)",background:"var(--bb-danger-soft)",color:"var(--bb-danger-ink)",fontSize:11,fontWeight:600,whiteSpace:"nowrap",flexShrink:0},children:"Repair"}),e.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",borderRadius:"var(--bb-radius-pill)",background:o.bg,color:o.fg,fontSize:11,fontWeight:600,whiteSpace:"nowrap",flexShrink:0},children:o.label}),e.jsx("span",{"aria-hidden":"true",style:{color:"var(--bb-fg-subtle)",fontSize:18,flexShrink:0},children:"âº"})]})})}function Z({label:a,value:l}){return l==null||l===""?null:e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--bb-fg-subtle)"},children:a}),e.jsx("div",{style:{fontSize:14,color:"var(--bb-fg)",marginTop:2,overflowWrap:"anywhere"},children:l})]})}function Ds({item:a,loans:l=[],onClose:i,onEdit:o,onCheckout:g,onCheckin:A,onRepairSend:k,onRepairDone:y,onStockChanged:v,product:j=null,onSell:h}){const[q,f]=n.useState(null),[w,r]=n.useState(!1),{showSuccess:x,showError:C}=se(),{canFully:E}=Jt(),R=E("equipment:create"),[c,N]=n.useState(void 0),[F,_]=n.useState(!1),[z,O]=n.useState(null),$=n.useRef(null),X=Ua[a.condition]||{label:a.condition||"â"},m=a.loanable!==!1&&l.length<(a.quantity||1);n.useEffect(()=>{let T=!0;return M.listPhotos(a.id).then(Y=>{T&&N(Array.isArray(Y)?Y:[])}).catch(()=>{T&&N([])}),()=>{T=!1}},[a.id]);async function P(T){if(T){_(!0);try{const Y=await M.uploadPhoto(a.id,T);N(ee=>[...ee||[],Y]),x("Photo added")}catch(Y){C(Y?.message||K)}finally{_(!1),$.current&&($.current.value="")}}}async function I(T){try{await M.deletePhoto(a.id,T),N(Y=>(Y||[]).filter(ee=>ee.id!==T)),x("Photo removed")}catch(Y){C(Y?.message||it)}finally{O(null)}}return e.jsxs(Ia,{isOpen:!0,onClose:i,title:je(a),children:[e.jsx(Ba,{isOpen:!!q,onClose:()=>f(null),item:a,kind:q||"received",onDone:T=>v?.(T)}),e.jsx(_a,{isOpen:w,onClose:()=>r(!1),item:a}),e.jsxs("div",{style:{padding:"var(--bb-space-4)"},children:[R&&e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:8,justifyContent:"flex-end",marginBottom:"var(--bb-space-3)"},children:[m&&g&&e.jsx(d,{type:"button",variant:"primary",size:"sm",onClick:()=>g(a),children:"Check out"}),Je(a)&&j&&h&&Le(a).inStock>0&&e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>h(a),children:"Sell to memberâ¦"}),Je(a)&&e.jsxs(e.Fragment,{children:[e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>f("received"),children:"Receiveâ¦"}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",onClick:()=>f("adjusted"),children:"Adjust countâ¦"}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",onClick:()=>f("lost"),children:"Write offâ¦"}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!0),children:"History"})]}),a.needsRepair&&k&&e.jsx(d,{type:"button",variant:"warning",size:"sm",onClick:()=>k(a),children:"Send for repair"}),a.needsRepair&&y&&e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>y(a),children:"Mark repaired"}),o&&e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:o,children:"Edit details"})]}),a.needsRepair&&e.jsxs("div",{style:{padding:"10px 12px",marginBottom:"var(--bb-space-4)",background:"var(--bb-danger-soft)",color:"var(--bb-danger-ink)",borderRadius:"var(--bb-radius-md)",fontSize:13},children:[e.jsx("strong",{children:"Needs repair"}),a.repairNotes?` â ${a.repairNotes}`:""]}),l.length>0&&e.jsxs("div",{style:{padding:"10px 12px",marginBottom:"var(--bb-space-4)",background:"var(--bb-surface-sunken)",borderRadius:"var(--bb-radius-md)",fontSize:13},children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--bb-fg-subtle)",marginBottom:6},children:"On loan"}),l.map(T=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:32},children:[e.jsxs("span",{style:{flex:1,minWidth:0},children:[T.firstName," ",T.lastName,e.jsxs("span",{style:{color:"var(--bb-fg-muted)"},children:[" · since ",ve(String(T.checkedOutAt||"").slice(0,10)),T.expectedReturnDate?` · due ${ve(T.expectedReturnDate)}`:""]}),T.agreementRequired&&!T.agreementCompletedAt&&e.jsx("span",{style:{marginLeft:6,padding:"1px 7px",borderRadius:"var(--bb-radius-pill)",background:"var(--bb-warning-soft)",color:"var(--bb-warning-ink)",fontSize:10,fontWeight:700},children:"Awaiting signature"})]}),R&&A&&e.jsx(d,{type:"button",variant:"ghost",size:"sm",onClick:()=>A(T,a),children:"Mark returnedâ¦"})]},T.id))]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px 16px"},children:[e.jsx(Z,{label:"Category",value:a.categoryName}),Je(a)?e.jsx(Z,{label:"In stock",value:`${Le(a).inStock} of ${Le(a).owned}${Le(a).minStock!=null?` · reorder at ${Le(a).minStock}`:""}`}):e.jsx(Z,{label:"Quantity",value:a.quantity}),e.jsx(Z,{label:"Condition",value:X.label}),e.jsx(Z,{label:"Make / Model",value:a.makeModel}),e.jsx(Z,{label:"Serial Number",value:a.serialNumber}),e.jsx(Z,{label:"Inventory Tag",value:a.inventoryTag}),e.jsx(Z,{label:"Location",value:a.storageVenueName||a.storageLocation}),e.jsx(Z,{label:"Ownership",value:a.ownership==="borrowed"?`Borrowed${a.borrowedFrom?" from "+a.borrowedFrom:""}`:"Own"}),e.jsx(Z,{label:"Value",value:a.estimatedValueCents!=null?`${Ut(a.estimatedValueCents,!0)}${a.valueAsOf?` (as of ${a.valueAsOf})`:""}`:null}),e.jsx(Z,{label:"Original Price",value:Ut(a.originalPriceCents,!0)}),e.jsx(Z,{label:"Source",value:a.source}),e.jsx(Z,{label:"Date Acquired",value:a.acquiredAt})]}),a.accessories&&e.jsx("div",{style:{marginTop:"var(--bb-space-4)"},children:e.jsx(Z,{label:"Accessories",value:a.accessories})}),a.description&&e.jsx("div",{style:{marginTop:"var(--bb-space-4)"},children:e.jsx(Z,{label:"Description",value:a.description})}),a.notes&&e.jsx("div",{style:{marginTop:"var(--bb-space-4)"},children:e.jsx(Z,{label:"Notes",value:a.notes})}),e.jsxs("div",{style:{marginTop:"var(--bb-space-5)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:10,marginBottom:4},children:[e.jsx("span",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--bb-fg-subtle)"},children:"Photos"}),R&&e.jsxs(e.Fragment,{children:[e.jsx(d,{type:"button",variant:"secondary",size:"sm",isLoading:F,onClick:()=>$.current?.click(),children:"Upload photo"}),e.jsx(Yt,{label:"Take a photo",disabled:F,onChange:T=>P(T.target.files?.[0])}),e.jsx("input",{ref:$,type:"file",accept:"image/jpeg,image/png,image/webp",hidden:!0,onChange:T=>P(T.target.files?.[0]),"aria-label":"Upload equipment photo"})]})]}),R&&e.jsx("div",{style:{fontSize:12,color:"var(--bb-fg-subtle)",marginBottom:8},children:"JPEG, PNG, or WebP · large photos are resized automatically"}),c===void 0?e.jsx("div",{style:{fontSize:13,color:"var(--bb-fg-muted)"},children:"Loading photosâ¦"}):c.length===0?e.jsx("div",{style:{fontSize:13,color:"var(--bb-fg-muted)"},children:"No photos yet."}):e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:10},children:c.map(T=>e.jsxs("div",{style:{position:"relative"},children:[e.jsx("a",{href:T.photoUrl,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:T.photoUrl,alt:T.caption||a.name,style:{height:96,width:96,objectFit:"cover",borderRadius:"var(--bb-radius-md)",border:"1px solid var(--bb-border-soft)",display:"block"}})}),R&&e.jsx("button",{type:"button","aria-label":"Remove photo",onClick:()=>O(T.id),style:{position:"absolute",top:-8,right:-8,height:26,width:26,borderRadius:"var(--bb-radius-pill)",border:"none",background:"var(--bb-danger)",color:"#fff",fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"var(--bb-shadow-
1pop)"},children:"â"})]},T.id))})]})]}),e.jsx(Qe,{isOpen:!!z,title:"Remove Photo",message:`Remove this photo of "${a.name}"? This cannot be undone.`,confirmLabel:"Remove",onConfirm:()=>z&&I(z),onClose:()=>O(null)})]})}function Fs(){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:14},children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function Vs({group:a,canManage:l,loansIncluded:i,activeLoans:o={},onCheckout:g,onMovement:A,onHistory:k,onEdit:y,onPhoto:v,product:j=null,paymentsOn:h=!1,onSell:q}){const f=fs(a.rows),w=a.rows.length===1&&!a.rows[0].variantLabel,r=a.rows[0],x=a.rows.find(O=>O.photoUrl)?.photoUrl||null,C=[...new Set(a.rows.map(O=>O.reorderUrl||"").filter(Boolean))],E=C.length===1?C[0]:null,R=E&&a.rows.find(O=>O.reorderUrl===E)?.reorderSource||null,c=`bsb-stock-open:${a.key}`,[N,F]=n.useState(()=>{try{return sessionStorage.getItem(c)==="1"}catch{return!1}});function _(){F(O=>{const $=!O;try{sessionStorage.setItem(c,$?"1":"0")}catch{}return $})}const z=e.jsxs(e.Fragment,{children:[r.categoryName?`${r.categoryName} · `:"","Stock",r.storageVenueName||r.storageLocation?` · ${r.storageVenueName||r.storageLocation}`:"",j?` · sells as ${j.name}`:"",r.estimatedValueCents!=null?` · $${(r.estimatedValueCents/100).toFixed(2)} each`:"",E?e.jsxs(e.Fragment,{children:[" · ",e.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"text-band-700 hover:underline",onClick:O=>O.stopPropagation(),children:["reorder from ",R||"link"]})]}):C.length>1?" · each size has its own reorder link":r.reorderSource&&!r.reorderUrl?` · reorder from ${r.reorderSource}`:"",f.onLoan>0?` · ${f.onLoan} out`:""]});return e.jsxs("div",{className:"bg-white rounded-xl border border-gray-200","data-testid":`stock-group-${a.key}`,children:[e.jsxs("div",{className:"px-4 py-2.5 flex items-center gap-3 flex-wrap",children:[w?e.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-3",children:[x&&e.jsx("img",{src:x,alt:"",className:"h-10 w-10 rounded object-cover border border-gray-200 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-semibold text-gray-900 truncate",children:[a.name,e.jsx("span",{className:"ml-2 text-xs font-medium text-gray-500",children:Te(r)})]}),e.jsx("div",{className:"text-xs text-gray-400 truncate",children:z})]})]}):e.jsxs("button",{type:"button",onClick:_,"aria-expanded":N,"aria-controls":`stock-sizes-${a.key}`,title:N?"Hide the sizes":"Show every size",className:"min-w-0 flex-1 flex items-start gap-2 text-left min-h-[2.75rem] focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-band-500","data-testid":`stock-toggle-${a.key}`,children:[e.jsx("svg",{className:`h-4 w-4 text-gray-400 shrink-0 mt-1 transition-transform ${N?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})}),x&&e.jsx("img",{src:x,alt:"",className:"h-10 w-10 rounded object-cover border border-gray-200 shrink-0"}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"block text-sm font-semibold text-gray-900 truncate",children:[a.name,e.jsxs("span",{className:"ml-2 text-xs font-medium text-gray-500",children:[f.inStock," in stock of ",f.owned," · ",a.rows.length," sizes"]})]}),e.jsx("span",{className:"block text-xs text-gray-400 truncate",children:z})]})]}),f.low>0&&!w&&e.jsx(fe,{color:"amber",children:f.low===1?"1 size to reorder":`${f.low} sizes to reorder`}),w&&e.jsx(Ra,{row:r,canManage:l,loansIncluded:i,activeLoans:o,onCheckout:g,onMovement:A,onHistory:k,onEdit:y,onPhoto:v,product:j,paymentsOn:h,onSell:q})]}),!w&&N&&e.jsx("div",{className:"border-t border-gray-100 px-4 py-2",id:`stock-sizes-${a.key}`,children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:[e.jsx("th",{className:"text-left font-semibold py-1",children:"Size"}),e.jsx("th",{className:"text-right font-semibold py-1",children:"On hand"}),e.jsx("th",{className:"text-right font-semibold py-1",children:"Out"}),e.jsx("th",{className:"text-right font-semibold py-1",children:"In stock"}),e.jsx("th",{className:"py-1","aria-hidden":"true"}),e.jsx("th",{className:"py-1","aria-hidden":"true"})]})}),e.jsx("tbody",{children:a.rows.map(O=>{const $=Le(O);return e.jsxs("tr",{className:"border-t border-gray-50","data-testid":`stock-row-${O.id}`,children:[e.jsx("td",{className:"py-1.5 font-medium text-gray-800",children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[O.photoUrl&&e.jsx("img",{src:O.photoUrl,alt:"",className:"h-7 w-7 rounded object-cover border border-gray-200"}),O.variantLabel||"â"]})}),e.jsx("td",{className:"py-1.5 text-right tabular-nums text-gray-700",children:$.owned}),e.jsx("td",{className:"py-1.5 text-right tabular-nums text-gray-500",children:$.onLoan}),e.jsx("td",{className:"py-1.5 text-right tabular-nums font-semibold text-gray-900",children:$.inStock}),e.jsx("td",{className:"py-1.5 pl-3",children:$.lowStock&&e.jsx(Wt,{row:O,minStock:$.minStock})}),e.jsx("td",{className:"py-1.5 text-right whitespace-nowrap",children:e.jsx(Ra,{row:O,canManage:l,loansIncluded:i,activeLoans:o,onCheckout:g,onMovement:A,onHistory:k,onEdit:y,onPhoto:v,product:j,paymentsOn:h,onSell:q,compact:!0})})]},O.id)})})]})})]})}function Ra({row:a,canManage:l,loansIncluded:i,activeLoans:o,onCheckout:g,onMovement:A,onHistory:k,onEdit:y,onPhoto:v,product:j=null,paymentsOn:h=!1,onSell:q,compact:f=!1}){const w=Le(a),r=w.onLoan||(o[a.id]||[]).length;return l?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[!f&&w.lowStock&&e.jsx(Wt,{row:a,minStock:w.minStock}),!f&&r>0&&e.jsxs(fe,{color:"blue",children:[r," out"]}),i&&a.loanable!==!1&&w.inStock>0&&e.jsx(d,{size:"sm",variant:"secondary",onClick:x=>{x.stopPropagation(),g(a)},children:"Check out to memberâ¦"}),e.jsxs(Ce,{align:"right",menuId:`stock-menu-${a.id}`,trigger:e.jsx(d,{size:"sm",variant:"ghost","aria-label":`More actions for ${a.variantLabel?`${a.name} ${a.variantLabel}`:a.name}`,children:"â¦"}),children:[j&&h&&q&&w.inStock>0&&e.jsx(Ce.Item,{onClick:()=>q(a),children:"Sell to memberâ¦"}),e.jsx(Ce.Item,{onClick:()=>A(a,"sold"),children:"Record salesâ¦"}),e.jsx(Ce.Item,{onClick:()=>A(a,"received"),children:"Receiveâ¦"}),e.jsx(Ce.Item,{onClick:()=>A(a,"adjusted"),children:"Adjust countâ¦"}),e.jsx(Ce.Item,{onClick:()=>A(a,"lost"),children:"Write offâ¦"}),e.jsx(Ce.Item,{onClick:()=>k(a),children:"History"}),v&&e.jsx(Ce.Item,{onClick:()=>v(a),children:"Photosâ¦"}),e.jsx(Ce.Item,{onClick:()=>y(a),children:"Edit"})]})]}):f?null:w.lowStock?e.jsx(Wt,{row:a,minStock:w.minStock}):null}function Wt({row:a,minStock:l}){const i=`Reorder${l!=null?` · at ${l}`:""}`;return a.reorderUrl?e.jsx("a",{href:a.reorderUrl,target:"_blank",rel:"noopener noreferrer",onClick:o=>o.stopPropagation(),title:`Order more ${a.variantLabel?`${a.name} ${a.variantLabel}`:a.name} from ${a.reorderSource||"the supplier"}`,className:"hover:underline",children:e.jsxs(fe,{color:"amber",children:[i," â"]})}):e.jsx(fe,{color:"amber",title:a.reorderSource?`Reorder from ${a.reorderSource}`:void 0,children:i})}function Bs({isOpen:a,onClose:l,item:i,onChanged:o}){const{showSuccess:g,showError:A}=se(),[k,y]=n.useState(void 0),[v,j]=n.useState(!1),[h,q]=n.useState(null),f=n.useRef(null);n.useEffect(()=>{if(!a||!i?.id)return;let x=!0;return y(void 0),M.listPhotos(i.id).then(C=>{x&&y(Array.isArray(C)?C:[])}).catch(()=>{x&&(y([]),A(ce("photos")))}),()=>{x=!1}},[a,i?.id]);async function w(x){if(x){j(!0);try{const C=await M.uploadPhoto(i.id,x);y(E=>[...E||[],C]),g("Photo added"),o?.()}catch(C){A(C?.message||K)}finally{j(!1),f.current&&(f.current.value="")}}}async function r(x){try{await M.deletePhoto(i.id,x),y(C=>(C||[]).filter(E=>E.id!==x)),g("Photo removed"),o?.()}catch(C){A(C?.message||it)}finally{q(null)}}return i?e.jsxs(de,{isOpen:a,onClose:l,title:`Photos â ${je(i)}
1`,size:"md",footer:e.jsx("div",{className:"flex gap-2",children:e.jsx(d,{type:"button",variant:"ghost",onClick:l,title:"Close this list of photos",children:"Close"})}),children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"The first photo is the one members see when they buy it, and the one on the inventory card."}),i.photoInherited&&i.photoUrl&&e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 p-3","data-testid":"inherited-photo",children:[e.jsx("img",{src:i.photoUrl,alt:"",className:"h-12 w-12 rounded object-cover border border-gray-200"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["This size shows the ",i.stockGroup||i.name," photo. Add one here only if this size looks different."]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(d,{type:"button",variant:"secondary",size:"sm",isLoading:v,title:"Choose a picture from this device",onClick:()=>f.current?.click(),children:"Upload photo"}),e.jsx(Yt,{label:"Take a photo",disabled:v,onChange:x=>w(x.target.files?.[0])}),e.jsx("input",{ref:f,type:"file",accept:"image/jpeg,image/png,image/webp",hidden:!0,onChange:x=>w(x.target.files?.[0]),"aria-label":"Photo file"}),e.jsx("span",{className:"text-xs text-gray-400",children:"JPEG, PNG or WebP"})]}),k===void 0?e.jsx("p",{className:"text-sm text-gray-400",children:"Loadingâ¦"}):k.length===0?e.jsx("p",{className:"text-sm text-gray-500",children:i.photoInherited?"No photo of its own yet.":"No photo yet. Add one so members know what they are buying."}):e.jsx("ul",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3","data-testid":"stock-photos",children:k.map((x,C)=>e.jsxs("li",{className:"relative",children:[e.jsx("a",{href:x.photoUrl,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:x.photoUrl,alt:x.caption||je(i),className:"w-full h-28 object-cover rounded-lg border border-gray-200"})}),C===0&&e.jsx("span",{className:"absolute top-1 left-1 px-1.5 py-0.5 rounded bg-white/90 text-[10px] font-semibold text-gray-700",children:"Shown to members"}),e.jsx(d,{type:"button",variant:"ghost",size:"sm",className:"mt-1 text-red-600",title:"Remove this photo",onClick:()=>q(x.id),children:"Remove"})]},x.id))})]}),e.jsx(Qe,{isOpen:!!h,onClose:()=>q(null),onConfirm:()=>r(h),title:"Remove this photo?",message:"The photo is deleted from this item.",confirmLabel:"Remove",confirmVariant:"danger"})]}):null}const _s=[{key:"inventory",label:"Inventory"},{key:"categories",label:"Categories"},{key:"loans",label:"Loans"},{key:"mapping",label:"Instrument mapping"}],ft={new:"New",excellent:"Excellent",very_good:"Very Good",good:"Good",fair:"Fair",used:"Used",poor:"Poor",needs_repair:"Needs Repair"},Gs={new:"teal",excellent:"green",very_good:"green",good:"green",fair:"yellow",used:"gray",poor:"orange",needs_repair:"red"},qa="grid grid-cols-[minmax(0,2fr)_minmax(0,1.5fr)_minmax(0,1.1fr)_minmax(0,0.9fr)_minmax(0,1.5fr)_minmax(5.5rem,auto)_auto] gap-x-4 items-center",vt=e.jsx("span",{className:"text-gray-300",children:"â"}),Us={requested:"bg-yellow-100 text-yellow-800",approved:"bg-blue-100 text-blue-800",active:"bg-green-100 text-green-800",returned:"bg-gray-100 text-gray-800",declined:"bg-red-100 text-red-800"};function Ws(a){let l=[];try{l=JSON.parse(a.checkinAccessories||"[]").filter(i=>!i.returned).map(i=>i.name)}catch{l=[]}return{missing:l,notes:a.checkinNotes||""}}function pr(){const{currentOrg:a}=Ue(),l=kt(a?.planTier,"equipmentLoans"),{showSuccess:i,showError:o}=se(),{canFully:g,canAny:A}=Jt(),k=g("equipment:create"),y=g("equipment:delete"),v=A("equipment_loan:manage"),j=A("equipment_loan:list"),h=us(),[q]=ms(),[f,w]=n.useState(q.get("tab")==="loans"?"loans":"inventory"),[r,x]=n.useState([]),[C,E]=n.useState([]),[R,c]=n.useState([]),[N,F]=n.useState([]),[_,z]=n.useState([]),[O,$]=n.useState(!0),[X,m]=n.useState(!1),[P,I]=n.useState(null),[T,Y]=n.useState(!1),[ee,te]=n.useState(!1),[re,ne]=n.useState(null),[ie,Se]=n.useState(""),[le,Re]=n.useState(""),[ue,L]=n.useState(""),[J,ae]=n.useState(!1),[me,lt]=n.useState(!1),[ke,qe]=n.useState("name"),[xe,Me]=n.useState(null),[Ee,Ye]=n.useState([]),[Oe,b]=n.useState(null),[V,W]=n.useState(null),[oe,Wa]=n.useState({}),[De,Fe]=n.useState(null),[Ct,Kt]=n.useState(null),[St,Xt]=n.useState(null),[Zt,ea]=n.useState(null),[ta,At]=n.useState(null),Pt=n.useRef(null),[Ne,Ha]=n.useState([]),[Ke,ot]=n.useState(null),Lt=kt(a?.planTier,"payments"),Xe=n.useCallback(()=>{Promise.resolve().then(()=>M.stockGroups()).then(t=>Ha(Array.isArray(t)?t:[])).catch(jt("stock groups are decoration on the inventory"))},[]),[Qa,aa]=n.useState(!1),[sa,Rt]=n.useState(null),[ra,ct]=n.useState(null),[Ja,na]=n.useState(0),[qt,$t]=n.useState({}),we=n.useCallback(()=>{Promise.resolve().then(()=>M.activeLoans()).then(t=>{const s={};for(const S of Array.isArray(t)?t:[])(s[S.equipmentId]||=[]).push(S);Wa(s)}).catch(()=>o(ce("loans")))},[]);n.useEffect(()=>{a?.id&&(Promise.resolve().then(()=>Gt.list(a.id)).then(t=>Ye(Array.isArray(t)?t:[])).catch(jt("storage-location options; the form still saves")),we())},[a?.id,we]);const[dt,ut]=n.useState(null),[ia,It]=n.useState(null),[la,zt]=n.useState(null),[oa,Tt]=n.useState(null);function Ya(){const t=dt?.loan?.equipmentId;ut(null),we(),be(),t&&Promise.resolve().then(()=>M.loans(t)).then(s=>$t(S=>({...S,[t]:Array.isArray(s)?s:[]}
1))).catch(()=>o(ce("loan history")))}async function ca(t,s){try{await M.resolveAccessory(t.id,{resolution:s}),i(`${t.name} marked ${s}`),be()}catch(S){o(S?.message||K)}}const[da,mt]=n.useState({}),[ua,ma]=n.useState(!1),[Ze,Mt]=n.useState(null),gt=n.useRef(null),Et=n.useRef(null),[u,B]=n.useState({kind:"item",variantLabel:"",minStock:"",agreementRequired:!0,loanable:!0,unitsPerPack:"",reorderSource:"",reorderUrl:"",stockGroup:"",stockGroupPick:"",name:"",categoryId:"",description:"",quantity:1,condition:"good",ownership:"own",borrowedFrom:"",storageLocation:"",storageVenueId:"",notes:"",makeModel:"",serialNumber:"",accessories:"",estimatedValue:"",valueAsOf:"",originalPrice:"",source:"",acquiredAt:"",needsRepair:!1,repairNotes:"",inventoryTag:""}),et=parseInt(u.unitsPerPack,10)||1,$e=!P&&u.kind==="stock"&&!u.stockGroupPick?vs(u.name,Ne):null,[Ve,pt]=n.useState({name:"",description:"",sortOrder:0}),[tt,at]=n.useState(null),[ga,ht]=n.useState(!1),[ge,Be]=n.useState({instrumentId:"",instrumentFamily:"",equipmentName:"",quantityPerPlayer:1,priority:"required"}),[pa,st]=n.useState(!1),Ae=gs({items:C,onReorder(t){E(t),Pe.reorder(t.map(s=>s.id)).then(E).catch(s=>o(s?.message||K))}});n.useEffect(()=>{a&&(be(),Ot(),hs.list("member").then(z).catch(()=>o(ce("instruments"))))},[a]),n.useEffect(()=>{a&&f==="loans"&&Dt()},[a,f]),n.useEffect(()=>{a&&Xe()},[a,Xe]),n.useEffect(()=>{a&&f==="mapping"&&Ft()},[a,f]);async function be(){$(!0);try{x(await M.list(a.id))}catch{o(ce("equipment"))}finally{$(!1)}}async function Ot(){try{E(await Pe.list(a.id))}catch{o(ce("categories"))}}async function Dt(){try{c(await Ca.list())}catch{o(ce("equipment loans"))}}async function Ft(){try{F(await M.listInstrumentMap(a.id))}catch{o(ce("instrument mappings"))}}const Ka=[...new Set(r.map(t=>(t.storageVenueName||t.storageLocation||"").trim()).filter(Boolean))].sort((t,s)=>t.localeCompare(s)),ha=(le.trim()?1:0)+(ie?1:0)+(ue?1:0)+(J?1:0)+(me?1:0),xa=le.trim().toLowerCase(),_e=r.filter(t=>!xa||[t.name,t.makeModel,t.serialNumber,t.inventoryTag,t.variantLabel].some(s=>s&&String(s).toLowerCase().includes(xa))).filter(t=>!ie||t.categoryId===ie).filter(t=>!ue||(t.storageVenueName||t.storageLocation||"").trim()===ue).filter(t=>!J&&!me?!0:J&&t.needsRepair===!0||me&&(t.missingAccessories?.length||0)>0).sort((t,s)=>ke==="category"?(t.categoryName||"ï¿¿").localeCompare(s.categoryName||"ï¿¿")||t.name.localeCompare(s.name):ke==="location"?((t.storageVenueName||t.storageLocation||"").trim()||"ï¿¿").localeCompare((s.storageVenueName||s.storageLocation||"").trim()||"ï¿¿")||t.name.localeCompare(s.name):ke==="value"?(s.estimatedValueCents??-1)-(t.estimatedValueCents??-1)||t.name.localeCompare(s.name):ke==="condition"&&(t.condition||"").localeCompare(s.condition||"")||t.name.localeCompare(s.name)),Vt=Object.values(oe).flat().map(t=>({loan:t,item:r.find(s=>s.id===t.equipmentId)})).sort((t,s)=>String(s.loan.checkedOutAt||"").localeCompare(String(t.loan.checkedOutAt||""))),ba=Vt.length,Xa=(()=>{const t=new Map;for(const s of Vt){const S=s.loan.batchId||s.loan.id;t.has(S)||t.set(S,[]),t.get(S).push(s)}return[...t.values()]})();function ya(){Re(""),Se(""),L(""),ae(!1)}function Za(t){const s=xe===t.id?null:t.id;Me(s),s&&da[t.id]===void 0&&M.listPhotos(t.id).then(S=>mt(D=>({...D,[t.id]:S}
1))).catch(()=>mt(S=>({...S,[t.id]:[]}))),s&&qt[t.id]===void 0&&Promise.resolve().then(()=>M.loans(t.id)).then(S=>$t(D=>({...D,[t.id]:Array.isArray(S)?S:[]}))).catch(()=>$t(S=>({...S,[t.id]:[]})))}async function fa(t,s){if(s){ma(!0);try{const S=await M.uploadPhoto(t.id,s);mt(D=>({...D,[t.id]:[...D[t.id]||[],S]})),i("Photo added")}catch(S){o(S?.message||K)}finally{ma(!1),gt.current&&(gt.current.value="")}}}async function es(t,s){try{await M.deletePhoto(t.id,s),mt(S=>({...S,[t.id]:(S[t.id]||[]).filter(D=>D.id!==s)})),i("Photo removed")}catch(S){o(S?.message||it)}finally{Mt(null)}}function ts(){const t=Qt(),s=a?.shortName||a?.slug||"band",S=D=>D!=null?"$"+(D/100).toFixed(2):"";ys(`equipment-${s}-${t}.csv`,["BSB ID","Item","Category","Qty","Make/Model","Serial Number","Accessories","Description","Condition","Location","Value","Value as of","Original Price","Source","Date Acquired","Needs Repair","Repair Notes","Inventory Tag","Notes"],_e.map(D=>[D.id,D.name,D.categoryName||"",D.quantity,D.makeModel||"",D.serialNumber||"",D.accessories||"",D.description||"",ft[D.condition]||D.condition||"",D.storageVenueName||D.storageLocation||"",S(D.estimatedValueCents),D.valueAsOf||"",S(D.originalPriceCents),D.source||"",D.acquiredAt||"",D.needsRepair?"yes":"",D.repairNotes||"",D.inventoryTag||"",D.notes||""])),i(`Exported ${_e.length} item${_e.length===1?"":"s"}${ha?" (filtered)":""}`)}function xt(t=null){At(null),Pt.current&&(Pt.current.value=""),t?(I(t),B({kind:t.kind||"item",variantLabel:t.variantLabel||"",minStock:t.minStock??"",agreementRequired:t.agreementRequired!==!1,loanable:t.loanable!==!1,stockGroup:t.stockGroup||"",stockGroupPick:t.stockGroup||"",unitsPerPack:t.unitsPerPack??"",reorderSource:t.reorderSource||"",reorderUrl:t.reorderUrl||"",name:t.name,categoryId:t.categoryId||"",description:t.description||"",quantity:t.quantity,condition:t.condition,ownership:t.ownership,borrowedFrom:t.borrowedFrom||"",storageLocation:t.storageLocation||"",storageVenueId:t.storageVenueId||"",notes:t.notes||"",makeModel:t.makeModel||"",serialNumber:t.serialNumber||"",accessories:t.accessories||"",estimatedValue:t.estimatedValueCents!=null?t.kind==="stock"?We(String(za(t.estimatedValueCents,t.unitsPerPack))):ze(String(Math.round(t.estimatedValueCents/100))):"",valueAsOf:t.valueAsOf||"",originalPrice:t.originalPriceCents!=null?ze(String(Math.round(t.originalPriceCents/100))):"",source:t.source||"",acquiredAt:t.acquiredAt||"",needsRepair:t.needsRepair===!0,repairNotes:t.repairNotes||"",inventoryTag:t.inventoryTag||""})):(I(null),B({kind:"item",variantLabel:"",minStock:"",agreementRequired:!0,loanable:!0,stockGroup:"",stockGroupPick:"",unitsPerPack:"",reorderSource:"",reorderUrl:"",name:"",categoryId:"",description:"",quantity:1,condition:"good",ownership:"own",borrowedFrom:"",storageLocation:"",storageVenueId:"",notes:"",makeModel:"",serialNumber:"",accessories:"",estimatedValue:"",valueAsOf:"",originalPrice:"",source:"",acquiredAt:"",needsRepair:!1,repairNotes:"",inventoryTag:""})),m(!0),setTimeout(()=>Et.current?.scrollIntoView({behavior:"smooth",block:"start"}),50)}async function as(t){const s=S=>{const D=String(S??"").replace(/[^0-9]/g,"");return D?Number(D)*100:null};t.preventDefault(),Y(!0);try{const{estimatedValue:S,originalPrice:D,stockGroupPick:p,...H}=u,va=H.kind==="stock",ja={...H,quantity:H.serialNumber&&H.serialNumber.trim()?1:H.quantity,...va?{serialNumber:"",makeModel:"",inventoryTag:"",accessories:"",needsRepair:!1,valueAsOf:"",originalPriceCents:null,source:"",acquiredAt:""}:{variantLabel:"",minStock:"",agreementRequired:!0,loanable:!0,stockGroup:"",unitsPerPack:"",reorderSource:"",reorderUrl:""},estimatedValueCents:va?Nt(He(S),H.unitsPerPack):s(S),originalPriceCents:s(D)};if(P)await M.update(P.id,ja),i("Equipment updated");
1else{const ka=await M.create({...ja,orgId:a.id});if(ta&&ka?.id)try{await M.uploadPhoto(ka.id,ta)}catch(os){o(os?.message||"Saved, but the photo did not upload")}At(null),i("Equipment created")}m(!1),I(null),be()}catch(S){o(S?.message||K)}finally{Y(!1)}}async function ss(){if(re)try{await M.remove(re.id),i("Equipment deleted"),te(!1),ne(null),P?.id===re.id&&(m(!1),I(null)),be()}catch(t){o(t?.message||it)}}function Bt(t=null){t?(at(t),pt({name:t.name,description:t.description||"",sortOrder:t.sortOrder})):(at(null),pt({name:"",description:"",sortOrder:0})),ht(!0)}async function rs(t){t.preventDefault();try{tt?(await Pe.update(tt.id,Ve),i("Category updated")):(await Pe.create({...Ve,orgId:a.id}),i("Category created")),ht(!1),at(null),Ot()}catch(s){o(s?.message||K)}}async function ns(t){try{await Pe.remove(t.id),i("Category deleted"),Ot()}catch{o("Cannot delete category in use")}}async function is(t){t.preventDefault();try{await M.createMapping({...ge,orgId:a.id}),i("Mapping created"),st(!1),Be({instrumentId:"",instrumentFamily:"",equipmentName:"",quantityPerPlayer:1,priority:"required"}),Ft()}catch(s){o(s?.message||K)}}async function ls(t){try{await M.deleteMapping(t),i("Mapping deleted"),Ft()}catch(s){o(s?.message||it)}}async function bt(t,s,S={}){try{await Ca[s](t,S),i(`Loan ${s}d`),Dt()}catch(D){o(D?.message||K)}}return h?e.jsx(Es,{}):e.jsxs("div",{children:[e.jsx(xs,{title:"Equipment",breadcrumbs:[{label:"Home",to:"/"},{label:"Equipment"}],actions:k&&(f==="inventory"?e.jsxs(e.Fragment,{children:[l&&e.jsx(d,{variant:"ghost",size:"md",onClick:()=>aa(!0),children:"Loan agreement"}),r.length>0&&e.jsx(d,{variant:"ghost",size:"md",onClick:ts,children:"Export CSV"}),e.jsx(Na,{to:"/import/equipment",children:e.jsx(d,{variant:"ai",size:"md",children:"Smart Import"})}),l&&e.jsx(d,{variant:"secondary",size:"md",onClick:()=>Fe({}),children:"New loan"}),e.jsx(d,{variant:"primary",size:"md",onClick:()=>xt(),children:"New equipment"})]}):f==="categories"?e.jsx(d,{variant:"primary",size:"md",onClick:()=>Bt(),children:"New category"}):f==="mapping"?e.jsx(d,{variant:"primary",size:"md",onClick:()=>st(!0),children:"New mapping"}):null)}),e.jsx(ks,{className:"mb-6",ariaLabel:"Equipment sections",tabs:_s.filter(t=>t.key!=="loans"||j).map(t=>t.key==="loans"&&ba>0?{...t,count:ba}:t),value:f,onChange:w}),f==="inventory"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-3",children:[e.jsx(Q,{type:"search",value:le,onChange:t=>Re(t.target.value),active:!!le.trim(),placeholder:"Search name, make, serialâ¦","aria-label":"Search equipment",className:"w-56"}),e.jsx(he,{value:ie,onChange:t=>Se(t.target.value),active:!!ie,placeholder:"All Categories",options:C.map(t=>({value:t.id,label:t.name}))}),e.jsx(he,{value:ue,onChange:t=>L(t.target.value),active:!!ue,placeholder:"All Locations",options:Ka.map(t=>({value:t,label:t}))}),e.jsxs("label",{className:`inline-flex items-center gap-2 text-sm border rounded-lg px-3 py-2 cursor-pointer ${J?"border-band-400 bg-band-50 text-band-700":"border-gray-300 text-gray-700"}`,children:[e.jsx("input",{type:"checkbox",checked:J,onChange:t=>ae(t.target.checked),className:"rounded border-gray-300 text-band-600 focus:ring-band-500 h-4 w-4"}),"Needs repair"]}),e.jsxs("label",{className:`inline-flex items-center gap-2 text-sm border rounded-lg px-3 py-2 cursor-pointer ${me?"border-band-400 bg-band-50 text-band-700":"border-gray-300 text-gray-700"}`,children:[e.jsx("input",{type:"checkbox",checked:me,onChange:t=>lt(t.target.checked),className:"rounded border-gray-300 text-band-600 focus:ring-band-500 h-4 w-4"}),"Incomplete"]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Sort"}),e.jsx(he,{value:ke,onChange:t=>qe(t.target.value),"aria-label":"Sort by",options:[{value:"name",label:"Name"},{value:"category",label:"Category"},{value:"location",label:"Location"},{value:"value",label:"Value (high first)"},{value:"condition",label:"Condition"}]})]})]}),ha>0&&e.jsx(bs,{count:_e.length,onClear:ya}),X&&e.jsxs("div",{ref:Et,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:P?u.kind==="stock"?"Edit stock":"Edit equipment":u.kind==="stock"?"New stock":"New equipment"}),e.jsxs("div",{className:"flex gap-2 pb-4",children:[e.jsx(d,{type:"button",variant:"primary",size:"sm",disabled:T,onClick:t=>Et.current?.querySelector("form")?.requestSubmit(),children:P?"Save changes":"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>{m(!1),I(null)},children:"Cancel"}),P&&y&&e.jsx(d,{type:"button",variant:"danger",size:"sm",className:"ml-auto",onClick:()=>{ne(P),te(!0)},children:"Delete"})]}),e.jsxs("form",{onSubmit:as,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx("div",{className:"sm:col-span-2",children:e.jsx(he,{label:"What is it",value:u.kind,onChange:t=>B({...u,kind:t.target.value}),options:[{value:"item",label:"An instrument or item â one record each"},{value:"stock",label:"Stock in quantity â identical units (shirts by size, stand lights, reeds)"}]})}),u.kind==="stock"&&e.jsx("div",{className:"sm:col-span-2",children:e.jsx(he,{label:"Part of",value:u.stockGroupPick,onChange:t=>{const s=t.target.value,S=Ne.find(D=>D.name===s);B({...u,stockGroupPick:s,stockGroup:s||"",name:S?S.name:u.stockGroupPick?"":u.n
1ame})},options:[{value:"",label:"A new item"},...Ne.map(t=>({value:t.name,label:`${t.name} (${t.rows.length} ${t.rows.length===1?"size":"sizes"})`}))],hint:"add a size to something you already track, or start a new item"})}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Name"}),u.kind==="stock"&&u.stockGroupPick?e.jsxs("p",{className:"text-sm text-gray-900 py-2","data-testid":"stock-name-locked",children:[u.stockGroupPick,e.jsx("span",{className:"text-xs text-gray-400",children:" â the item this size belongs to"})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",required:!0,value:u.name,onChange:t=>B({...u,name:t.target.value}),placeholder:u.kind==="stock"?"e.g. Band polo":void 0,className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"}),u.kind==="stock"&&!$e&&e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Sizes share the name: one record per size, the page shows them as one card."}),$e&&e.jsxs("p",{className:"text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mt-1 flex items-center gap-2 flex-wrap","data-testid":"near-miss",children:[e.jsxs("span",{children:["You already track ",e.jsx("span",{className:"font-semibold",children:$e.name}),". A different name makes a separate item."]}),e.jsxs(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>B({...u,stockGroupPick:$e.name,stockGroup:$e.name,name:$e.name}),children:["Add as a size of ",$e.name]})]})]})]}),u.kind==="stock"&&e.jsx("div",{children:e.jsx(Q,{label:"Size or variant",value:u.variantLabel,onChange:t=>B({...u,variantLabel:t.target.value}),placeholder:"e.g. XL â leave blank for one size"})}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Category"}),e.jsxs("select",{value:u.categoryId,onChange:t=>{const s=t.target.value;if(s==="__new__"){W("");return}B({...u,categoryId:s})},className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"None"}),C.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id)),e.jsx("option",{value:"__new__",children:"+ Add new categoryâ¦"})]}),V!==null&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(Q,{autoFocus:!0,value:V,placeholder:"New category name","aria-label":"New category name",onChange:t=>W(t.target.value)}),e.jsx(d,{type:"button",size:"sm",onClick:async()=>{const t=(V||"").trim();if(t)try{const s=await Pe.create({orgId:a.id,name:t});E(S=>[...S,s]),B(S=>({...S,categoryId:s.id})),W(null)}catch(s){o(s?.message||K)}},children:"Add"}),e.jsx(d,{type:"button",size:"sm",variant:"ghost",onClick:()=>W(null),children:"Cancel"})]})]}),u.kind==="stock"&&P?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"On hand"}),e.jsx("p",{className:"text-sm text-gray-700 py-2",children:Te(P)}),e.jsx("p",{className:"text-xs text-gray-400",children:"The count moves through Receive, Adjust count and Write off on the row, so the history stays true."})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:u.kind==="stock"?"Quantity on hand":"Quantity"}),e.jsx("input",{type:"number",min:"0",disabled:!!u.serialNumber.trim(),value:u.serialNumber.trim()?1:u.quantity,onChange:t=>B({...u,quantity:parseInt(t.target.value)||0}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm disabled:bg-gray-50 disabled:text-gray-500"}),!!u.serialNumber.trim()&&e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"One record per serial number â add each instrument separately."})]}),u.kind==="stock"&&e.jsx("div",{children:e.jsx(Q,{label:"Reorder when in stock is at or below",type:"number",min:"0",value:u.minStock,onChange:t=>B({...u,minStock:t.target.value}),placeholder:"e.g. 3 â leave blank for no reminder"})}),u.kind!=="stock"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Condition"}),e.jsx("select",{value:u.condition,onChange:t=>B({...u,condition:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:Object.entries(ft).map(([t,s])=>e.jsx("option",{value:t,children:s},t))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ownership"}),e.jsxs("select",{value:u.ownership,onChange:t=>B({...u,ownership:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"own",children:"Own"}),e.jsx("option",{value:"borrowed",children:"Borrowed"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Storage Location"}),e.jsxs("select",{value:u.storageVenueId||"",onChange:t=>{const s=t.target.value;if(s==="__new__"){b("");return}B({...u,storageVenueId:s})},className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"â None â"}),Ee.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id)),e.jsx("option",{value:"__new__",children:"+ Add new locationâ¦"})]}),Oe!==null&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx("input",{type:"text",autoFocus:!0,value:Oe,placeholder:"New location name",onChange:t=>b(t.target.value),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"}),e.jsx(d,{type:"button",size:"sm",onClick:async()=>{const t=(Oe||"").trim();if(t)try{const s=await Gt.create({orgId:a.id,name:t});Ye(S=>[...S,s]),B(S=>({...S,storageVenueId:s.id})),b(null)}catch(s){o(s?.message||K)}},children:"Add"}),e.jsx(d,{type:"button",size:"sm",variant:"ghost",onClick:()=>b(null),children:"Cancel"})]}),u.storageLocation&&!u.storageVenueId&&e.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["Legacy text: â",u.storageLocation,"â â pick a location to link it."]})]}),u.kind!=="stock"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Make / Model"}),e.jsx("input",{type:"text",value:u.makeModel,onChange:t=>B({...u,makeModel:t.target.value}),placeholder:"e.g. Selmer",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Serial Number"}),e.jsx("input",{type:"text",value:u.serialNumber,onChange:t=>B({...u,serialNumber:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]})]}),e.jsx("div",{children:u.kind==="stock"?e.jsxs(e.Fragment,{children:[e.jsx(Q,{label:et>1?`What you pay for a pack of ${et}`:"What you pay per unit",inputMode:"numeric",value:u.estimatedValue,onChange:t=>B({...u,estimatedValue:We(t.target.value)}),placeholder:et>1?"$31.00":"$25.00"}),et>1&&He(u.estimatedValue)!=null&&e.jsxs("p",{className:"mt-1 text-xs text-gray-600","data-testid":"per-unit-cost",children:["That is ",We(String(Nt(He(u.estimatedValue),et)))," each â what one costs the band, and what the sale price is set against."]})]}):e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Estimated Value"}),e.jsx("input",{type:"text",value:u.estimatedValue,onChange:t=>B({...u,estimatedValue:ze(t.target.value)}),placeholder:"e.g. $100",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]})}),u.kind==="stock"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{children:e.jsx(Q,{label:"Units per pack",type:"number",min:"1",value:u.unitsPerPack,onChange:t=>B({...u,unitsPerPack:t.target.value}),placeholder:"e.g. 10 â a box of reeds; blank for one at a time",hint:"how many sellable units come in one purchase"})}),e.jsx("div",{children:e.jsx(Q,{label:"Where to reorder",value:u.reorderSource,onCh
1ange:t=>B({...u,reorderSource:t.target.value}),placeholder:"e.g. Amazon, Woodwind & Brasswind"})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"Reorder link",type:"url",value:u.reorderUrl,onChange:t=>B({...u,reorderUrl:t.target.value}),placeholder:"https://â¦"})}),!P&&e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Photo (optional)"}),e.jsx("input",{ref:Pt,type:"file",accept:"image/jpeg,image/png,image/webp","aria-label":"Photo",onChange:t=>At(t.target.files?.[0]||null),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"}),e.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"Another size of the same item shows this one until you give it its own, so one photo can cover them all."})]})]}),u.kind!=="stock"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Value as of"}),e.jsx("input",{type:"text",value:u.valueAsOf,onChange:t=>B({...u,valueAsOf:t.target.value}),placeholder:"e.g. 2018",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Original Price"}),e.jsx("input",{type:"text",value:u.originalPrice,onChange:t=>B({...u,originalPrice:ze(t.target.value)}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Source (donor or vendor)"}),e.jsx("input",{type:"text",value:u.source,onChange:t=>B({...u,source:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Date Acquired"}),e.jsx("input",{type:"date",value:u.acquiredAt,onChange:t=>B({...u,acquiredAt:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]})]}),u.kind==="stock"&&e.jsxs("div",{className:"sm:col-span-2 space-y-1",children:[e.jsxs("label",{className:"inline-flex items-center gap-2 text-sm font-medium text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:u.loanable,onChange:t=>B({...u,loanable:t.target.checked}),className:"rounded border-gray-300 text-band-600 focus:ring-band-500 h-4 w-4"}),"Members can borrow this"]}),e.jsx("p",{className:"text-xs text-gray-400",children:"Leave it unticked for something used up, like reeds: it is sold or handed out, never checked back in."}),u.loanable&&e.jsxs("label",{className:"inline-flex items-center gap-2 text-sm font-medium text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:u.agreementRequired,onChange:t=>B({...u,agreementRequired:t.target.checked}),className:"rounded border-gray-300 text-band-600 focus:ring-band-500 h-4 w-4"}),"Ask for the loan agreement at checkout"]})]}),u.kind!=="stock"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Inventory Tag"}),e.jsx("input",{type:"text",value:u.inventoryTag,onChange:t=>B({...u,inventoryTag:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsx("div",{className:"flex items-end pb-1",children:e.jsxs("label",{className:"inline-flex items-center gap-2 text-sm font-medium text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:u.needsRepair,onChange:t=>B({...u,needsRepair:t.target.checked}),className:"rounded border-gray-300 text-band-600 focus:ring-band-500 h-4 w-4"}),"Needs repair"]})})]})]}),u.kind!=="stock"&&u.needsRepair&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Describe repair needs"}),e.jsx("textarea",{value:u.repairNotes,onChange:t=>B({...u,repairNotes:t.target.value}),placeholder:"e.g. sticky valve, missing water key",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",rows:2})]}),u.kind!=="stock"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Accessories"}),e.jsx("textarea",{value:u.accessories,onChange:t=>B({...u,accessories:t.target.value}),placeholder:"e.g. Artley case, cleaning rod",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",rows:2})]}),u.ownership==="borrowed"&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Borrowed From"}),e.jsx("input",{type:"text",value:u.borrowedFrom,onChange:t=>B({...u,borrowedFrom:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Description"}),e.jsx("textarea",{value:u.description,onChange:t=>B({...u,description:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",rows:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notes"}),e.jsx("textarea",{value:u.notes,onChange:t=>B({...u,notes:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",rows:2})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{type:"submit",variant:"primary",size:"sm",disabled:T,children:P?"Save changes":"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>{m(!1),I(null)},children:"Cancel"}),P&&y&&e.jsx(d,{type:"button",variant:"danger",size:"sm",className:"ml-auto",onClick:()=>{ne(P),te(!0)},children:"Delete"})]})]})]}),!X&&(O?e.jsx("div",{className:"text-center py-8 text-gray-500",children:"Loading..."}):r.length>0&&_e.length===0?e.jsx(Ie,{card:!0,title:"No equipment matches these filters.",action:e.jsx(d,{variant:"secondary",size:"sm",onClick:ya,children:"Clear all filters"})}):r.length===0?e.jsx(Ie,{card:!0,title:"No equipment yet.",action:k?e.jsx(d,{variant:"primary",size:"sm",onClick:()=>xt(),children:"Create first equipment"}):null}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:`${qa} sticky top-0 z-10 will-change-transform bg-gray-50 px-4 pt-1 pb-1.5`,children:[["Item","Make / Model","Serial","Tag","Location","Condition"].map(t=>e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:t},t)),e.jsx("span",{"aria-hidden":"true"})]}),js(_e).map(t=>{if(t.type==="group")return e.jsx(Vs,{group:t,canManage:k,loansIncluded:l,activeLoans:oe,product:ye(Ne,t.rows[0]),paymentsOn:Lt,onSell:p=>ot({item:p,product:ye(Ne,p)}),onCheckout:p=>Fe(p),onMovement:(p,H)=>Kt({item:p,kind:H}),onHistory:p=>Xt(p),onPhoto:p=>ea(p),onEdit:p=>xt(p)},t.key);const s=t.item,S=xe===s.id,D=da[s.id];return e.jsxs("div",{className:"bg-white rounded-xl border border-gray-200",children:[e.jsxs("div",{className:"px-4 py-2.5 cursor-pointer",onClick:()=>Za(s),children:[e.jsxs("div",{className:qa,children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-semibold text-gray-900 truncate",children:[s.name,s.quantity>1&&e.jsxs("span",{className:"ml-1.5 text-xs font-medium text-gray-500",children:["Ã",s.quantity]})]}),s.categoryName&&e.jsx("div",{className:"text-xs text-gray-400 truncate",children:s.categoryName})]}),e.jsx("div",{className:"text-sm text-gray-700 truncate",title:s.makeModel||void 0,children:s.makeModel||vt}),e.jsx("div",{className:"font-mono text-xs text-gray-600 truncate",title:s.serialNumber||void 0,children:s.serialNumber||vt}),e.jsx("div",{className:"font-mono text-xs text-gray-600 truncate",title:s.inventoryTag||void 0,children:s.inventoryTag||vt}),e.jsx("div",{className:"text-sm text-gray-700 truncate",title:s.storageVenueName||s.storageLocation||void 0,children:s.storageVenueName||s.storageLocation||vt}),e.jsx("div",{children:e.jsx(fe,{color:Gs[s.condition],children:ft[s.condition]||s.condition})}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[k&&e.jsx(d,{variant:"ghost",size:"sm",onClick:p=>{p.stopPropagation(),xt(s)},children:"Edit"}),e.jsx("svg",{className:`h-4 w-4 text-gray-400 transition-transform ${S?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),(s.needsRepair||oe[s.id]?.length>0||s.missingAccessories?.length>0)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-2",children:[s.needsRepair&&(s.openRepair?e.jsxs(fe,{color:"amber",title:s.repairNotes||void 0,children:["At repair",s.openRepair.vendor?" â "+s.openRepair.vendor:""]}):e.jsxs(fe,{color:"red",title:s.repairNotes||void 0,children:["Needs repair",s.repairNotes?" â "+(s.repairNotes.length>40?s.repairNotes.slice(0,40)+"â¦":s.repairNotes):""]})),oe[s.id]?.length>0&&e.jsxs(fe,{color:"blue",children:["Checked out to ",oe[s.id].map(p=>`${p.firstName} ${p.lastName}
1`).join(", ")]}),s.missingAccessories?.length>0&&e.jsx(fe,{color:"amber",title:`Missing: ${s.missingAccessories.map(p=>p.name).join(", ")}`,children:"Incomplete"})]})]}),S&&e.jsxs("div",{className:"border-t border-gray-100 px-4 py-4",children:[e.jsx("dl",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-3 text-sm",children:[["Category",s.categoryName],["Quantity",s.quantity],["Condition",ft[s.condition]||s.condition],["Make / Model",s.makeModel],["Serial Number",s.serialNumber],["Inventory Tag",s.inventoryTag],["Location",s.storageVenueName||s.storageLocation],["Ownership",s.ownership==="borrowed"?`Borrowed${s.borrowedFrom?" from "+s.borrowedFrom:""}`:"Own"],["Value",s.estimatedValueCents!=null?"$"+(s.estimatedValueCents/100).toLocaleString("en-US",{minimumFractionDigits:2})+(s.valueAsOf?` (as of ${s.valueAsOf})`:""):null],["Original Price",s.originalPriceCents!=null?"$"+(s.originalPriceCents/100).toLocaleString("en-US",{minimumFractionDigits:2}):null],["Source",s.source],["Date Acquired",s.acquiredAt]].filter(([,p])=>p!=null&&p!=="").map(([p,H])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:p}),e.jsx("dd",{className:"text-gray-900 mt-0.5",children:H})]},p))}),e.jsxs("div",{className:"mt-3 text-sm",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Checked out"}),(oe[s.id]||[]).map(p=>e.jsxs("div",{className:"mt-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-gray-800",children:[p.firstName," ",p.lastName]}),e.jsxs("span",{className:"text-xs text-gray-400",children:["since ",ve(String(p.checkedOutAt||"").slice(0,10)),p.expectedReturnDate?` · due ${ve(p.expectedReturnDate)}`:""]}),p.agreementRequired&&!p.agreementCompletedAt&&e.jsx("span",{className:"inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold bg-amber-100 text-amber-800",children:p.guardianEmail||p.guardianName?"Awaiting guardian":"Awaiting agreement"}),p.agreementRequired&&p.agreementCompletedAt&&e.jsx("span",{className:"inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold bg-green-100 text-green-800",children:p.guardianEmail||p.guardianName?"Signed by guardian":"Agreement signed"}),k&&e.jsx(d,{size:"sm",variant:"ghost",onClick:H=>{H.stopPropagation(),ut({loan:p,item:s})},children:"Mark returnedâ¦"})]}),(p.guardianEmail||p.guardianName)&&e.jsxs("div",{className:"text-xs text-gray-500 mt-0.5",children:["Guardian: ",e.jsx("span",{className:"text-gray-700",children:p.guardianName}),p.guardianEmail?e.jsxs(e.Fragment,{children:[" · ",e.jsx("a",{className:"text-band-700",href:`mailto:${p.guardianEmail}`,onClick:H=>H.stopPropagation(),children:p.guardianEmail})]}):null,p.guardianPhone?e.jsxs(e.Fragment,{children:[" · ",e.jsx("a",{className:"text-band-700",href:`tel:${String(p.guardianPhone).replace(/\D/g,"")}`,onClick:H=>H.stopPropagation(),children:p.guardianPhone})]}):null]})]},p.id)),(oe[s.id]||[]).length===0&&e.jsx("p",{className:"text-gray-400 text-xs mt-0.5",children:"Not checked out."}),k&&l&&(oe[s.id]||[]).length<(s.quantity||1)&&e.jsx(d,{size:"sm",variant:"secondary",className:"mt-2",onClick:p=>{p.stopPropagation(),Fe(s)},children:"Check out to memberâ¦"}),(qt[s.id]||[]).filter(p=>p.returnedAt).length>0&&e.jsxs("div",{className:"mt-3",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Loan history"}),(qt[s.id]||[]).filter(p=>p.returnedAt).map(p=>{const H=Ws(p);return e.jsxs("div",{className:"text-xs text-gray-500 mt-1",children:[p.firstName," ",p.lastName," · ",String(p.checkedOutAt||"").slice(0,10)," â ",String(p.returnedAt||"").slice(0,10),p.conditionIn?` · returned ${String(p.conditionIn).replace(/_/g," ")}`:"",p.guardianName?` · guardian: ${p.guardianName}`:"",H.missing.length>0&&e.jsxs("span",{className:"text-amber-700",children:[" · still out: ",H.missing.join(", ")]}),H.notes&&e.jsx("div",{className:"text-gray-400 italic mt-0.5",children:H.notes})]},p.id)})]})]}),s.needsRepair&&(s.openRepair?e.jsxs("div",{className:"mt-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800 p-3 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold",children:"Out for repair"}),s.openRepair.vendor?` at ${s.openRepair.vendor}`:"",s.openRepair.sentAt?` since ${String(s.openRepair.sentAt).slice(0,10)}`:"",s.repairNotes?` â ${s.repairNotes}`:""]}),k&&e.jsx(d,{size:"sm",variant:"secondary",onClick:p=>{p.stopPropagation(),ct(s)},children:"Mark repairedâ¦"})]}):e.jsxs("div",{className:"mt-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 p-3 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold",children:"Repair needs:"})," ",s.repairNotes||"flagged at check-in"]}),k&&e.jsxs("span",{className:"flex gap-2 shrink-0",children:[e.jsx(d,{size:"sm",variant:"secondary",onClick:p=>{p.stopPropagation(),Rt(s)},children:"Send for repairâ¦"}),e.jsx(d,{size:"sm",variant:"secondary",onClick:p=>{p.stopPropagation(),ct(s)},children:"Mark repairedâ¦"})]})]})),e.jsx(Ts,{equipmentId:s.id,refreshToken:Ja}),(s.accessories||s.missingAccessories?.length>0)&&e.jsxs("div",{className:"mt-3 text-sm",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Accessories"}),s.accessories&&e.jsx("p",{className:"text-gray-700 mt-0.5",children:s.accessories}),s.missingAccessories?.length>0&&e.jsxs("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-semibold text-amber-800",children:"Incomplete â not returned at check-in:"}),s.missingAccessories.map(p=>e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm text-amber-900",children:p.name}),e.jsxs("span",{className:"text-xs text-amber-700/70",children:["since ",String(p.reportedAt||"").slice(0,10)]}),k&&e.jsxs(e.Fragment,{children:[e.jsx(d,{size:"sm",variant:"ghost",onClick:H=>{H.stopPropagation(),ca(p,"returned")},children:"Mark returned"}),e.jsx(d,{size:"sm",variant:"ghost",onClick:H=>{H.stopPropagation(),ca(p,"replaced")},children:"Replaced"})]})]}
1,p.id)),e.jsx("p",{className:"text-xs text-amber-700",children:"New checkouts leave these out until the item is whole again."})]})]}),s.description&&e.jsxs("div",{className:"mt-3 text-sm",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Description"}),e.jsx("p",{className:"text-gray-700 mt-0.5",children:s.description})]}),s.notes&&e.jsxs("div",{className:"mt-3 text-sm",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Notes"}),e.jsx("p",{className:"text-gray-700 mt-0.5",children:s.notes})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-gray-400",children:"Photos"}),k&&e.jsxs(e.Fragment,{children:[e.jsx(d,{type:"button",variant:"secondary",size:"sm",isLoading:ua,onClick:()=>gt.current?.click(),children:"Upload photo"}),e.jsx(Yt,{label:"Take a photo",disabled:ua,onChange:p=>fa(s,p.target.files?.[0])}),e.jsx("span",{className:"text-xs text-gray-400",children:"JPEG, PNG, or WebP · large photos are resized automatically"}),e.jsx("input",{ref:gt,type:"file",accept:"image/jpeg,image/png,image/webp",hidden:!0,onChange:p=>fa(s,p.target.files?.[0]),"aria-label":"Upload equipment photo"})]})]}),D===void 0?e.jsx("p",{className:"text-sm text-gray-400",children:"Loading photosâ¦"}):D.length===0?e.jsx(Ie,{size:"compact",title:"No photos yet."}):e.jsx("div",{className:"flex flex-wrap gap-3",children:D.map(p=>e.jsxs("div",{className:"relative group",children:[e.jsx("a",{href:p.photoUrl,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:p.photoUrl,alt:p.caption||s.name,className:"h-24 w-24 object-cover rounded-lg border border-gray-200"})}),k&&e.jsx("button",{type:"button","aria-label":"Remove photo",onClick:()=>Mt({item:s,photo:p}),className:"absolute -top-2 -right-2 hidden group-hover:flex h-6 w-6 items-center justify-center rounded-full bg-red-600 text-white text-xs shadow",children:"â"})]},p.id))})]})]})]},s.id)})]}))]}),f==="categories"&&e.jsxs(e.Fragment,{children:[ga&&e.jsxs("div",{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:tt?"Edit Category":"New Category"}),e.jsxs("div",{className:"flex gap-2 pb-4",children:[e.jsx(d,{type:"button",variant:"primary",size:"sm",onClick:t=>t.target.closest(".bg-white")?.querySelector("form")?.requestSubmit(),children:tt?"Save changes":"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>{ht(!1),at(null)},children:"Cancel"})]}),e.jsxs("form",{onSubmit:rs,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Name"}),e.jsx("input",{type:"text",required:!0,value:Ve.name,onChange:t=>pt({...Ve,name:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Description"}),e.jsx("input",{type:"text",value:Ve.description,onChange:t=>pt({...Ve,description:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{type:"submit",variant:"primary",size:"sm",children:tt?"Save changes":"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>{ht(!1),at(null)},children:"Cancel"})]})]})]}),!ga&&(C.length===0?e.jsx(Ie,{card:!0,title:"No categories yet.",action:k?e.jsx(d,{variant:"primary",size:"sm",onClick:()=>Bt(),children:"Create first category"}):null}):e.jsx("div",{className:"space-y-2",children:C.map((t,s)=>e.jsxs("div",{...k?Ae.getRowProps(s):{},draggable:k&&!Ae.tapMode,onDragStart:()=>Ae.handleDragStart(s),onDragOver:S=>Ae.handleDragOver(S,s),onDrop:S=>Ae.handleDrop(S,s),onDragEnd:Ae.handleDragEnd,className:`bg-white rounded-xl border p-4 flex items-center justify-between transition-colors ${Ae.dragOverIndex===s?"border-band-400 bg-band-50":"border-gray-200"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[k&&e.jsx("div",{...Ae.getHandleProps(s),className:"shrink-0 text-gray-300 cursor-grab touch-none p-1 -m-1",title:"Drag to reorder",children:e.jsxs("svg",{className:"h-4 w-4",fill:"
1currentColor",viewBox:"0 0 20 20",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"})]})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-gray-900",children:t.name}),t.description&&e.jsx("div",{className:"text-sm text-gray-500",children:t.description})]})]}),k&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{variant:"ghost",size:"sm",onClick:()=>Bt(t),children:"Edit"}),e.jsx(d,{variant:"ghost",size:"sm",onClick:()=>ns(t),children:"Delete"})]})]},t.id))}))]}),f==="loans"&&j&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide",children:"Member checkouts"}),k&&l&&e.jsx(d,{size:"sm",variant:"secondary",onClick:()=>Fe({}),children:"New loanâ¦"})]}),!l&&e.jsxs("p",{className:"text-sm text-gray-600 mb-3",children:["Checking instruments out to members, with an online or paper agreement, is on the Complete plan. Anything already checked out stays here and can still be marked returned."," ",k&&e.jsx(Na,{to:"/settings/billing",className:"text-band-700 font-medium hover:underline",children:"See plans"})]}),Vt.length===0?e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 p-6 text-center",children:e.jsx("p",{className:"text-gray-500 text-sm",children:"Nothing checked out to members."})}):e.jsx("div",{className:"space-y-3",children:Xa.map(t=>e.jsx(Ea,{group:t,canManage:k,onCheckin:(s,S)=>ut({loan:s,item:S}),onNudge:l?(s,S)=>It({loan:s,kind:S}):void 0,onExtend:l?s=>zt({loan:s}):void 0,onPaper:s=>Tt({loan:s}),onSell:Lt&&ye(Ne,t[0].item)?(s,S)=>ot({item:S,loan:s,product:ye(Ne,S)}):void 0},t[0].loan.batchId||t[0].loan.id))}),e.jsx(Oa,{isOpen:!!ia,target:ia,onClose:()=>It(null),onSent:()=>{It(null),we()}}),e.jsx(Da,{isOpen:!!la,target:la,onClose:()=>zt(null),onSaved:()=>{zt(null),we()}}),e.jsx(Qe,{isOpen:!!oa,title:"Record Signed Paper Copy",message:"Mark this loan agreement as signed on paper? This completes the whole loan (every item on it), exactly like an online signature â keep the signed sheet in your files.",confirmLabel:"Record signature",onConfirm:async()=>{try{await M.recordPaperSignature(oa.loan.id),i("Paper signature recorded â loan approved"),Tt(null),we()}catch(t){o(t.message||"Could not record the signature")}},onClose:()=>Tt(null)})]}),e.jsx("h3",{className:"text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2",children:"Between organizations"}),R.length===0?e.jsx(Ie,{card:!0,title:"No equipment loans between organizations yet."}):e.jsx("div",{className:"space-y-2",children:R.map(t=>{const s=t.lendingOrgId===a?.id;return e.jsx("div",{className:"bg-white rounded-xl border border-gray-200 p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-gray-900",children:t.equipmentName}),e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:[s?`To: ${t.borrowingOrg?.name}`:`From: ${t.lendingOrg?.name}`,t.quantityRequested>1&&` (qty: ${t.quantityRequested})`]}),t.requestNotes&&e.jsx("div",{className:"text-sm text-gray-400 mt-1",children:t.requestNotes})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-2",children:[e.jsx("span",{className:`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${Us[t.status]}`,children:t.status}),v&&s&&t.status==="requested"&&e.jsxs(e.Fragment,{children:[e.jsx(d,{variant:"primary",size:"sm",onClick:()=>bt(t.id,"approve"),children:"Approve"}),e.jsx(d,{variant:"danger",size:"sm",onClick:()=>bt(t.id,"decline"),children:"Decline"})]}),v&&s&&t.status==="approved"&&e.jsx(d,{variant:"primary",size:"sm",onClick:()=>bt(t.id,"activate"),children:"Activate"}),v&&t.status==="active"&&e.jsx(d,{variant:"secondary",size:"sm",onClick:()=>bt(t.id,"return"),children:"Mark returned"})]})]})},t.id)})})]}),f==="mapping"&&e.jsxs(e.Fragment,{children:[pa&&e.jsxs("div",{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:"New Mapping"}),e.jsxs("div",{className:"flex gap-2 pb-4",children:[e.jsx(d,{type:"button",variant:"primary",size:"sm",onClick:t=>t.target.closest(".bg-white")?.querySelector("form")?.requestSubmit(),children:"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>st(!1),children:"Cancel"})]}),e.jsxs("form",{onSubmit:is,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Instrument"}),e.jsxs("select",{value:ge.instrumentId,onChange:t=>Be({...ge,instrumentId:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"",children:"Any"}),_.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Instrument Family"}),e.jsx("input",{type:"text",value:ge.instrumentFamily,onChange:t=>Be({...ge,instrumentFamily:t.target.value}),placeholder:"e.g. percussion",className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Equipment Name"}),e.jsx("input",{type:"text",required:!0,value:ge.equipmentName,onChange:t=>Be({...ge,equipmentName:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Qty Per Player"}),e.jsx("input",{type:"number",min:"1",value:ge.quantityPerPlayer,onChange:t=>Be({...ge,quantityPerPlayer:parseInt(t.target.value)||1}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Priority"}),e.jsxs("select",{value:ge.priority,onChange:t=>Be({...ge,priority:t.target.value}),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm",children:[e.jsx("option",{value:"required",children:"Required"}),e.jsx("option",{value:"optional",children:"Optional"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(d,{type:"submit",variant:"primary",size:"sm",children:"Create"}),e.jsx(d,{type:"button",variant:"secondary",size:"sm",onClick:()=>st(!1),children:"Cancel"})]})]})]}),!pa&&(N.length===0?e.jsx(Ie,{card:!0,title:"No instrument-equipment mappings yet.",action:k?e.jsx(d,{variant:"primary",size:"sm",onClick:()=>st(!0),children:"Create first mapping"}):null}):e.jsx("div",{className:"space-y-2",children:N.map(t=>{const s=t.instrumentId?_.find(S=>S.id===t.instrumentId)?.name:null;return e.jsxs("div",{className:"bg-white rounded-xl border border-gray-200 p-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-gray-900",children:t.equipmentName}),e.jsxs("div",{className:"text-sm text-gray-500 flex flex-wrap gap-3 mt-1",children:[s&&e.jsxs("span",{children:["Instrument: ",s]}),t.instrumentFamily&&e.jsxs("span",{children:["Family: ",t.instrumentFamily]}),e.jsxs("span",{children:["Qty/player: ",t.quantityPerPlayer]}),e.jsx("span",{className:`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${t.priority==="required"?"bg-blue-100 text-blue-800":"bg-gray-100 text-gray-600"}`,children:t.priority})]})]}),y&&e.jsx(d,{variant:"ghost",size:"sm",onClick:()=>ls(t.id),children:"Delete"})]},t.id)})}))]}),e.jsx(Cs,{isOpen:Qa,onClose:()=>aa(!1)}),e.jsx(Fa,{isOpen:!!sa,item:sa,onClose:()=>Rt(null),onSaved:()=>{Rt(null),na(t=>t+1),be()}}),e.jsx(Va,{isOpen:!!ra,item:ra,onClose:()=>ct(null),onSaved:()=>{ct(null),na(t=>t+1),be()}}),e.jsx(Ba,{isOpen:!!Ct,onClose:()=>Kt(null),item:Ct?.item,kind:Ct?.kind,onDone:()=>{be(),we(),Xe()}}),e.jsx(_a,{isOpen:!!St,onClose:()=>Xt(null),item:St},St?.id||"none"),e.jsx(Bs,{isOpen:!!Zt,onClose:()=>ea(null),item:Zt,onChanged:()=>{Xe(),be()}}),e.jsx(Ga,{isOpen:!!Ke,onClose:()=>ot(null),item:Ke?.item,product:Ke?.product,loan:Ke?.loan||null,memberId:Ke?.memberId||"",onDone:()=>{be(),we(),Xe(),f==="loans"&&Dt()}}),e.jsx(Ta,{item:De&&De.id?De:null,items:r,activeLoans:oe,isOpen:!!De,onClose:()=>Fe(null),onSaved:()=>{Fe(null),we()},product:De&&Lt?ye(Ne,De):null,onBuyInstead:(t,s)=>ot({item:t,memberId:s,product:ye(Ne,t)})}),e.jsx(Ma,{loan:dt?.loan,item:dt?.item,isOpen:!!dt,onClose:()=>ut(null),onSaved:Ya}),e.jsx(Qe,{isOpen:ee,title:"Delete Equipment",message:`Are you sure you want to delete "${re?.name}"?`,confirmLabel:"Delete",onConfirm:ss,onClose:()=>{te(!1),ne(null)}}),e.jsx(Qe,{isOpen:!!Ze,title:"Remove Photo",message:`Remove this photo of "${Ze?.item?.name}"? This cannot be undone.`,confirmLabel:"Remove",onConfirm:()=>Ze&&es(Ze.item,Ze.photo.id),onClose:()=>Mt(null)})]})}export{pr as EquipmentPage};
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.