diff --git a/CHANGELOG.md b/CHANGELOG.md index e8c04050e..c81bf8154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.5b1] - Unreleased +### Fixed +- **Label printing produced two identical PDFs per click (#1628)** — `LabelTemplatePickerModal.tsx::openBlobInNewTab` called `window.open(url, '_blank', 'noopener,noreferrer')` and treated a `null` return as "popup blocked → fall back to `` click." Per the WindowFeatures spec, `noopener` deliberately forces `window.open` to return `null` even on success, so the `if (!win)` fallback fired on EVERY click. Path 1 (window.open) opened the blob tab — on Linux Chromium without an inline PDF viewer the OS saved a random-named copy (the `zo70GhSL.pdf` / `f7w0OcDi.pdf` files in the reporter's screenshot). Path 2 (fallback) downloaded a second copy named `bambuddy-labels.pdf`. Two identical PDFs per click. Fix: drop `noopener,noreferrer`. The blob is same-origin (created via `URL.createObjectURL` from our own fetch response), the destination is a passive PDF preview tab with no script context to abuse `window.opener`, and `noreferrer` is a no-op for blob URLs. After removal, `window.open` returns a real window reference on success → `if (!win)` only fires on genuine popup-block, single PDF per click. Existing 17 vitest cases in `LabelTemplatePickerModal.test.tsx` still pass; the change is comment + one parameter. + ### Changed - **AMS drying now enabled for H2C starting at firmware 01.02.00.00** — H2C was previously in `_DRYING_UNSUPPORTED_MODELS` alongside the A1 family. Moved to `_DRYING_MIN_FIRMWARE` with the same `01.02.00.00` floor as H2S / P2S. Both SSDP model codes the H2C advertises (`O1C`, `O1C2` — single- and dual-nozzle variants) get the same firmware gate so the `supports_drying()` check fires correctly regardless of which form is in the printer record. Test coverage extended in `TestSupportsDrying`: H2C / O1C / O1C2 cases added to the with-firmware pass set, the old-firmware fail set, and removed from the unsupported-models loop. diff --git a/frontend/src/components/LabelTemplatePickerModal.tsx b/frontend/src/components/LabelTemplatePickerModal.tsx index e083f9e2a..0c9a95c23 100644 --- a/frontend/src/components/LabelTemplatePickerModal.tsx +++ b/frontend/src/components/LabelTemplatePickerModal.tsx @@ -73,7 +73,16 @@ const TEMPLATE_OPTIONS: TemplateOption[] = [ function openBlobInNewTab(blob: Blob): void { const url = window.URL.createObjectURL(blob); - const win = window.open(url, '_blank', 'noopener,noreferrer'); + // Do NOT pass `noopener,noreferrer`: per the WindowFeatures spec, `noopener` + // forces window.open to return `null` even on success, which made the + // `if (!win)` popup-block fallback below fire on EVERY click — so the blob + // tab opened (downloading a random-named PDF on systems without an inline + // viewer) AND the `` fallback fired (downloading a second copy + // named bambuddy-labels.pdf). Two identical PDFs per click — issue #1628. + // The blob is same-origin, the destination is a passive PDF tab with no + // script context, and `noreferrer` is a no-op for blob URLs, so dropping + // these flags has no security impact. + const win = window.open(url, '_blank'); if (!win) { const a = document.createElement('a'); a.href = url; diff --git a/static/assets/index-B_QEe6y0.js b/static/assets/index-CYiRVzBv.js similarity index 99% rename from static/assets/index-B_QEe6y0.js rename to static/assets/index-CYiRVzBv.js index 8d6f5d67c..59d175fc2 100644 --- a/static/assets/index-B_QEe6y0.js +++ b/static/assets/index-CYiRVzBv.js @@ -8729,7 +8729,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ls(t. `+n.map(([s,o])=>a+" "+JSON.stringify(s)+": "+cI(o,e+1)).join(`, `)+` `+a+"}"}return String(t)}function Wit({setting:t,onClose:e,onDeleted:a,onDuplicate:n,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=sa(),c=aa(),[d,u]=y.useState(!1),{data:m,isLoading:p}=Qe({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>re.getCloudSettingDetail(t.setting_id)}),f=lt({mutationFn:()=>re.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),a()},onError:b=>l(b.message,"error")}),g=NS(t.setting_id),v=S5(t.name,m?.setting?.inherits);return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&r.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),r.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[r.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsx("span",{children:v.printer})]})]})]}),r.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:cI(m)}):r.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?r.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[r.jsx(ga,{className:"w-5 h-5"}),r.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),r.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(De,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),r.jsxs(De,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(ta,{className:"w-4 h-4"}),o("common.delete")]})]})]}):r.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex gap-2",children:[r.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),r.jsxs(De,{variant:"secondary",onClick:n,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[r.jsx(bi,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),g&&r.jsxs(r.Fragment,{children:[r.jsxs(De,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[r.jsx(xi,{className:"w-4 h-4"}),o("common.edit")]}),r.jsx(De,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:r.jsx(ta,{className:"w-4 h-4"})})]})]})})]})})})}function dde(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function ude(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Kit({onClose:t,onApply:e,t:a}){const{showToast:n}=sa(),[i,s]=y.useState(dde),[o,l]=y.useState("all"),[c,d]=y.useState(null),[u,m]=y.useState(""),[p,f]=y.useState(""),[g,v]=y.useState("{}"),[b,x]=y.useState(null),[S,k]=y.useState(null),N=o==="all"?i:i.filter(O=>O.type===o),C=O=>{s(O),ude(O)},T=O=>{const L=i.filter(Y=>Y.id!==O);C(L),k(null),n(a("profiles.templates.toast.deleted"))},j=O=>{d(O.id),m(O.name),f(O.description),v(JSON.stringify(O.settings,null,2)),x(null)},F=()=>{if(!(!c||!u.trim()))try{const O=JSON.parse(g),L=i.map(Y=>Y.id===c?{...Y,name:u.trim(),description:p.trim(),settings:O}:Y);C(L),d(null),n(a("profiles.templates.toast.updated"))}catch(O){x(O.message)}},P=()=>{d(null),m(""),f(""),v("{}"),x(null)},D=O=>{const L=i.map(Y=>Y.id===O?{...Y,showInModal:!Y.showInModal}:Y);C(L)},R={filament:{label:a("profiles.presets.types.filament"),icon:AT,color:"text-amber-400"},print:{label:a("profiles.presets.types.process"),icon:hu,color:"text-blue-400"},printer:{label:a("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},B=S?i.find(O=>O.id===S):null;return y.useEffect(()=>{const O=L=>{L.key==="Escape"&&(S?k(null):c?P():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[S,c,t]),r.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[B&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:r.jsx(At,{className:"w-full max-w-md",children:r.jsxs(Mt,{className:"p-6",children:[r.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[r.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:r.jsx(ga,{className:"w-6 h-6 text-red-400"})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:a("profiles.templates.deleteTitle")}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("profiles.templates.deleteWarning")})]})]}),r.jsx("p",{className:"text-white mb-6",children:a("profiles.templates.deleteConfirm",{name:B.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(De,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:a("common.cancel")}),r.jsxs(De,{onClick:()=>T(S),className:"flex-1 bg-red-500 hover:bg-red-600",children:[r.jsx(ta,{className:"w-4 h-4"}),a("common.delete")]})]})]})})}),r.jsx(At,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:r.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(zg,{className:"w-5 h-5 text-amber-400"}),a("profiles.templates.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(O=>r.jsx("button",{onClick:()=>l(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?a("common.all"):R[O].label},O))]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:N.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(zg,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:a("profiles.templates.noTemplates")}),r.jsx("p",{className:"text-sm mt-1",children:a("profiles.templates.createFirst")})]}):r.jsx("div",{className:"space-y-2",children:N.map(O=>{const L=R[O.type],Y=L.icon;return c===O.id?r.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[r.jsx("input",{type:"text",value:u,onChange:ee=>m(ee.target.value),placeholder:a("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:p,onChange:ee=>f(ee.target.value),placeholder:a("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:a("profiles.templates.settingsJson")}),r.jsx("textarea",{value:g,onChange:ee=>{v(ee.target.value),x(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${b?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),b&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(De,{size:"sm",onClick:F,disabled:!u.trim(),children:[r.jsx(cs,{className:"w-4 h-4"}),"Save"]}),r.jsx(De,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},O.id):r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[r.jsx(Y,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:O.name}),r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),r.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:a("profiles.templates.fieldsCount",{count:Object.keys(O.settings).length})}),r.jsx("button",{onClick:()=>D(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?a("profiles.templates.shownInModals"):a("profiles.templates.hiddenInModals"),children:O.showInModal?r.jsx(Cl,{className:"w-4 h-4"}):r.jsx(db,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:a("profiles.templates.apply")}),r.jsx("button",{onClick:()=>j(O),className:"p-1 text-bambu-gray hover:text-white",title:a("common.edit"),children:r.jsx(xi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>k(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:a("common.delete"),children:r.jsx(ta,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function mde({onClose:t,leftPreset:e,rightPreset:a,leftLabel:n,rightLabel:i,t:s}){const[o,l]=y.useState("changes"),[c,d]=y.useState(""),u=y.useMemo(()=>{const g=new Set([...Object.keys(e),...Object.keys(a)]),v=[];for(const b of g){if(b==="inherits"||b==="version")continue;const x=e[b],S=a[b],k=b in e,N=b in a;let C;!k&&N?C="added":k&&!N?C="removed":JSON.stringify(x)!==JSON.stringify(S)?C="changed":C="same",v.push({key:b,left:x,right:S,status:C})}return v.sort((b,x)=>{const S={changed:0,added:1,removed:2,same:3};return S[b.status]!==S[x.status]?S[b.status]-S[x.status]:b.key.localeCompare(x.key)})},[e,a]),m=y.useMemo(()=>{let g=[...u];if(o==="changes"&&(g=g.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();g=g.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return g},[u,o,c]),p=y.useMemo(()=>({added:u.filter(g=>g.status==="added").length,removed:u.filter(g=>g.status==="removed").length,changed:u.filter(g=>g.status==="changed").length,same:u.filter(g=>g.status==="same").length}),[u]),f=g=>{if(g===void 0)return"—";if(g===null)return"null";if(Array.isArray(g))return g.length===0?"[]":g.length===1?String(g[0]):g.join(", ");if(typeof g=="object")return JSON.stringify(g);const v=String(g);if(v.includes("\\n")||v.length>100){const b=v.split("\\n").length;if(b>1)return`[${b} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return y.useEffect(()=>{const g=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t]),r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsx(At,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:r.jsxs(Mt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(ny,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),r.jsx("p",{className:"text-white font-medium truncate",children:n})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),r.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),r.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[r.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[r.jsx(ar,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx(cC,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[r.jsx(nC,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),r.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[r.jsx(xE,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:c,onChange:g=>d(g.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),p.same>0&&r.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),r.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?r.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[r.jsx(xE,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),r.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:r.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[r.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),r.jsx("th",{className:"text-left p-3 w-1/3",children:n}),r.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),r.jsx("tbody",{children:m.map(g=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[g.status],b={added:r.jsx(ar,{className:"w-3.5 h-3.5 text-green-400"}),removed:r.jsx(cC,{className:"w-3.5 h-3.5 text-red-400"}),changed:r.jsx(nC,{className:"w-3.5 h-3.5 text-amber-400"}),same:r.jsx(xE,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[g.status];return r.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[r.jsx("td",{className:"p-3",children:r.jsxs("div",{className:"flex items-center gap-2",children:[b,r.jsx("span",{className:"text-sm text-white font-mono",children:g.key})]})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="removed"?"text-red-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.left)})}),r.jsx("td",{className:"p-3",children:r.jsx("span",{className:`text-sm font-mono break-all ${g.status==="added"?"text-green-300":g.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(g.right)})})]},g.key)})})]})})]})})})}function Yit({onClose:t,initialData:e,allPresets:a,t:n}){const{showToast:i}=sa(),s=aa(),o=!!e?.setting_id,[l,c]=y.useState("common"),[d,u]=y.useState(e?.type||"filament"),[m,p]=y.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,g]=y.useState(e?.base_id||""),[v,b]=y.useState(""),[x,S]=y.useState(e?.setting||{inherits:""}),[k,N]=y.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[C,T]=y.useState(null),[j,F]=y.useState(""),[P,D]=y.useState(!1),[R,B]=y.useState(""),[O,L]=y.useState(!1),[Y,ee]=y.useState(dde),[Z,ce]=y.useState(!1),[de,ue]=y.useState(""),[Q,ne]=y.useState(""),[pe,me]=y.useState(!0),[be,q]=y.useState(null),[J,A]=y.useState(!1),M=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer})[d]||[],[a,d]),H=y.useMemo(()=>M.filter(Fe=>NS(Fe.setting_id)),[M]),{data:W}=Qe({queryKey:["cloudFields",d],queryFn:()=>re.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:U}=Qe({queryKey:["allPresetDetails",d,H.map(Fe=>Fe.setting_id).join(",")],queryFn:async()=>{const Fe={};for(let Oe=0;Oe{try{const Te=await re.getCloudSettingDetail(st.setting_id);return{id:st.setting_id,detail:Te}}catch{return null}}))).forEach(st=>{st&&(Fe[st.id]=st.detail)})}return Fe},enabled:H.length>0,staleTime:1e3*60*10}),{data:se,isLoading:I}=Qe({queryKey:["cloudSettingDetail",f],queryFn:()=>re.getCloudSettingDetail(f),enabled:!!f});y.useEffect(()=>{l!=="json"&&N(JSON.stringify(x,null,2))},[x,l]);const G=y.useMemo(()=>({filament:a.filament,print:a.process,printer:a.printer}[d]||[]).filter(qe=>!NS(qe.setting_id)).sort((qe,Oe)=>qe.name.localeCompare(Oe.name)),[a,d]);y.useEffect(()=>{if(!f)return;const Fe=G.find(qe=>qe.setting_id===f);Fe&&(b(Fe.name),o||(S({inherits:Fe.name}),N(JSON.stringify({inherits:Fe.name},null,2))))},[f,G,o]);const K=y.useMemo(()=>{const Fe=W?.fields||[],qe=new Set(Fe.map(st=>st.key)),Oe=new Set,it=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);U&&Object.values(U).forEach(st=>{st?.setting&&Object.keys(st.setting).forEach(Te=>{!qe.has(Te)&&!it.has(Te)&&Oe.add(Te)})}),Object.keys(x).forEach(st=>{!qe.has(st)&&!it.has(st)&&Oe.add(st)});const Le=Array.from(Oe).sort().map(st=>({key:st,label:st.replace(/_/g," ").replace(/\b\w/g,Te=>Te.toUpperCase()),type:"text",category:"discovered",description:n("profiles.presets.discoveredFromPresets")}));return[...Fe,...Le]},[W,U,x,n]),X=K.filter(Fe=>Fe.label.toLowerCase().includes(j.toLowerCase())||Fe.key.toLowerCase().includes(j.toLowerCase())),ie=()=>{if(R.trim()){const Fe=R.trim().toLowerCase().replace(/\s+/g,"_");oe(Fe,""),B(""),L(!1),i(n("profiles.presets.toast.fieldAdded",{key:Fe}))}},oe=(Fe,qe)=>{S(Oe=>{const it={...Oe};return qe===""||qe===void 0?delete it[Fe]:it[Fe]=qe,it})},he=Fe=>{S(qe=>({...qe,...Fe.settings})),q(Fe.name),i(n("profiles.templates.toast.applied"))},le=()=>{if(!de.trim())return;const Fe={...x};if(delete Fe.inherits,Object.keys(Fe).length===0){i(n("profiles.presets.noOverridesToSave"),"error");return}const qe={id:Date.now().toString(),name:de.trim(),description:Q.trim()||n("profiles.presets.customTemplate"),type:d,settings:Fe,showInModal:pe},Oe=[...Y,qe];ee(Oe),ude(Oe),ce(!1),ue(""),ne(""),me(!0),i(n("profiles.templates.toast.created"))},fe=y.useMemo(()=>Y.filter(Fe=>Fe.type===d&&Fe.showInModal),[d,Y]),$=Fe=>{N(Fe);try{const qe=JSON.parse(Fe);S(qe),T(null)}catch(qe){T(qe.message)}},z=Fe=>{Fe.preventDefault(),D(!1);const qe=Fe.dataTransfer.files[0];if(qe&&qe.name.endsWith(".json")){const Oe=new FileReader;Oe.onload=it=>{try{const Le=it.target?.result,st=JSON.parse(Le),Te=st.setting||st;S(Xe=>({...Xe,...Te})),N(JSON.stringify({...x,...Te},null,2)),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJsonFile"),"error")}},Oe.readAsText(qe)}},ae=lt({mutationFn:()=>{const Fe={...x},qe=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";Fe[qe]=`"${m}"`;const Oe={type:d,name:m,base_id:f,setting:Fe};return re.createCloudSetting(Oe)},onSuccess:async()=>{i(n("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Fe=>i(Fe.message,"error")}),ge=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(n("profiles.presets.noSettingId"));return re.updateCloudSetting(e.setting_id,{name:m,setting:x})},onSuccess:async()=>{i(n("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Fe=>i(Fe.message,"error")}),xe=o?ge:ae,ve=se?.setting?.inherits,je=ve?G.find(Fe=>Fe.name===ve):void 0,{data:Me}=Qe({queryKey:["cloudSettingDetail",je?.setting_id],queryFn:()=>re.getCloudSettingDetail(je.setting_id),enabled:!!je?.setting_id}),Se=y.useMemo(()=>{const Fe=Me?.setting||{},qe=se?.setting||{},Oe=f&&U?.[f]?.setting?U[f].setting:{};return{...Fe,...qe,...Oe}},[f,se,Me,U]),Ue=Fe=>{if(Fe==null)return"";if(Array.isArray(Fe)){const qe=[...new Set(Fe.map(Oe=>String(Oe)))];return qe.length===1?qe[0]:Fe.join(", ")}return String(Fe)},_e=Fe=>{const qe=x[Fe.key],Oe=Se[Fe.key],it=Ue(Oe),Le=I?n("common.loading"):it||"",st="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Fe.type==="boolean"){const Te=qe==="1"||qe===void 0&&Oe==="1";return r.jsx("button",{type:"button",onClick:()=>oe(Fe.key,qe==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Te?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Te?"translate-x-3.5":"translate-x-0.5"}`})})}return Fe.type==="select"?r.jsxs("select",{value:qe||"",onChange:Te=>oe(Fe.key,Te.target.value),className:st,children:[r.jsx("option",{value:"",children:Le}),Fe.options?.map(Te=>r.jsx("option",{value:Te.value,children:Te.label},Te.value))]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:Fe.type==="number"?"number":"text",value:qe!==void 0?String(qe):"",onChange:Te=>oe(Fe.key,Te.target.value),step:Fe.step,min:Fe.min,max:Fe.max,placeholder:Le,className:st}),Fe.unit&&r.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Fe.unit})]})},ze=y.useMemo(()=>se?.setting?se.setting:{},[se]);return r.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Fe=>{Fe.preventDefault(),D(!0)},onDragLeave:()=>D(!1),onDrop:z,children:[J&&f&&r.jsx(mde,{onClose:()=>A(!1),leftPreset:ze,rightPreset:x,leftLabel:n("profiles.presets.baseLabel",{name:v||f}),rightLabel:n("profiles.presets.currentLabel",{name:m||n("profiles.presets.newPreset")}),t:n}),r.jsx(At,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:r.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("profiles.presets.customizeSettings")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[f&&r.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:n("profiles.presets.compareWithBase"),children:[r.jsx(ny,{className:"w-4 h-4"}),n("profiles.presets.compare")]}),r.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]})]}),P&&r.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(kn,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),r.jsx("p",{className:"text-bambu-green font-medium",children:n("profiles.presets.dropJsonToImport")})]})}),r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("common.type")}),r.jsxs("select",{value:d,onChange:Fe=>{u(Fe.target.value),g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"filament",children:n("profiles.presets.types.filament")}),r.jsx("option",{value:"print",children:n("profiles.presets.types.process")}),r.jsx("option",{value:"printer",children:n("profiles.presets.types.printer")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.basePreset")}),r.jsxs("select",{value:f,onChange:Fe=>g(Fe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"",children:n("profiles.presets.selectBasePreset")}),G.map(Fe=>r.jsx("option",{value:Fe.setting_id,children:Fe.name},Fe.setting_id))]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("profiles.presets.presetName")}),r.jsx("input",{type:"text",value:m,onChange:Fe=>p(Fe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:n("profiles.presets.myCustomPreset")})]})]}),v&&r.jsx("div",{className:"text-xs text-bambu-gray",children:r.jsxs("p",{className:"flex items-center gap-1",children:[r.jsx(_r,{className:"w-3 h-3 text-bambu-green"}),n("profiles.presets.inheritsFrom")," ",r.jsx("span",{className:"text-white",children:v}),I&&r.jsx(pt,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[r.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(P8,{className:"w-4 h-4"}),n("profiles.presets.tabs.common")]}),r.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(LS,{className:"w-4 h-4"}),n("profiles.presets.tabs.allFields")]}),r.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Jy,{className:"w-4 h-4"}),"JSON",C&&r.jsx(On,{className:"w-3 h-3 text-red-400"})]}),r.jsx("div",{className:"flex-1 max-[640px]:hidden"}),r.jsxs("button",{onClick:()=>{const Fe={name:m,type:d,base_id:f,setting:x},qe=new Blob([JSON.stringify(Fe,null,2)],{type:"application/json"}),Oe=URL.createObjectURL(qe),it=document.createElement("a");it.href=Oe,it.download=`${m||"preset"}.json`,document.body.appendChild(it),it.click(),document.body.removeChild(it),URL.revokeObjectURL(Oe),i(n("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.exportToJson"),children:[r.jsx(Ur,{className:"w-4 h-4"}),n("common.download")]}),r.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:n("profiles.presets.importFromJson"),children:[r.jsx(kn,{className:"w-4 h-4"}),n("common.upload")]}),r.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Fe=>{const qe=Fe.target.files?.[0];if(qe){const Oe=new FileReader;Oe.onload=it=>{try{const Le=JSON.parse(it.target?.result),st=Le.setting||Le;S(Te=>({...Te,...st})),i(n("profiles.presets.fileImported"))}catch{i(n("profiles.presets.invalidJson"),"error")}},Oe.readAsText(qe)}}})]}),r.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&r.jsxs("div",{className:"space-y-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(zg,{className:"w-4 h-4 text-amber-400"}),n("profiles.templates.title")]}),Object.keys(x).filter(Fe=>Fe!=="inherits").length>0&&r.jsxs("button",{onClick:()=>ce(!Z),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[r.jsx(cs,{className:"w-3 h-3"}),n("profiles.presets.saveAsTemplate")]})]}),Z&&r.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:de,onChange:Fe=>ue(Fe.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx("input",{type:"text",value:Q,onChange:Fe=>ne(Fe.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(De,{size:"sm",onClick:le,disabled:!de.trim(),children:[r.jsx(cs,{className:"w-3 h-3"}),n("common.save")]}),r.jsx(De,{size:"sm",variant:"secondary",onClick:()=>ce(!1),children:n("common.cancel")})]}),r.jsxs("button",{onClick:()=>me(!pe),className:`flex items-center gap-1.5 text-xs transition-colors ${pe?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[pe?r.jsx(Cl,{className:"w-3.5 h-3.5"}):r.jsx(db,{className:"w-3.5 h-3.5"}),n(pe?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),be&&r.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[r.jsx(_r,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-sm text-bambu-green",children:[n("profiles.presets.templateApplied")," ",r.jsx("span",{className:"font-medium",children:be})]}),r.jsx("button",{onClick:()=>q(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:r.jsx(Gt,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[fe.map(Fe=>r.jsxs("button",{onClick:()=>he(Fe),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Fe.name}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Fe.description})]},Fe.id)),fe.length===0&&r.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:n("profiles.presets.noTemplatesSelected")})]}),r.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:n("profiles.presets.manageTemplatesHint")})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.commonSettings")}),r.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:K.slice(0,10).map(Fe=>r.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[r.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Fe.label}),r.jsx("div",{className:"w-48 max-[640px]:w-full",children:_e(Fe)})]},Fe.key))})]}),Object.keys(x).length>1&&r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:n("profiles.presets.currentOverrides")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(x).filter(([Fe])=>Fe!=="inherits").map(([Fe,qe])=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Fe,": ",String(qe).slice(0,20),r.jsx("button",{onClick:()=>oe(Fe,void 0),className:"hover:text-white",children:r.jsx(Gt,{className:"w-3 h-3"})})]},Fe))})]})]}),l==="fields"&&r.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.availableFields")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:U?n("profiles.templates.fieldsCount",{count:K.length}):n("common.loading")})]}),r.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:j,onChange:Fe=>F(Fe.target.value),placeholder:n("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[X.filter(Fe=>!(Fe.key in x)).map(Fe=>{const qe=Se[Fe.key],Oe=Ue(qe);return r.jsxs("div",{onClick:()=>{S(it=>({...it,[Fe.key]:Oe||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Fe.label}),r.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Fe.key})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Oe&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Oe,children:[Oe.slice(0,20),Oe.length>20?"...":""]}),r.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:r.jsx(ar,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Fe.key)}),X.filter(Fe=>!(Fe.key in x)).length===0&&r.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:n(j?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"text",value:R,onChange:Fe=>B(Fe.target.value),onKeyDown:Fe=>Fe.key==="Enter"&&ie(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),r.jsx(De,{size:"sm",onClick:ie,disabled:!R.trim(),children:r.jsx(ar,{className:"w-4 h-4"})}),r.jsx(De,{size:"sm",variant:"secondary",onClick:()=>{L(!1),B("")},children:r.jsx(Gt,{className:"w-4 h-4"})})]}):r.jsxs("button",{onClick:()=>L(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(ar,{className:"w-4 h-4"}),n("profiles.presets.addCustomField")]})})]}),r.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[r.jsx("h3",{className:"text-sm font-medium text-white",children:n("profiles.presets.yourOverrides")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:n("profiles.templates.fieldsCount",{count:Object.keys(x).filter(Fe=>Fe!=="inherits").length})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(x).filter(([Fe])=>Fe!=="inherits").map(([Fe,qe])=>{const Oe=K.find(it=>it.key===Fe);return r.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-sm font-medium text-white",children:Oe?.label||Fe}),r.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Fe})]}),r.jsx("button",{onClick:()=>oe(Fe,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:r.jsx(Gt,{className:"w-4 h-4"})})]}),Oe?_e(Oe):r.jsx("input",{type:"text",value:String(qe),onChange:it=>oe(Fe,it.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Fe)}),Object.keys(x).filter(Fe=>Fe!=="inherits").length===0&&r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(P8,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),r.jsx("p",{className:"text-sm",children:n("profiles.presets.noOverridesYet")}),r.jsx("p",{className:"text-xs mt-1",children:n("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(x).filter(Fe=>Fe!=="inherits").length>0&&r.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:r.jsxs("button",{onClick:()=>{ce(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[r.jsx(cs,{className:"w-4 h-4"}),n("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&r.jsxs("div",{className:"space-y-2",children:[C&&r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx(On,{className:"w-4 h-4"}),C]}),r.jsx("textarea",{value:k,onChange:Fe=>$(Fe.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${C?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),r.jsx("p",{className:"text-xs text-bambu-gray",children:n("profiles.presets.jsonTip")})]})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[r.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:n("common.cancel")}),r.jsxs(De,{onClick:()=>xe.mutate(),disabled:xe.isPending||!m.trim()||!o&&!f||!!C,className:"flex-1",children:[xe.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o?r.jsx(cs,{className:"w-4 h-4"}):r.jsx(ar,{className:"w-4 h-4"}),n(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function Qit({settings:t,lastSyncTime:e,onRefresh:a,isRefreshing:n,printers:i,hasPermission:s,t:o}){const[l,c]=y.useState(""),[d,u]=y.useState("all"),[m,p]=y.useState("all"),[f,g]=y.useState("all"),[v,b]=y.useState("all"),[x,S]=y.useState("all"),[k,N]=y.useState("all"),[C,T]=y.useState(null),[j,F]=y.useState(!1),[P,D]=y.useState(!1),[R,B]=y.useState(null),[O,L]=y.useState(null),[Y,ee]=y.useState(null),[Z,ce]=y.useState(!1),[de,ue]=y.useState([null,null]),[Q,ne]=y.useState(!1),[pe,me]=y.useState(null),be=aa(),q=y.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:S5(ie.name)})),[t]),J=y.useMemo(()=>{const X=new Set,ie=new Set,oe=new Set;return q.forEach(he=>{he.meta.nozzle&&X.add(he.meta.nozzle),he.meta.filamentType&&ie.add(he.meta.filamentType),he.meta.layerHeight&&oe.add(he.meta.layerHeight)}),{printers:i.map(he=>({id:he.id.toString(),name:he.name})),nozzles:Array.from(X).sort((he,le)=>parseFloat(he)-parseFloat(le)),filaments:Array.from(ie).sort(),layerHeights:Array.from(oe).sort((he,le)=>parseFloat(he)-parseFloat(le))}},[q,i]),A=y.useMemo(()=>f==="all"?null:i.find(ie=>ie.id.toString()===f)?.model||null,[f,i]),M=y.useMemo(()=>q.filter(X=>d==="all"||X.type===d).filter(X=>{if(m==="all")return!0;const ie=NS(X.setting_id);return m==="custom"?ie:!ie}).filter(X=>{if(f==="all"||!A)return!0;const ie=X.meta.printer?.toLowerCase()||"",oe=A.toLowerCase();return ie.includes(oe)||oe.includes(ie)}).filter(X=>v==="all"||X.meta.nozzle===v).filter(X=>x==="all"||X.meta.filamentType===x).filter(X=>k==="all"||X.meta.layerHeight===k).filter(X=>l===""||X.name.toLowerCase().includes(l.toLowerCase())).sort((X,ie)=>X.name.localeCompare(ie.name)),[q,d,m,f,A,v,x,k,l]),H=X=>{if(Z){const ie=de[0]?.setting_id===X.setting_id,oe=de[1]?.setting_id===X.setting_id;if(ie)ue([de[1],null]);else if(oe)ue([de[0],null]);else if(!de[0])ue([X,null]);else if(de[1]){if(de[0].type!==X.type)return;ue([de[0],X])}else{if(de[0].type!==X.type)return;ue([de[0],X])}}else T(X)},W=X=>{if(de[0]?.setting_id===X.setting_id)return 0;if(de[1]?.setting_id===X.setting_id)return 1},U=async X=>{try{const ie=await re.getCloudSettingDetail(X.setting_id),oe=X.type==="process"?"print":X.type;B({type:oe,name:X.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),T(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},se=async X=>{try{be.removeQueries({queryKey:["cloudSettingDetail",X.setting_id]});const ie=await re.getCloudSettingDetail(X.setting_id),oe=X.type==="process"?"print":X.type;L({type:oe,name:X.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:X.setting_id}),T(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},I=()=>{u("all"),p("all"),g("all"),b("all"),S("all"),N("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||x!=="all"||k!=="all"||l!=="",K=t.filament.length+t.printer.length+t.process.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"space-y-4 mb-6",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",value:l,onChange:X=>c(X.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),r.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r.jsxs(De,{variant:Z?"primary":"secondary",onClick:()=>{Z?(ce(!1),ue([null,null])):ce(!0)},children:[r.jsx(ny,{className:"w-4 h-4"}),o(Z?"common.cancel":"profiles.presets.compare")]}),r.jsxs(De,{variant:"secondary",onClick:()=>D(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[r.jsx(zg,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),r.jsxs(De,{variant:"secondary",onClick:a,disabled:n||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[r.jsx(Qa,{className:`w-4 h-4 ${n?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),r.jsxs(De,{onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx(MS,{className:"w-4 h-4 text-bambu-gray"}),r.jsx(Bx,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:K},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:X=>u(X)}),r.jsx(Bx,{label:o("profiles.cloudView.filters.owner"),value:m,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:X=>p(X)}),J.printers.length>0&&r.jsx(Bx,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.printers.map(X=>({value:X.id,label:X.name}))],onChange:g}),J.nozzles.length>0&&r.jsx(Bx,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.nozzles.map(X=>({value:X,label:X}))],onChange:b}),J.filaments.length>0&&(d==="all"||d==="filament")&&r.jsx(Bx,{label:o("profiles.cloudView.filters.filament"),value:x,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.filaments.map(X=>({value:X,label:X}))],onChange:S}),J.layerHeights.length>0&&(d==="all"||d==="process")&&r.jsx(Bx,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.layerHeights.map(X=>({value:X,label:X}))],onChange:N}),G&&r.jsx("button",{onClick:I,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),Z&&r.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx(ny,{className:"w-5 h-5 text-blue-400"}),r.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),r.jsx("span",{className:"text-bambu-gray",children:de[0]?o("profiles.cloudView.selectAnotherPreset",{type:de[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[0]?de[0].name:o("profiles.cloudView.selectFirst")}),r.jsx(nC,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${de[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:de[1]?de[1].name:o("profiles.cloudView.selectSecond")})]}),de[0]&&de[1]&&r.jsxs(De,{size:"sm",onClick:async()=>{try{const[X,ie]=await Promise.all([re.getCloudSettingDetail(de[0].setting_id),re.getCloudSettingDetail(de[1].setting_id)]);me([X.setting||{},ie.setting||{}]),ne(!0)}catch{}},children:[r.jsx(ny,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx(er,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Rh(e.toISOString(),"system",o)]}),r.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:M.length,total:K})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),r.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),M.length===0?r.jsxs("div",{className:"text-center py-16",children:[r.jsx(cn,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),r.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&r.jsx("button",{onClick:I,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(AT,{className:"w-4 h-4 text-amber-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",M.filter(X=>X.type==="filament").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[M.filter(X=>X.type==="filament").map(X=>r.jsx(NL,{setting:X,onClick:()=>H(X),onDuplicate:()=>U(X),compareMode:Z,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Z&&!!de[0]&&de[0].type!==X.type,t:o},X.setting_id)),M.filter(X=>X.type==="filament").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(hu,{className:"w-4 h-4 text-blue-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",M.filter(X=>X.type==="process").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[M.filter(X=>X.type==="process").map(X=>r.jsx(NL,{setting:X,onClick:()=>H(X),onDuplicate:()=>U(X),compareMode:Z,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Z&&!!de[0]&&de[0].type!==X.type,t:o},X.setting_id)),M.filter(X=>X.type==="process").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[r.jsx(xr,{className:"w-4 h-4 text-purple-400"}),r.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),r.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",M.filter(X=>X.type==="printer").length,")"]})]}),r.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[M.filter(X=>X.type==="printer").map(X=>r.jsx(NL,{setting:X,onClick:()=>H(X),onDuplicate:()=>U(X),compareMode:Z,isCompareSelected:W(X)!==void 0,compareIndex:W(X),compareDisabled:Z&&!!de[0]&&de[0].type!==X.type,t:o},X.setting_id)),M.filter(X=>X.type==="printer").length===0&&r.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),C&&r.jsx(Wit,{setting:C,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>U(C),onEdit:()=>se(C),hasPermission:s,t:o}),(j||R||O||Y)&&r.jsx(Yit,{onClose:()=>{F(!1),B(null),L(null),ee(null)},initialData:O||R||(Y?{type:Y.type,name:"",base_id:"",setting:Y.setting}:void 0),allPresets:t,t:o}),P&&r.jsx(Kit,{onClose:()=>D(!1),onApply:X=>{ee({type:X.type,setting:X.settings}),D(!1)},t:o}),Q&&pe&&de[0]&&de[1]&&r.jsx(mde,{onClose:()=>{ne(!1),me(null)},leftPreset:pe[0],rightPreset:pe[1],leftLabel:de[0].name,rightLabel:de[1].name,t:o})]})}function Xit(){const{t}=wt(),e=aa(),{showToast:a}=sa(),{hasPermission:n}=lr(),[i,s]=y.useState("cloud"),[o,l]=y.useState(),{data:c,isLoading:d}=Qe({queryKey:["cloudStatus"],queryFn:re.getCloudStatus}),{data:u=[]}=Qe({queryKey:["printers"],queryFn:re.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:g}=Qe({queryKey:["cloudSettings"],queryFn:()=>re.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});y.useEffect(()=>{g&&l(new Date(g))},[g]);const v=lt({mutationFn:re.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),a(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?r.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Kh,{className:"w-7 h-7 text-bambu-green"}),t("profiles.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("profiles.subtitle")})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[r.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(Kh,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),r.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(ub,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),r.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${i==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[r.jsx(ES,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&r.jsxs(r.Fragment,{children:[c?.is_authenticated&&r.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),r.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",r.jsx("span",{className:"text-white",children:c.email}),c.region&&r.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs rounded bg-bambu-dark-tertiary text-bambu-gray",children:c.region==="china"?t("profiles.login.regionChina"):t("profiles.login.regionGlobal")})]})]}),r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!n("cloud:auth"),title:n("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[r.jsx(iy,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?r.jsx(Qit,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:n,t}):r.jsxs("div",{className:"text-center py-16",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),r.jsx(De,{onClick:()=>f(),children:t("profiles.retry")})]}):r.jsx($it,{onSuccess:b,t})]}),i==="local"&&r.jsx(Git,{}),i==="kprofiles"&&r.jsx(Bit,{}),r.jsx(Vit,{})]})}function Zit(t,e){const a=(e||"").toUpperCase().replace(/[- ]/g,""),n=a.includes("X1"),i=a.includes("P1"),s=a.includes("A1MINI"),o=a.includes("A1")&&!s,l=a.includes("H2D"),c=a.includes("H2C"),d=a.includes("H2S"),u=l||c||d,m=a.includes("P2S"),p=a.includes("X2D"),f=m||p;switch(t){case"Lubricate Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return f?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return n||i?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":u?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":f?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return n?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":i?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":d?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":f?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return n||i?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return n||i?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":d?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return u?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return u?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}const ew={Droplet:AT,Flame:gm,Ruler:Iye,Sparkles:zg,Square:io,Cable:jI,Wrench:Qm,Calendar:wn,Timer:eu,Cog:hd,Fan:QZ,Zap:Cc,Wind:dJ,Thermometer:BS,Layers:cn,Box:Ai,Target:sJ,RefreshCw:Qa,Settings:wy,Filter:MS,CircleDot:Uge};function Cw(t){return t&&ew[t]||Qm}function Ux(t,e,a){if(e==="days"){if(t<1)return a?a("common.today"):"Today";if(t===1)return a?a("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return a?a("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?a?a("maintenance.week"):"1 week":a?a("maintenance.weeks",{count:i}):`${i} weeks`}const n=Math.round(t/30);return n===1?a?a("maintenance.month"):"1 month":a?a("maintenance.months",{count:n}):`${n} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const n=t/24;if(n<7)return`${n<2?n.toFixed(1):Math.round(n)}d`;const i=n/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function CL(t,e,a){return e==="days"?t===1?a?a("maintenance.day"):"1 day":t===7?a?a("maintenance.week"):"1 week":t===14?a?a("maintenance.weeks",{count:2}):"2 weeks":t===30?a?a("maintenance.month"):"1 month":t===60?a?a("maintenance.months",{count:2}):"2 months":t===90?a?a("maintenance.months",{count:3}):"3 months":t===180?a?a("maintenance.months",{count:6}):"6 months":t===365?a?a("maintenance.year"):"1 year":a?a("maintenance.days",{count:t}):`${t} days`:`${t}h`}function Jit({item:t,onPerform:e,onToggle:a,hasPermission:n,t:i}){const s=Cw(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),d=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",u=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",m=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",p=()=>{if(!t.enabled)return i("common.disabled");if(o==="days"){const f=t.days_until_due??0;return t.is_due?i("maintenance.overdueBy",{duration:Ux(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(f,"days",i)}):i("maintenance.timeLeft",{duration:Ux(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ux(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ux(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ux(t.hours_until_due,"hours",i)})};return r.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:r.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[r.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[r.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&r.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&r.jsx("span",{title:i("maintenance.timeBasedInterval"),children:r.jsx(wn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||Zit(t.maintenance_type_name,t.printer_model);return f?r.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:i("maintenance.viewDocumentation"),onClick:g=>g.stopPropagation(),children:r.jsx(Dr,{className:"w-3.5 h-3.5"})}):null})()]}),r.jsx("div",{className:"mt-2 mb-1.5",children:r.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),r.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&r.jsx(ga,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&r.jsx(er,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&r.jsx(_r,{className:"w-3 h-3"}),p()]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[r.jsx("span",{title:n("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:r.jsx(Ma,{checked:t.enabled,onChange:f=>a(t.id,f),disabled:!n("maintenance:update")})}),r.jsxs(De,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!n("maintenance:update"),title:n("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[r.jsx(hs,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function est({overview:t,onPerform:e,onToggle:a,onSetHours:n,hasPermission:i,t:s}){const[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(t.total_print_hours.toFixed(1)),p=[...t.maintenance_items].sort((v,b)=>v.is_due&&!b.is_due?-1:!v.is_due&&b.is_due?1:v.is_warning&&!b.is_warning?-1:!v.is_warning&&b.is_warning?1:v.maintenance_type_id-b.maintenance_type_id),f=p.find(v=>v.enabled&&(v.is_due||v.is_warning)),g=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(n(t.printer_id,v),d(!1))};return r.jsxs(At,{className:"overflow-hidden",children:[r.jsxs("div",{className:"p-5",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(ga,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&r.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(er,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&r.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[r.jsx(_r,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),r.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Fa,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),r.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:r.jsx(eu,{className:"w-4 h-4 text-bambu-gray"})}),c?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&g(),v.key==="Escape"&&d(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),r.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),r.jsx(De,{size:"sm",onClick:g,children:s("common.save")}),r.jsx(De,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):r.jsxs("button",{onClick:()=>{i("maintenance:update")&&(m(Math.round(t.total_print_hours).toString()),d(!0))},className:`group ${i("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:i("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[r.jsxs("div",{className:`text-sm font-medium text-white ${i("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),r.jsx(Rg,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),r.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),r.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=Cw(f.maintenance_type_icon);return r.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),r.jsxs("div",{children:[r.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),r.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&r.jsx(Mt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:r.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>r.jsx(Jit,{item:v,onPerform:e,onToggle:a,hasPermission:i,t:s},v.id))})})]})}function tst({overview:t,types:e,onUpdateInterval:a,onAddType:n,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=y.useState(null),[g,v]=y.useState(""),[b,x]=y.useState("hours"),[S,k]=y.useState(!1),[N,C]=y.useState(""),[T,j]=y.useState("100"),[F,P]=y.useState("hours"),[D,R]=y.useState("Wrench"),[B,O]=y.useState(""),[L,Y]=y.useState(new Set),[ee,Z]=y.useState(null),[ce,de]=y.useState(null),ue=y.useMemo(()=>t?t.map($=>({id:$.printer_id,name:$.printer_name})):[],[t]),Q=$=>t?t.filter(z=>z.maintenance_items.some(ae=>ae.maintenance_type_id===$)).map(z=>({printerId:z.printer_id,printerName:z.printer_name,itemId:z.maintenance_items.find(ae=>ae.maintenance_type_id===$)?.id})):[],ne=$=>{if(!t)return[];const z=new Set(Q($).map(ae=>ae.printerId));return ue.filter(ae=>!z.has(ae.id))},[pe,me]=y.useState(null),[be,q]=y.useState(""),[J,A]=y.useState(""),[M,H]=y.useState("hours"),[W,U]=y.useState("Wrench"),[se,I]=y.useState(""),G=$=>{me($),q($.name),A($.default_interval_hours.toString()),H($.interval_type||"hours"),U($.icon||"Wrench"),I($.wiki_url||"")},K=()=>{pe&&be.trim()&&parseFloat(J)>0&&(i(pe.id,{name:be.trim(),default_interval_hours:parseFloat(J),interval_type:M,icon:W,wiki_url:se.trim()||null}),me(null))},X=($,z,ae)=>{const ge=parseFloat(g);if(!isNaN(ge)&&ge>0){const xe=Math.abs(ge-z)<.01?null:ge;a($,{custom_interval_hours:xe,custom_interval_type:b!==ae?b:null})}f(null)},ie=$=>{$.preventDefault(),N.trim()&&parseFloat(T)>0&&L.size>0&&(n({name:N.trim(),default_interval_hours:parseFloat(T),interval_type:F,icon:D,wiki_url:B.trim()||null},Array.from(L)),C(""),j("100"),P("hours"),O(""),Y(new Set),k(!1))},oe=$=>{Y(z=>{const ae=new Set(z);return ae.has($)?ae.delete($):ae.add($),ae})},he=t?.map($=>({printerId:$.printer_id,printerName:$.printer_name,items:$.maintenance_items.sort((z,ae)=>z.maintenance_type_id-ae.maintenance_type_id)})).sort(($,z)=>$.printerName.localeCompare(z.printerName))||[],le=e.filter($=>$.is_system),fe=e.filter($=>!$.is_system);return r.jsxs("div",{className:"space-y-8",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(De,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),r.jsxs(De,{onClick:()=>k(!S),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[r.jsx(ar,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),S&&r.jsx(At,{className:"mb-6",children:r.jsx(Mt,{className:"py-4",children:r.jsxs("form",{onSubmit:ie,children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[r.jsxs("div",{className:"lg:col-span-2",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),r.jsx("input",{type:"text",value:N,onChange:$=>C($.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.exampleName"),autoFocus:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),r.jsxs("select",{value:F,onChange:$=>{P($.target.value),$.target.value==="days"?j("30"):j("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:F==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),r.jsx("input",{type:"number",value:T,onChange:$=>j($.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),r.jsx("div",{className:"mt-4 flex items-end justify-between",children:r.jsxs("div",{children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),r.jsx("div",{className:"flex gap-1",children:Object.keys(ew).map($=>{const z=ew[$];return r.jsx("button",{type:"button",onClick:()=>R($),className:`p-2 rounded-lg transition-colors ${D===$?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:r.jsx(z,{className:"w-4 h-4"})},$)})})]})}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),r.jsx("input",{type:"url",value:B,onChange:$=>O($.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),r.jsxs("div",{className:"mt-4",children:[r.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),r.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map($=>r.jsx("button",{type:"button",onClick:()=>oe($.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has($.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:$.name},$.id))}),L.size===0&&r.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),r.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:()=>{k(!1),Y(new Set)},children:m("common.cancel")}),r.jsx(De,{type:"submit",disabled:!N.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[le.map($=>{const z=Cw($.icon),ae=$.interval_type||"hours";return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:r.jsx(z,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-sm font-medium text-white truncate",children:$.name}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?r.jsx(wn,{className:"w-3 h-3"}):r.jsx(eu,{className:"w-3 h-3"}),CL($.default_interval_hours,ae,m)]})]}),r.jsx("button",{onClick:()=>{u("maintenance:delete")&&de($)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(ta,{className:"w-4 h-4"})})]})},$.id)}),fe.map($=>{const z=Cw($.icon),ae=$.interval_type||"hours";if(pe?.id===$.id)return r.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:r.jsxs("div",{className:"space-y-3",children:[r.jsx("input",{type:"text",value:be,onChange:Me=>q(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("common.name"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("select",{value:M,onChange:Me=>H(Me.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:J,onChange:Me=>A(Me.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),r.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(ew).map(Me=>{const Se=ew[Me];return r.jsx("button",{type:"button",onClick:()=>U(Me),className:`p-1.5 rounded transition-colors ${W===Me?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:r.jsx(Se,{className:"w-3.5 h-3.5"})},Me)})}),r.jsx("input",{type:"url",value:se,onChange:Me=>I(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:m("maintenance.documentationLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(De,{size:"sm",onClick:K,disabled:!be.trim(),children:m("common.save")}),r.jsx(De,{size:"sm",variant:"secondary",onClick:()=>me(null),children:m("common.cancel")})]})]})},$.id);const xe=Q($.id),ve=ne($.id),je=ee===$.id;return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:r.jsx(z,{className:"w-5 h-5 text-bambu-green"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-white truncate",children:$.name}),r.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:m("maintenance.custom")})]}),r.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ae==="days"?r.jsx(wn,{className:"w-3 h-3"}):r.jsx(eu,{className:"w-3 h-3"}),CL($.default_interval_hours,ae,m)]})]}),r.jsxs("button",{onClick:()=>Z(je?null:$.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${xe.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:m("maintenance.printersAssignedClick",{count:xe.length}),children:[r.jsx(xr,{className:"w-3 h-3"}),r.jsx("span",{className:"text-xs font-medium",children:xe.length}),r.jsx(Fa,{className:`w-3 h-3 transition-transform ${je?"rotate-180":""}`})]}),r.jsx("button",{onClick:()=>G($),disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${u("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(Rg,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:$.name}))&&s($.id)},disabled:!u("maintenance:delete"),title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${u("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:r.jsx(ta,{className:"w-4 h-4"})})]}),je&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),xe.length===0?r.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):r.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:xe.map(Me=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[Me.printerName,r.jsx("button",{onClick:()=>Me.itemId&&d(Me.itemId),disabled:!u("maintenance:delete"),title:u("maintenance:delete")?m("maintenance.removeFromPrinter"):m("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${u("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},Me.printerId))}),ve.length>0&&r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ve.map(Me=>r.jsxs("button",{onClick:()=>c(Me.id,$.id),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${u("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",Me.name]},Me.id))]})]})]},$.id)})]})]}),he.length>0&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),r.jsx("div",{className:"space-y-4",children:he.map($=>r.jsx(At,{children:r.jsxs(Mt,{className:"py-4",children:[r.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:$.printerName}),r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:$.items.map(z=>{const ae=Cw(z.maintenance_type_icon),ge=e.find(Se=>Se.id===z.maintenance_type_id),xe=ge?.default_interval_hours||z.interval_hours,ve=ge?.interval_type||"hours",je=z.interval_type||"hours",Me=p===z.id;return r.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[r.jsx(ae,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:z.maintenance_type_name}),Me?r.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?r.jsx(wn,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):r.jsx(eu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),r.jsxs("select",{value:b,onChange:Se=>x(Se.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[r.jsx("option",{value:"hours",children:m("maintenance.printHours")}),r.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),r.jsx("input",{type:"number",value:g,onChange:Se=>v(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&X(z.id,xe,ve),Se.key==="Escape"&&f(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),r.jsx(De,{size:"sm",onClick:()=>X(z.id,xe,ve),children:"OK"})]}):r.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(z.id),v(z.interval_hours.toString()),x(je))},disabled:!u("maintenance:update"),title:u("maintenance:update")?void 0:m("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${u("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[je==="days"?r.jsx(wn,{className:"w-3 h-3"}):r.jsx(eu,{className:"w-3 h-3"}),CL(z.interval_hours,je,m),r.jsx(Rg,{className:"w-3 h-3 text-bambu-gray"})]})]},z.id)})})]})},$.printerId))})]}),he.length===0&&r.jsx(At,{children:r.jsxs(Mt,{className:"text-center py-12",children:[r.jsx(er,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ce&&r.jsx(ya,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ce.name}),confirmText:m("common.delete"),cancelText:m("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(ce.id),de(null)},onCancel:()=>de(null)})]})}function ast(){const{t}=wt(),e=aa(),{showToast:a}=sa(),{hasPermission:n}=lr(),[i,s]=y.useState("status"),{data:o,isLoading:l}=Qe({queryKey:["maintenanceOverview"],queryFn:re.getMaintenanceOverview}),{data:c}=Qe({queryKey:["maintenanceTypes"],queryFn:re.getMaintenanceTypes}),d=lt({mutationFn:({id:T,notes:j})=>re.performMaintenance(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.maintenanceComplete"))},onError:T=>{a(T.message,"error")}}),u=lt({mutationFn:({id:T,data:j})=>re.updateMaintenanceItem(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{a(T.message,"error")}}),m=lt({mutationFn:({id:T,data:j})=>re.updateMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onError:T=>{a(T.message,"error")}}),p=lt({mutationFn:re.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeDeleted"))},onError:T=>{a(T.message,"error")}}),f=lt({mutationFn:re.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{a(T.message,"error")}}),g=lt({mutationFn:({printerId:T,hours:j})=>re.setPrinterHours(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),a(t("maintenance.printHoursUpdated"))},onError:T=>{a(T.message,"error")}}),v=lt({mutationFn:({printerId:T,typeId:j})=>re.assignMaintenanceType(T,j),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerAssigned"))},onError:T=>{a(T.message,"error")}}),b=lt({mutationFn:re.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.printerRemoved"))},onError:T=>{a(T.message,"error")}}),x=T=>{d.mutate({id:T})},S=(T,j)=>{u.mutate({id:T,data:{enabled:j}})},k=(T,j)=>{g.mutate({printerId:T,hours:j})};if(l)return r.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})});const N=o?.reduce((T,j)=>T+j.due_count,0)||0,C=o?.reduce((T,j)=>T+j.warning_count,0)||0;return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"mb-6",children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Qm,{className:"w-7 h-7 text-bambu-green"}),t("maintenance.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:i==="status"?r.jsxs(r.Fragment,{children:[N>0&&r.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:N})}),N>0&&C>0&&" · ",C>0&&r.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:C})}),N===0&&C===0&&r.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),r.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[r.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),r.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${i==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),i==="status"?r.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((T,j)=>{const F=T.due_count*10+T.warning_count,P=j.due_count*10+j.warning_count;return F!==P?P-F:T.printer_name.localeCompare(j.printer_name)}).map(T=>r.jsx(est,{overview:T,onPerform:x,onToggle:S,onSetHours:k,hasPermission:n,t},T.printer_id)):r.jsx(At,{children:r.jsxs(Mt,{className:"text-center py-16",children:[r.jsx(Qm,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),r.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),r.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):r.jsx(tst,{overview:o,types:c||[],onUpdateInterval:(T,j)=>u.mutate({id:T,data:j}),onAddType:async(T,j)=>{const F=await re.createMaintenanceType(T);for(const P of j)await re.assignMaintenanceType(P,F.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),a(t("maintenance.typeUpdated"))},onUpdateType:(T,j)=>m.mutate({id:T,data:j}),onDeleteType:T=>p.mutate(T),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(T,j)=>v.mutate({printerId:T,typeId:j}),onRemoveItem:T=>b.mutate(T),hasPermission:n,t})]})}const DX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function pde({project:t,onClose:e,onSave:a,isLoading:n,currencySymbol:i,t:s}){const[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.description||""),[u,m]=y.useState(t?.color||DX[0]),[p,f]=y.useState(t?.target_count?.toString()||""),[g,v]=y.useState(t?.target_parts_count?.toString()||""),[b,x]=y.useState(t?.status||"active"),[S,k]=y.useState(t?.tags||""),[N,C]=y.useState(t?.due_date?.split("T")[0]||""),[T,j]=y.useState(t?.priority||"normal"),[F,P]=y.useState(t?.budget?.toString()||""),[D,R]=y.useState(t?.url||""),[B,O]=y.useState(null),L=aa(),[Y,ee]=y.useState(t?.cover_image_filename||null),Z=y.useRef(null),[ce,de]=y.useState(!1),[ue,Q]=y.useState(0),ne=async be=>{const q=be.target.files?.[0];if(!(!q||!t)){de(!0);try{const J=await re.uploadProjectCoverImage(t.id,q);ee(J.filename),Q(A=>A+1),L.invalidateQueries({queryKey:["projects"]})}catch{}finally{de(!1),Z.current&&(Z.current.value="")}}},pe=async()=>{if(t){de(!0);try{await re.deleteProjectCoverImage(t.id),ee(null),Q(be=>be+1),L.invalidateQueries({queryKey:["projects"]})}finally{de(!1)}}},me=be=>{be.preventDefault();const q=D.trim();if(q&&!/^https?:\/\//i.test(q)){O(s("projects.urlInvalid"));return}O(null),a({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:g?parseInt(g,10):void 0,tags:S.trim()||void 0,due_date:N||void 0,priority:T,budget:F.trim()?parseFloat(F):null,url:t?q||null:q||void 0,...t&&{status:b}})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),r.jsxs("form",{onSubmit:me,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsx("input",{type:"text",value:o,onChange:be=>l(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.namePlaceholder"),required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),r.jsx("textarea",{value:c,onChange:be=>d(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:s("projects.descriptionPlaceholder"),rows:2})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.urlLabel")}),r.jsx("input",{type:"url",value:D,onChange:be=>{R(be.target.value),B&&O(null)},className:`w-full bg-bambu-dark border rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none ${B?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,placeholder:s("projects.urlPlaceholder"),maxLength:2048}),B&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:B})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.coverImageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-20 h-20 rounded bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden flex items-center justify-center flex-shrink-0",children:Y?r.jsx("img",{src:`${re.getProjectCoverImageUrl(t.id)}?v=${ue}`,alt:s("projects.coverImageAlt"),className:"w-full h-full object-cover"}):r.jsx(pu,{className:"w-6 h-6 text-bambu-gray"})}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("input",{ref:Z,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",onChange:ne,className:"hidden"}),r.jsxs(De,{type:"button",variant:"secondary",onClick:()=>Z.current?.click(),disabled:ce,children:[ce?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(kn,{className:"w-4 h-4 mr-1"}),s(Y?"projects.coverImageReplace":"projects.coverImageUpload")]}),Y&&r.jsxs(De,{type:"button",variant:"secondary",onClick:pe,disabled:ce,children:[r.jsx(Gt,{className:"w-4 h-4 mr-1"}),s("projects.coverImageRemove")]})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:DX.map(be=>r.jsx("button",{type:"button",onClick:()=>m(be),className:`w-8 h-8 rounded-full transition-transform ${u===be?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:be}},be))})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),r.jsx("input",{type:"number",value:p,onChange:be=>f(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPlatesPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),r.jsx("input",{type:"number",value:g,onChange:be=>v(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.targetPartsPlaceholder"),min:"1"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),r.jsx("input",{type:"text",value:S,onChange:be=>k(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:s("projects.tagsPlaceholder")})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),r.jsx("input",{type:"date",value:N,onChange:be=>C(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),r.jsxs("select",{value:T,onChange:be=>j(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"low",children:s("projects.priorityLow")}),r.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),r.jsx("option",{value:"high",children:s("projects.priorityHigh")}),r.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),r.jsxs("div",{className:"relative",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),r.jsx("input",{type:"number",step:"0.01",min:"0",value:F,onChange:be=>P(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded pl-8 pr-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"0.00"})]})]}),t&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),r.jsxs("select",{value:b,onChange:be=>x(be.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"active",children:s("projects.statusActive")}),r.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),r.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),r.jsx(De,{type:"submit",disabled:!o.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function rst({projectId:t,altText:e}){const a=y.useRef(null),[n,i]=y.useState(!1),[s,o]=y.useState(null),l=()=>{if(!a.current)return;const d=a.current.getBoundingClientRect(),u=384,m=8,p=window.innerWidth,f=window.innerHeight;let g=d.right+m;g+u>p-8&&(g=d.left-u-m);let v=d.top;v+u>f-8&&(v=f-u-8),v<8&&(v=8),o({left:g,top:v}),i(!0)},c=()=>i(!1);return r.jsxs("div",{ref:a,className:"relative flex-shrink-0",onMouseEnter:l,onMouseLeave:c,onClick:d=>d.stopPropagation(),children:[r.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden bg-bambu-dark border border-bambu-dark-tertiary",children:r.jsx("img",{src:re.getProjectCoverImageUrl(t),alt:e,className:"w-full h-full object-cover",loading:"lazy"})}),n&&s&&fc.createPortal(r.jsx("div",{className:"fixed z-[100] w-96 h-96 rounded-lg overflow-hidden border border-bambu-dark-tertiary shadow-2xl bg-bambu-dark pointer-events-none",style:{left:s.left,top:s.top},"aria-hidden":"true",children:r.jsx("img",{src:re.getProjectCoverImageUrl(t),alt:"",className:"w-full h-full object-contain",loading:"lazy"})}),document.body)]})}function nst({project:t,onClick:e,onEdit:a,onDelete:n,hasPermission:i,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",d=t.status==="archived",[u,m]=y.useState(!1),f=c?{icon:eo,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:ao,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:er,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:ro,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return r.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[r.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),r.jsxs("div",{className:"p-5 pl-6",children:[r.jsxs("div",{className:"flex items-start justify-between mb-4",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[t.cover_image_filename?r.jsx(rst,{projectId:t.id,altText:s("projects.coverImageAlt")}):r.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:r.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.url&&r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",onClick:g=>g.stopPropagation(),title:t.url,"aria-label":s("projects.openExternalUrl"),className:"inline-flex items-center justify-center w-6 h-6 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-green hover:bg-bambu-green/10 hover:border-bambu-green transition-colors flex-shrink-0",children:r.jsx(Dr,{className:"w-3.5 h-3.5"})}),t.target_parts_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?r.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&r.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),d&&r.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&r.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const g=t.archives.map(S=>S.filament_type).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(g)],b=t.archives.map(S=>S.filament_color).filter(Boolean).flatMap(S=>S.split(",").map(k=>k.trim())).filter(S=>S.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(S)),x=[...new Set(b)];return v.length===0&&x.length===0?null:r.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(S=>r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:S},S)),x.length>0&&r.jsxs("div",{className:"flex items-center gap-0.5",children:[x.slice(0,5).map(S=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:S.startsWith("#")?S:`#${S}`},title:S},S)),x.length>5&&r.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",x.length-5]})]})]})})()]})]}),r.jsxs("div",{className:"relative",onClick:g=>g.stopPropagation(),children:[r.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>m(!u),children:r.jsx(km,{className:"w-4 h-4"})}),u&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),r.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:update")&&(a(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4"}),s("common.edit")]}),r.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${i("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{i("projects:delete")&&(n(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[r.jsx(ta,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),r.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?r.jsxs("div",{className:"space-y-3",children:[t.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),r.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[r.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),r.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),r.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:r.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&r.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?r.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[r.jsx(ao,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[r.jsx(ga,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[r.jsx(er,{className:"w-3.5 h-3.5"}),r.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):r.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(g=>r.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:g.print_name||"Unknown",children:[g.thumbnail_path?r.jsx("img",{src:re.getArchiveThumbnail(g.id),alt:g.print_name||"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:r.jsx(qr,{className:"w-6 h-6"})}),g.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:r.jsx(ga,{className:"w-4 h-4 text-white"})})]},g.id))}),t.archive_count>4&&r.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),r.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[r.jsx(cn,{className:"w-3.5 h-3.5 text-blue-400"}),r.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),r.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[r.jsx(qr,{className:"w-3.5 h-3.5 text-bambu-green"}),r.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[r.jsx(ga,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&r.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[r.jsx(n3,{className:"w-3.5 h-3.5"}),r.jsx("span",{children:t.queue_count})]})]}),r.jsx(qn,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function ist(){const{t}=wt(),e=Ri(),a=aa(),{showToast:n}=sa(),{hasPermission:i}=lr(),[s,o]=y.useState(!1),[l,c]=y.useState(),[d,u]=y.useState("active"),[m,p]=y.useState(null),{data:f}=Qe({queryKey:["settings"],queryFn:re.getSettings}),g=Ho(f?.currency||"USD"),{data:v,isLoading:b}=Qe({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>re.getProjects(d==="all"?void 0:d)}),x=lt({mutationFn:Y=>re.createProject(Y),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),n(t("projects.toast.created"),"success")},onError:Y=>{n(Y.message,"error")}}),S=lt({mutationFn:({id:Y,data:ee})=>re.updateProject(Y,ee),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),n(t("projects.toast.updated"),"success")},onError:Y=>{n(Y.message,"error")}}),k=lt({mutationFn:Y=>re.deleteProject(Y),onSuccess:()=>{p(null),n(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:Y=>{p(null),n(Y.message,"error")}}),N=lt({mutationFn:Y=>re.importProject(Y),onSuccess:()=>{a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success")},onError:Y=>{n(Y.message,"error")}}),C=y.useRef(null),T=async()=>{try{const Y=await re.getProjects(),ee=await Promise.all(Y.map(async ue=>await re.exportProjectJson(ue.id))),Z=new Blob([JSON.stringify(ee,null,2)],{type:"application/json"}),ce=URL.createObjectURL(Z),de=document.createElement("a");de.href=ce,de.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,de.click(),URL.revokeObjectURL(ce),n(t("projects.toast.exported"),"success")}catch(Y){n(Y.message,"error")}},j=()=>{C.current?.click()},F=async Y=>{const ee=Y.target.files?.[0];if(ee){try{if(ee.name.toLowerCase().endsWith(".zip"))await re.importProjectFile(ee),a.invalidateQueries({queryKey:["projects"]}),n(t("projects.toast.imported"),"success");else{const ce=await ee.text(),de=JSON.parse(ce),ue=Array.isArray(de)?de:[de];for(const Q of ue)await N.mutateAsync(Q);ue.length>1&&n(t("projects.toast.multipleImported",{count:ue.length}),"success")}}catch(Z){n(`${t("projects.toast.importFailed")}: ${Z.message}`,"error")}Y.target.value=""}},P=Y=>{l?S.mutate({id:l.id,data:Y}):x.mutate(Y)},D=Y=>{c(Y),o(!0)},R=Y=>{e(`/projects/${Y.id}`)},B=Y=>{p(Y)},O=()=>{m!==null&&k.mutate(m)},L=v?.reduce((Y,ee)=>(Y[ee.status]=(Y[ee.status]||0)+1,Y.all=(Y.all||0)+1,Y),{})||{};return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsx("input",{ref:C,type:"file",accept:".json,.zip",onChange:F,className:"hidden"}),r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(ro,{className:"w-7 h-7 text-bambu-green"}),t("projects.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("projects.subtitle")})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(De,{variant:"secondary",onClick:j,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[r.jsx(kn,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),r.jsxs(De,{variant:"secondary",onClick:T,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),r.jsxs(De,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),r.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:er},{key:"completed",label:t("projects.statusCompleted"),icon:eo},{key:"archived",label:t("projects.statusArchived"),icon:ao},{key:"all",label:t("common.all"),icon:ro}].map(({key:Y,label:ee,icon:Z})=>r.jsxs("button",{onClick:()=>u(Y),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===Y?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Z,{className:"w-4 h-4"}),r.jsx("span",{children:ee}),L[Y]>0&&r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===Y?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[Y]})]},Y))}),b?r.jsx("div",{className:"flex items-center justify-center py-20",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(ro,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:d==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:d})}),d==="all"&&r.jsxs(De,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(Y=>r.jsx(nst,{project:Y,onClick:()=>R(Y),onEdit:()=>D(Y),onDelete:()=>B(Y.id),hasPermission:i,t},Y.id))}),m!==null&&r.jsx(ya,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:O,onCancel:()=>p(null)}),s&&r.jsx(pde,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:P,isLoading:x.isPending||S.isPending,currencySymbol:g,t})]})}function sst(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function ost(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function lst({status:t,t:e}){const a={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},n=a[t]||a.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return r.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${n}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function FX({icon:t,label:e,value:a,subValue:n,hint:i,color:s="text-bambu-gray"}){return r.jsx(At,{children:r.jsx(Mt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",title:i,children:[r.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:r.jsx(t,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:e}),r.jsx("p",{className:"text-xl font-semibold text-white",children:a}),n&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:n})]})]})})})}function cst({archives:t,t:e}){return t.length===0?r.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[r.jsx(qr,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),r.jsx("p",{children:e("projectDetail.noPrints")})]}):r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(a=>r.jsxs(Ds,{to:`/archives?search=${encodeURIComponent(a.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[a.thumbnail_path?r.jsx("img",{src:re.getArchiveThumbnail(a.id),alt:a.print_name||"Print",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:r.jsx(qr,{className:"w-8 h-8"})}),a.status==="failed"&&r.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:r.jsx(Er,{className:"w-8 h-8 text-white"})}),a.status==="completed"&&r.jsx("div",{className:"absolute top-1 right-1",children:r.jsx(gr,{className:"w-4 h-4 text-bambu-green"})}),r.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx("p",{className:"text-xs text-white truncate",children:a.print_name||"Unknown"})})]},a.id))})}function dst({priority:t,t:e}){const a={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:n,label:i}=a[t]||a.normal;return r.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${n}`,children:[t==="urgent"&&r.jsx(ga,{className:"w-3 h-3"}),i]})}function TL(t,e){if(!t)return null;const a=Ia(t);if(!a)return null;const n=new Date,i=Math.ceil((a.getTime()-n.getTime())/(1e3*60*60*24));return i<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:i===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:i<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:i})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:i})}}function ust(){const{id:t}=AS(),e=Ri(),{t:a}=wt(),n=aa(),{showToast:i}=sa(),{hasPermission:s}=lr(),[o,l]=y.useState(!1),[c,d]=y.useState(!1),[u,m]=y.useState(""),[p,f]=y.useState(null),[g,v]=y.useState(null),b=parseInt(t||"0",10),{data:x,isLoading:S,error:k}=Qe({queryKey:["project",b],queryFn:()=>re.getProject(b),enabled:b>0}),{data:N,isLoading:C}=Qe({queryKey:["project-archives",b],queryFn:()=>re.getProjectArchives(b),enabled:b>0}),{data:T,isLoading:j}=Qe({queryKey:["project-bom",b],queryFn:()=>re.getProjectBOM(b),enabled:b>0}),{data:F,isLoading:P}=Qe({queryKey:["project-timeline",b],queryFn:()=>re.getProjectTimeline(b,20),enabled:b>0}),{data:D}=Qe({queryKey:["settings"],queryFn:re.getSettings}),{data:R}=Qe({queryKey:["project-folders",b],queryFn:()=>re.getLibraryFoldersByProject(b),enabled:b>0}),{data:B,isLoading:O}=Qe({queryKey:["project-files",b],queryFn:()=>re.getLibraryFiles(null,!1,b),enabled:b>0}),L=y.useMemo(()=>{const Ne=new Map;for(const Ie of B??[])if(Ie.folder_id!=null){const et=Ne.get(Ie.folder_id)??[];et.push(Ie),Ne.set(Ie.folder_id,et)}return Ne},[B]),Y=Ho(D?.currency||"USD"),ee=D?.time_format||"system",Z=lt({mutationFn:Ne=>re.updateProject(b,Ne),onSuccess:()=>{n.invalidateQueries({queryKey:["project",b]}),n.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(a("projectDetail.toast.projectUpdated"),"success")},onError:Ne=>{i(Ne.message,"error")}}),ce=()=>{m(x?.notes||""),d(!0)},de=()=>{Z.mutate({notes:u})},ue=()=>{d(!1),m("")},[Q,ne]=y.useState(""),[pe,me]=y.useState(1),[be,q]=y.useState(""),[J,A]=y.useState(""),[M,H]=y.useState(""),[W,U]=y.useState(!1),[se,I]=y.useState(!1),[G,K]=y.useState(null),[X,ie]=y.useState(""),[oe,he]=y.useState(1),[le,fe]=y.useState(""),[$,z]=y.useState(""),[ae,ge]=y.useState(""),[xe,ve]=y.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),je=lt({mutationFn:Ne=>re.createBOMItem(b,Ne),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),ne(""),me(1),q(""),A(""),H(""),U(!1),i(a("projectDetail.toast.partAdded"),"success")},onError:Ne=>i(Ne.message,"error")}),Me=lt({mutationFn:({itemId:Ne,data:Ie})=>re.updateBOMItem(b,Ne,Ie),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),K(null)},onError:Ne=>i(Ne.message,"error")}),Se=lt({mutationFn:Ne=>re.deleteBOMItem(b,Ne),onSuccess:()=>{n.invalidateQueries({queryKey:["project-bom",b]}),n.invalidateQueries({queryKey:["project",b]}),i(a("projectDetail.toast.partRemoved"),"success")},onError:Ne=>i(Ne.message,"error")}),Ue=Ne=>{Ne.preventDefault(),Q.trim()&&je.mutate({name:Q.trim(),quantity_needed:pe,unit_price:be?parseFloat(be):void 0,sourcing_url:J.trim()||void 0,remarks:M.trim()||void 0})},_e=Ne=>{const Ie=Ne.is_complete?0:Ne.quantity_needed;Me.mutate({itemId:Ne.id,data:{quantity_acquired:Ie}})},ze=(Ne,Ie)=>{ve({isOpen:!0,title:a("projectDetail.bom.deletePart"),message:a("projectDetail.bom.deleteConfirm",{name:Ie}),onConfirm:()=>{ve(et=>({...et,isOpen:!1})),Se.mutate(Ne)}})},Fe=Ne=>{K(Ne),ie(Ne.name),he(Ne.quantity_needed),fe(Ne.unit_price?.toString()||""),z(Ne.sourcing_url||""),ge(Ne.remarks||"")},qe=Ne=>{Ne.preventDefault(),!(!G||!X.trim())&&Me.mutate({itemId:G.id,data:{name:X.trim(),quantity_needed:oe,unit_price:le?parseFloat(le):void 0,sourcing_url:$.trim()||void 0,remarks:ae.trim()||void 0}})},Oe=()=>{K(null)},it=async()=>{try{const{blob:Ne,filename:Ie}=await re.exportProjectZip(Number(b)),et=URL.createObjectURL(Ne),We=document.createElement("a");We.href=et,We.download=Ie||`${x?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,We.click(),URL.revokeObjectURL(et),i(a("projectDetail.toast.projectExported"),"success")}catch(Ne){i(Ne.message,"error")}},Le=lt({mutationFn:()=>re.createTemplateFromProject(b),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),i(a("projectDetail.toast.templateCreated"),"success")},onError:Ne=>i(Ne.message,"error")}),st=Ne=>Bg(Ne,ee,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(S)return r.jsx("div",{className:"flex items-center justify-center py-24",children:r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(k||!x)return r.jsxs("div",{className:"text-center py-24",children:[r.jsx("p",{className:"text-bambu-gray",children:k?`${a("common.error")}: ${k.message}`:a("projectDetail.notFound")}),r.jsx(De,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:a("projectDetail.backToProjects")})]});const Te=x.stats,Xe=Te?.progress_percent??0,$e=Te?.parts_progress_percent??0;return r.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[r.jsx(Ds,{to:"/projects",className:"hover:text-white transition-colors",children:a("nav.projects")}),r.jsx(qn,{className:"w-4 h-4"}),r.jsx("span",{className:"text-white",children:x.name})]}),r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:r.jsx(CT,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-4 h-4 rounded-full shrink-0",style:{backgroundColor:x.color||"#6b7280"}}),r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-white",children:x.name}),x.description&&r.jsx("p",{className:"text-bambu-gray mt-1",children:x.description})]})]}),r.jsx(lst,{status:x.status,t:a})]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(De,{variant:"secondary",onClick:it,disabled:!s("projects:read"),title:s("projects:read")?a("projectDetail.exportProject"):a("projectDetail.noExportPermission"),children:[r.jsx(Ur,{className:"w-4 h-4 mr-2"}),a("projectDetail.export")]}),r.jsxs(De,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-2"}),a("common.edit")]})]})]}),(x.target_count||x.target_parts_count)&&r.jsx(At,{children:r.jsxs(Mt,{className:"p-4 space-y-4",children:[x.target_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.platesProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Te?.total_archives||0," / ",x.target_count," ",a("projectDetail.progress.printJobs")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Xe,100)}%`,backgroundColor:Xe>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:Xe.toFixed(0)})}),Te?.remaining_prints!=null&&Te.remaining_prints>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Te.remaining_prints})})]})]}),x.target_parts_count&&r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:a("projectDetail.progress.partsProgress")}),r.jsxs("span",{className:"text-sm font-medium text-white",children:[Te?.completed_prints||0," / ",x.target_parts_count," ",a("projectDetail.progress.parts")]})]}),r.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:r.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min($e,100)}%`,backgroundColor:$e>=100?"#22c55e":x.color||"#6b7280"}})}),r.jsxs("div",{className:"flex justify-between mt-1",children:[r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.percentComplete",{percent:$e.toFixed(0)})}),Te?.remaining_parts!=null&&Te.remaining_parts>0&&r.jsx("span",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.progress.remaining",{count:Te.remaining_parts})})]})]})]})}),Te&&r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsx(At,{children:r.jsx(Mt,{className:"p-4",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:r.jsx(qr,{className:"w-5 h-5"})}),r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.printJobs")}),r.jsxs("p",{className:"text-xl font-semibold text-white",children:[Te.total_archives," ",r.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:a("projectDetail.stats.total")})]}),Te.failed_prints>0&&r.jsx("p",{className:"text-sm text-status-error",children:a("projectDetail.stats.failed",{count:Te.failed_prints})}),r.jsx("p",{className:"text-sm text-bambu-gray",children:a("projectDetail.stats.partsPrinted",{count:Te.completed_prints})})]})]})})}),r.jsx(FX,{icon:er,label:a("projectDetail.stats.printTime"),value:C0e(Te.total_print_time_hours),color:"text-yellow-400"}),r.jsx(FX,{icon:xr,label:a("projectDetail.stats.filamentUsed"),value:ost(Te.total_filament_grams),color:"text-purple-400"})]}),Te&&(()=>{const Ne=Te.estimated_cost+Te.total_energy_cost+Te.bom_cost;return Te.estimated_cost>0||Ne>0||x.budget!==null})()&&r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:a("projectDetail.cost.title")}),r.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.filamentCost")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Y,Te.estimated_cost.toFixed(2)]})]}),Te.total_energy_kwh>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.energy")}),r.jsxs("p",{className:"text-lg font-semibold text-white",children:[Te.total_energy_kwh.toFixed(3)," kWh",Te.total_energy_cost>0&&r.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",Y,Te.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Ne=Te.estimated_cost+Te.total_energy_cost+Te.bom_cost;return Ne<=0?null:r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.totalCost")}),r.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[Y,Ne.toFixed(2)]}),Te.bom_cost>0&&r.jsx("p",{className:"text-xs text-bambu-gray/70",children:a("projectDetail.cost.includesBom")})]})})(),x.budget!==null&&(()=>{const Ne=Te.estimated_cost+Te.total_energy_cost+Te.bom_cost,Ie=x.budget-Ne;return r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.cost.budget")}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:[a("projectDetail.cost.total"),": ",r.jsxs("span",{className:"text-white font-semibold",children:[Y,x.budget.toFixed(2)]})]}),r.jsxs("p",{className:`text-sm ${Ie>=0?"text-bambu-green":"text-red-400"}`,children:[a("projectDetail.cost.remaining"),": ",r.jsxs("span",{className:"font-semibold",children:[Y,Ie.toFixed(2)]})]})]})})()]})]})}),x.children&&x.children.length>0&&r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[r.jsx(Jbe,{className:"w-5 h-5"}),a("projectDetail.subProjects.title",{count:x.children.length})]}),r.jsx("div",{className:"space-y-2",children:x.children.map(Ne=>r.jsxs(Ds,{to:`/projects/${Ne.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Ne.color||"#6b7280"}}),r.jsx("span",{className:"text-white",children:Ne.name}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Ne.status==="completed"?"bg-status-ok/20 text-status-ok":Ne.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Ne.status})]}),Ne.progress_percent!==null&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Ne.progress_percent.toFixed(0),"%"]})]},Ne.id))})]})}),x.parent_id&&x.parent_name&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(cn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.partOf")}),r.jsx(Ds,{to:`/projects/${x.parent_id}`,className:"text-bambu-green hover:underline",children:x.parent_name})]}),(x.tags||x.due_date||x.priority!=="normal")&&r.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[x.priority&&x.priority!=="normal"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:a("projectDetail.priorityLabel")}),r.jsx(dst,{priority:x.priority,t:a})]}),x.due_date&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(wn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"text-sm text-white",children:Og(x.due_date,{year:"numeric",month:"short",day:"numeric"})}),TL(x.due_date,a)&&r.jsxs("span",{className:`text-xs ${TL(x.due_date,a).color}`,children:["(",TL(x.due_date,a).label,")"]})]}),x.tags&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Km,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:x.tags.split(",").map((Ne,Ie)=>r.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Ne.trim()},Ie))})]})]}),r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(zs,{className:"w-5 h-5"}),a("projectDetail.notes.title")]}),c?r.jsxs("div",{className:"flex gap-2",children:[r.jsxs(De,{variant:"secondary",size:"sm",onClick:ue,disabled:Z.isPending,children:[r.jsx(Gt,{className:"w-4 h-4 mr-1"}),a("common.cancel")]}),r.jsxs(De,{size:"sm",onClick:de,disabled:Z.isPending,children:[Z.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}):r.jsx(cs,{className:"w-4 h-4 mr-1"}),a("common.save")]})]}):r.jsxs(De,{variant:"secondary",size:"sm",onClick:ce,disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.notes.noEditPermission"),children:[r.jsx(Rg,{className:"w-4 h-4 mr-1"}),a("common.edit")]})]}),c?r.jsx(tI,{content:u,onChange:m,placeholder:a("projectDetail.notes.placeholder")}):x.notes?r.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:CB.sanitize(x.notes)}}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.notes.empty")})]})}),r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Tl,{className:"w-5 h-5"}),a("projectDetail.files.title")]})}),r.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[r.jsx(Ds,{to:"/files",className:"text-bambu-green hover:underline",children:a("projectDetail.files.linkFolders")})," ",a("projectDetail.files.forQuickAccess")]}),R&&R.length>0?r.jsx("div",{className:"space-y-4",children:R.map(Ne=>{const Ie=L.get(Ne.id)??[],et=O;return r.jsxs("div",{children:[r.jsxs(Ds,{to:`/files?folder=${Ne.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors mb-2",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx(Tl,{className:"w-5 h-5 text-bambu-green shrink-0"}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:Ne.name}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("projectDetail.files.fileCount",{count:Ne.file_count})})]})]}),r.jsx(qn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),et?r.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-bambu-gray text-sm",children:r.jsx(pt,{className:"w-4 h-4 animate-spin"})}):Ie.length===0?r.jsx("p",{className:"text-bambu-gray/60 text-xs italic px-3",children:a("projectDetail.files.noFiles")}):r.jsx("div",{className:"space-y-1 pl-3",children:Ie.map(We=>{const Ae=sst(We.filename);return r.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsx("div",{className:"w-10 h-10 shrink-0 rounded bg-bambu-dark overflow-hidden flex items-center justify-center",children:We.thumbnail_path?r.jsx("img",{src:re.getLibraryFileThumbnailUrl(We.id),alt:We.print_name||We.filename,className:"w-full h-full object-cover"}):r.jsx(Mh,{className:"w-5 h-5 text-bambu-gray/40"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",title:We.print_name||We.filename,children:We.print_name||We.filename}),r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${We.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":We.file_type==="gcode"?"bg-blue-500/20 text-blue-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:We.file_type.toUpperCase()})]}),Ae&&r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>f(We),title:a("projectDetail.files.print"),className:"p-1.5 rounded hover:bg-bambu-green/20 text-bambu-green transition-colors",children:r.jsx(ps,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>v(We),title:a("projectDetail.files.addToQueue"),className:"p-1.5 rounded hover:bg-blue-500/20 text-blue-400 transition-colors",children:r.jsx(wge,{className:"w-4 h-4"})})]})]},We.id)})})]},Ne.id)})}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.files.empty")})]})}),r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(mb,{className:"w-5 h-5"}),a("projectDetail.bom.title"),Te&&Te.bom_total_items>0&&r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",a("projectDetail.bom.acquired",{completed:Te.bom_completed_items,total:Te.bom_total_items}),")"]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[T&&T.some(Ne=>Ne.is_complete)&&r.jsx("button",{onClick:()=>I(!se),className:`text-xs px-2 py-1 rounded transition-colors ${se?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a(se?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!W&&r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>U(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noAddPermission"),children:[r.jsx(ar,{className:"w-4 h-4 mr-1"}),a("projectDetail.bom.addPart")]})]})]}),W&&r.jsxs("form",{onSubmit:Ue,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:Q,onChange:Ne=>ne(Ne.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:pe,onChange:Ne=>me(parseInt(Ne.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:be,onChange:Ne=>q(Ne.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:Y})})]})]}),r.jsx("input",{type:"url",value:J,onChange:Ne=>A(Ne.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:M,onChange:Ne=>H(Ne.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:()=>U(!1),children:a("common.cancel")}),r.jsx(De,{type:"submit",size:"sm",disabled:!Q.trim()||je.isPending,children:je.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("projectDetail.bom.addPart")})]})]}),j?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):T&&T.length>0?r.jsxs("div",{className:"space-y-2",children:[T.filter(Ne=>!se||!Ne.is_complete).map(Ne=>r.jsx("div",{className:`p-3 rounded-lg transition-colors ${Ne.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:G?.id===Ne.id?r.jsxs("form",{onSubmit:qe,className:"space-y-3",children:[r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[r.jsx("input",{type:"text",value:X,onChange:Ie=>ie(Ie.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.partName"),autoFocus:!0}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{type:"number",value:oe,onChange:Ie=>he(parseInt(Ie.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:a("projectDetail.bom.qty")}),r.jsx("input",{type:"number",step:"0.01",value:le,onChange:Ie=>fe(Ie.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.price",{currency:Y})})]})]}),r.jsx("input",{type:"url",value:$,onChange:Ie=>z(Ie.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.sourcingUrlPlaceholder")}),r.jsx("input",{type:"text",value:ae,onChange:Ie=>ge(Ie.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projectDetail.bom.remarksPlaceholder")}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx(De,{type:"button",variant:"secondary",size:"sm",onClick:Oe,children:a("common.cancel")}),r.jsx(De,{type:"submit",size:"sm",disabled:!X.trim()||Me.isPending,children:Me.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]})]}):r.jsxs("div",{className:"flex items-start gap-3",children:[r.jsx("button",{onClick:()=>s("projects:update")&&_e(Ne),disabled:Me.isPending||!s("projects:update"),title:s("projects:update")?void 0:a("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors shrink-0 ${Ne.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:Ne.is_complete&&r.jsx(gr,{className:"w-3 h-3"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsxs("p",{className:`text-sm font-medium ${Ne.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Ne.name,r.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Ne.quantity_needed]})]}),Ne.unit_price!==null&&r.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[Y,(Ne.unit_price*Ne.quantity_needed).toFixed(2)]})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>s("projects:update")&&Fe(Ne),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.edit"):a("projectDetail.bom.noEditPermission"),children:r.jsx(xi,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("projects:update")&&ze(Ne.id,Ne.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?a("common.delete"):a("projectDetail.bom.noDeletePermission"),children:r.jsx(ta,{className:"w-4 h-4"})})]})]}),Ne.sourcing_url&&r.jsxs("a",{href:Ne.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:Ie=>Ie.stopPropagation(),children:[r.jsx(Dr,{className:"w-3 h-3 shrink-0"}),r.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Ne.sourcing_url).hostname.replace("www.","")}catch{return Ne.sourcing_url}})()})]}),Ne.remarks&&r.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Ne.remarks})]})]})},Ne.id)),Te&&Te.bom_cost>0&&r.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.bom.totalCost")}),r.jsxs("span",{className:"text-white font-medium",children:[Y,Te.bom_cost.toFixed(2)]})]})]}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.bom.empty")})]})}),r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsx("div",{className:"flex items-center justify-between mb-3",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Yh,{className:"w-5 h-5"}),a("projectDetail.timeline.title")]})}),P?r.jsx("div",{className:"flex items-center justify-center py-4",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):F&&F.length>0?r.jsx("div",{className:"space-y-3",children:F.slice(0,10).map((Ne,Ie)=>r.jsxs("div",{className:"flex gap-3",children:[r.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${Ne.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Ne.event_type==="print_failed"?"bg-status-error/20 text-status-error":Ne.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Ne.event_type==="print_completed"&&r.jsx(gr,{className:"w-4 h-4"}),Ne.event_type==="print_failed"&&r.jsx(Er,{className:"w-4 h-4"}),Ne.event_type==="print_started"&&r.jsx(xr,{className:"w-4 h-4"}),Ne.event_type==="queued"&&r.jsx(n3,{className:"w-4 h-4"}),Ne.event_type==="project_created"&&r.jsx(ar,{className:"w-4 h-4"})]}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white",children:Ne.title}),Ne.description&&r.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Ne.description}),r.jsx("p",{className:"text-xs text-bambu-gray/70",children:st(Ne.timestamp)})]})]},Ie))}):r.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:a("projectDetail.timeline.empty")})]})}),!x.is_template&&r.jsx("div",{className:"flex justify-end",children:r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>Le.mutate(),disabled:Le.isPending||!s("projects:create"),title:s("projects:create")?void 0:a("projectDetail.template.noCreatePermission"),children:[Le.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):r.jsx(bi,{className:"w-4 h-4 mr-2"}),a("projectDetail.template.saveAsTemplate")]})}),Te&&(Te.queued_prints>0||Te.in_progress_prints>0)&&r.jsx(At,{children:r.jsxs(Mt,{className:"p-4",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(n3,{className:"w-5 h-5"}),a("projectDetail.queue.title")]}),r.jsx(Ds,{to:`/queue?project=${b}`,className:"text-sm text-bambu-green hover:underline",children:a("projectDetail.queue.viewAll")})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Te.in_progress_prints>0&&r.jsx("span",{className:"text-yellow-400",children:a("projectDetail.queue.printing",{count:Te.in_progress_prints})}),Te.queued_prints>0&&r.jsx("span",{className:"text-bambu-gray",children:a("projectDetail.queue.queued",{count:Te.queued_prints})})]})]})}),r.jsxs("div",{children:[r.jsx("div",{className:"flex items-center justify-between mb-4",children:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(qr,{className:"w-5 h-5"}),a("projectDetail.prints.title",{count:N?.length||0})]})}),C?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})}):r.jsx(cst,{archives:N||[],t:a})]}),o&&r.jsx(pde,{t:a,currencySymbol:Y,project:{...x,archive_count:Te?.total_archives||0,total_items:Te?.total_items||0,completed_count:Te?.completed_prints||0,failed_count:Te?.failed_prints||0,queue_count:Te?.queued_prints||0,progress_percent:Te?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Ne=>Z.mutate(Ne),isLoading:Z.isPending}),xe.isOpen&&r.jsx(ya,{title:xe.title,message:xe.message,confirmText:a("common.delete"),variant:"danger",onConfirm:xe.onConfirm,onCancel:()=>ve(Ne=>({...Ne,isOpen:!1}))}),p&&r.jsx(kc,{mode:"reprint",libraryFileId:p.id,archiveName:p.print_name||p.filename,projectId:b,onClose:()=>f(null),onSuccess:()=>{f(null),n.invalidateQueries({queryKey:["archives"]})}}),g&&r.jsx(kc,{mode:"add-to-queue",libraryFileId:g.id,archiveName:g.print_name||g.filename,projectId:b,onClose:()=>v(null),onSuccess:()=>{v(null),n.invalidateQueries({queryKey:["queue"]})}})]})}function mst({archiveId:t,libraryFileId:e,title:a,fileType:n,onClose:i,onSliceWithBambuddy:s}){const{t:o}=wt(),{data:l}=Qe({queryKey:["settings"],queryFn:re.getSettings}),c=l?.preferred_slicer||"bambu_studio",d=e!=null,[u,m]=y.useState(null),[p,f]=y.useState(null),[g,v]=y.useState(!0),[b,x]=y.useState(null),[S,k]=y.useState(!1),[N,C]=y.useState(null),[T,j]=y.useState(0),[F,P]=y.useState(!1),[D,R]=y.useState(null),[B,O]=y.useState(!1),[L,Y]=y.useState(!1),ee=y.useRef(null),Z=y.useRef(null),ce=10,de=160,ue=240,Q=.35;y.useEffect(()=>{const z=ae=>{ae.key==="Escape"&&i()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[i]),y.useEffect(()=>{if(v(!0),d){const z=(n||"").toLowerCase(),ae=z==="3mf"||z==="gcode.3mf",ge=ae||z==="stl",xe=ae||z==="gcode";f({has_model:ge,has_gcode:xe,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m(ge?"3d":xe?"gcode":null),v(!1);return}if(!t){f(null),m(null),v(!1);return}re.getArchiveCapabilities(t).then(z=>{f(z),z.has_model?m("3d"):z.has_gcode&&m("gcode"),v(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),m("3d"),v(!1)})},[t,n,d]),y.useEffect(()=>{if(k(!0),C(null),j(0),d){const z=(n||"").toLowerCase();if(!e||!(z==="3mf"||z==="gcode.3mf")){x(null),k(!1);return}re.getLibraryFilePlates(e).then(ge=>x(ge)).catch(()=>x(null)).finally(()=>k(!1));return}if(!t){x(null),k(!1);return}re.getArchivePlates(t).then(z=>x(z)).catch(()=>x(null)).finally(()=>k(!1))},[t,n,d,e]);const ne=y.useMemo(()=>b?.plates??[],[b]),pe=(b?.is_multi_plate??!1)&&ne.length>1,me=F&&pe,be=N==null?null:ne.find(z=>z.index===N)??null,q=z=>z.object_count??z.objects?.length??0,J=ne.reduce((z,ae)=>z+q(ae),0),A=be?q(be):J,M=be?o("modelViewer.plateNumber",{number:be.index}):o("modelViewer.allPlates"),H=ne.length>0,W=y.useRef(null),U=y.useRef(null),[se,I]=y.useState(10),[G,K]=y.useState(3),X=ne.length>se,ie=Math.max(1,Math.ceil(ne.length/se)),oe=X?ne.slice(T*se,(T+1)*se):ne;y.useEffect(()=>{if(!me){I(10),K(3);return}const z=W.current,ae=U.current;if(!z||!ae)return;let ge=0;const xe=()=>{const Me=ae.clientWidth,Ue=Math.floor(Me/210),_e=Math.max(3,Math.min(5,Ue||3));K(Xe=>Xe===_e?Xe:_e);const ze=window.getComputedStyle(z),Fe=Number.parseFloat(ze.rowGap||"0"),Oe=z.querySelector("button")?.getBoundingClientRect().height??44,it=ae.clientHeight,st=Math.max(1,Math.floor((it+Fe)/(Oe+Fe)))*_e,Te=Math.max(1,st-1);I(Xe=>Xe===Te?Xe:Te)},ve=()=>{ge&&cancelAnimationFrame(ge),ge=requestAnimationFrame(xe)};ve();const je=new ResizeObserver(ve);return je.observe(ae),je.observe(z),()=>{ge&&cancelAnimationFrame(ge),je.disconnect()}},[me,ne.length]),y.useEffect(()=>{if(!X){j(0);return}j(z=>Math.min(z,ie-1))},[ne.length,X,ie]),y.useEffect(()=>{if(!X||N==null)return;const z=ne.findIndex(ge=>ge.index===N);if(z<0)return;const ae=Math.floor(z/se);j(ge=>ge===ae?ge:ae)},[ne,se,N,X]),y.useEffect(()=>{if(!me){R(null),Y(!1);return}if(L)return;const z=ee.current,ae=Z.current;if(!z||!ae)return;const ge=z.clientHeight;if(!ge)return;const xe=Math.max(ue,ge*Q),ve=Math.max(de,ge-ce-xe),je=Math.min(ae.scrollHeight,ve);R(Math.max(de,je))},[me,L,ne.length,T,ce,de,ue,Q]),y.useEffect(()=>{if(!B)return;const z=ge=>{const xe=ee.current;if(!xe)return;const ve=xe.getBoundingClientRect(),je=ve.height;if(!je)return;const Me=Math.max(ue,je*Q),Se=Math.max(de,je-ce-Me),Ue=Math.min(Se,Math.max(de,ge.clientY-ve.top));R(Ue)},ae=()=>{O(!1),Y(!0)};return document.addEventListener("mousemove",z),document.addEventListener("mouseup",ae),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",ae),document.body.style.cursor="",document.body.style.userSelect=""}},[B,ce,de,ue,Q]);const he=d?(n||"").toLowerCase()==="3mf":!0,le=(()=>{const z=(n||"").toLowerCase();return z==="3mf"||z==="stl"||z==="step"||z==="stp"})(),fe=!!(d&&l?.use_slicer_api&&s&&le),$=async()=>{if(!he)return;const z=a||"model";try{if(d){const{token:ae}=await re.createLibrarySlicerToken(e),ge=re.getLibrarySlicerDownloadUrl(e,ae,z);Dm(`${window.location.origin}${ge}`,c)}else{const{token:ae}=await re.createArchiveSlicerToken(t),ge=re.getArchiveSlicerDownloadUrl(t,ae,z);Dm(`${window.location.origin}${ge}`,c)}}catch{if(d){const ae=`${window.location.origin}${re.getLibraryFileDownloadUrl(e)}`;Dm(ae,c)}else{const ae=`${window.location.origin}${re.getArchiveForSlicer(t,z)}`;Dm(ae,c)}}};return r.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${F?"p-0":"p-8"}`,onClick:i,children:r.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${F?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:z=>z.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[r.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:a}),H&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[M,": ",o("modelViewer.objectCount",{count:A})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[fe?r.jsxs(De,{variant:"secondary",size:"sm",onClick:s,children:[r.jsx(hd,{className:"w-4 h-4"}),o("slice.action")]}):r.jsxs(De,{variant:"secondary",size:"sm",onClick:$,disabled:!he,children:[r.jsx(Dr,{className:"w-4 h-4"}),o("modelViewer.openInSlicer")]}),r.jsx(De,{variant:"secondary",size:"sm",onClick:()=>P(z=>!z),title:F?"Exit fullscreen":"Enter fullscreen",children:F?r.jsx(RI,{className:"w-4 h-4"}):r.jsx(MT,{className:"w-4 h-4"})}),r.jsx(De,{variant:"ghost",size:"sm",onClick:i,children:r.jsx(Gt,{className:"w-5 h-5"})})]})]}),p&&r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[r.jsxs("button",{onClick:()=>p.has_model&&m("3d"),disabled:!p.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":p.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Ai,{className:"w-4 h-4"}),o("modelViewer.tabs.model"),!p.has_model&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notAvailable"),")"]})]}),r.jsxs("button",{onClick:()=>p.has_gcode&&m("gcode"),disabled:!p.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":p.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[r.jsx(Jge,{className:"w-4 h-4"}),o("modelViewer.tabs.gcode"),!p.has_gcode&&r.jsxs("span",{className:"text-xs",children:["(",o("modelViewer.notSliced"),")"]})]})]}),r.jsx("div",{className:"flex-1 overflow-hidden p-4",children:g?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&p?r.jsxs("div",{ref:ee,className:`w-full h-full flex flex-col ${me?"gap-0 min-h-0":"gap-3"}`,children:[pe&&r.jsxs("div",{ref:Z,style:me&&D!=null?{height:D}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${me?"flex flex-col shrink-0":""}`,children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[r.jsx(cn,{className:"w-4 h-4"}),o("modelViewer.plates"),S&&r.jsx(pt,{className:"w-3 h-3 animate-spin"})]}),r.jsxs("div",{className:me?"flex flex-col min-h-0 flex-1":void 0,children:[r.jsx("div",{ref:U,className:me?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:r.jsxs("div",{ref:W,className:me?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:me?{gridTemplateColumns:`repeat(${G}, minmax(0, 1fr))`}:void 0,children:[r.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${me?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${me?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${me?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${me?"text-xs":"text-sm"} text-white font-medium truncate`,children:o("modelViewer.allPlates")}),r.jsx("p",{className:`${me?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.plateCount",{count:ne.length})})]}),N==null&&r.jsx(_r,{className:`${me?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),oe.map(z=>r.jsxs("button",{type:"button",onClick:()=>C(z.index),className:`flex items-center rounded-lg border text-left transition-colors ${me?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===z.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[z.has_thumbnail&&z.thumbnail_url?r.jsx("img",{src:z.thumbnail_url,alt:`Plate ${z.index}`,className:`${me?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):r.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${me?"w-8 h-8":"w-10 h-10"}`,children:r.jsx(cn,{className:`${me?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:`${me?"text-xs":"text-sm"} text-white font-medium truncate`,children:z.name||o("modelViewer.plateNumber",{number:z.index})}),r.jsx("p",{className:`${me?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:o("modelViewer.objectCount",{count:z.object_count??z.objects?.length??0})})]}),N===z.index&&r.jsx(_r,{className:`${me?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},z.index))]})}),(be||X)&&r.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[be&&r.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[r.jsx("span",{children:o("modelViewer.plateNumber",{number:be.index})}),be.print_time_seconds!=null&&r.jsx("span",{children:o("modelViewer.eta",{minutes:Math.round(be.print_time_seconds/60)})}),be.filament_used_grams!=null&&r.jsxs("span",{children:[be.filament_used_grams.toFixed(1)," g"]}),be.filaments.length>0&&r.jsx("span",{children:o("modelViewer.filamentCount",{count:be.filaments.length})})]}),X&&r.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${be?"ml-auto":""}`,children:[r.jsx("span",{children:o("modelViewer.pagination.pageOf",{current:T+1,total:ie})}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{type:"button",onClick:()=>j(z=>Math.max(z-1,0)),disabled:T===0,className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.prev")}),(()=>{let ae=Math.max(0,T-Math.floor(2.5));const ge=Math.min(ie,ae+5);ge-ae<5&&(ae=Math.max(0,ge-5));const xe=Array.from({length:ge-ae},(ve,je)=>ae+je);return r.jsxs(r.Fragment,{children:[ae>0&&r.jsx("button",{type:"button",onClick:()=>j(0),className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ae>1&&r.jsx("span",{className:"px-1",children:"…"}),xe.map(ve=>r.jsx("button",{type:"button",onClick:()=>j(ve),className:`px-2 py-1 rounded border text-xs ${T===ve?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ve+1},ve)),gej(ie-1),className:`px-2 py-1 rounded border text-xs ${T===ie-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:ie})]})})(),r.jsx("button",{type:"button",onClick:()=>j(z=>Math.min(z+1,ie-1)),disabled:T>=ie-1,className:`px-2 py-1 rounded border text-xs ${T>=ie-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:o("modelViewer.pagination.next")})]})]})]})]})]}),me&&r.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:z=>{z.preventDefault(),O(!0),Y(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${B?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:r.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),r.jsx("div",{className:`flex-1 ${me?"min-h-0":""}`,children:r.jsx(uee,{url:d?re.getLibraryFileDownloadUrl(e):p.has_source?re.getSource3mfDownloadUrl(t):re.getArchiveDownload(t),fileType:n,buildVolume:p.build_volume,filamentColors:p.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&p?r.jsx(Wee,{gcodeUrl:d?re.getLibraryFileGcodeUrl(e):re.getArchiveGcode(t),filamentColors:p.filament_colors,className:"w-full h-full"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:o("modelViewer.noPreview")})})]})})}const pst=90;function hst({onClose:t}){const{t:e}=wt(),a=aa(),{showToast:n}=sa(),[i,s]=y.useState(pst),[o,l]=y.useState(!0),[c,d]=y.useState(i);y.useEffect(()=>{const b=window.setTimeout(()=>d(i),300);return()=>window.clearTimeout(b)},[i]);const u=Qe({queryKey:["library-purge-preview",c,o],queryFn:()=>re.previewLibraryPurge(c,o),enabled:c>=1}),m=lt({mutationFn:()=>re.executeLibraryPurge(i,o),onSuccess:b=>{n(e("libraryPurge.toast.success",{count:b.moved_to_trash}),"success"),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]}),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),t()},onError:b=>n(b.message||e("libraryPurge.toast.failed"),"error")});y.useEffect(()=>{const b=x=>{x.key==="Escape"&&!m.isPending&&t()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,m.isPending]);const p=u.data,f=p?.count??0,g=p?.total_bytes??0,v=f>0&&!m.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(ta,{className:"w-5 h-5"}),e("libraryPurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":e("common.close"),disabled:m.isPending,children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:e("libraryPurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"purge-days",type:"number",min:1,max:3650,value:i,onChange:b=>s(Math.max(1,Math.min(3650,parseInt(b.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:e("libraryPurge.days")})]})]}),r.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[r.jsx("input",{type:"checkbox",checked:o,onChange:b=>l(b.target.checked),className:"rounded border-gray-300"}),e("libraryPurge.includeNeverPrinted")]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:e("libraryPurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:e("libraryPurge.effect1")}),r.jsx("li",{children:e("libraryPurge.effect2")}),r.jsx("li",{children:e("libraryPurge.effect3")}),r.jsx("li",{children:e("libraryPurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:u.isLoading||u.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"})," ",e("libraryPurge.previewLoading")]}):u.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:u.error?.message??e("libraryPurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:e("libraryPurge.previewSummary",{count:f,size:ss(g)})}),p?.sample_filenames&&p.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[p.sample_filenames.map(b=>r.jsx("li",{className:"truncate",children:b},b)),f>p.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:e("libraryPurge.andMore",{count:f-p.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(ga,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:e("libraryPurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(De,{variant:"secondary",onClick:t,disabled:m.isPending,children:e("common.cancel")}),r.jsx(De,{variant:"danger",disabled:!v,onClick:()=>m.mutate(),children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin mr-1"}),e("libraryPurge.purging")]}):e("libraryPurge.confirmCta",{count:f})})]})]})})}function fst({parentId:t,onClose:e,onSave:a,isLoading:n,t:i}){const[s,o]=y.useState(""),l=c=>{c.preventDefault(),a({name:s.trim(),parent_id:t})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),r.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),r.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:i("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(De,{type:"submit",disabled:!s.trim()||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function gst({onClose:t,onSave:e,isLoading:a,t:n}){const[i,s]=y.useState(""),[o,l]=y.useState(""),[c,d]=y.useState(!0),[u,m]=y.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(lC,{className:"w-5 h-5 text-bambu-green"}),n("fileManager.linkExternalFolder")]}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:n("fileManager.linkExternalFolderDescription")})]}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.folderName")}),r.jsx("input",{type:"text",value:i,onChange:f=>s(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:n("fileManager.externalPath")}),r.jsx("input",{type:"text",value:o,onChange:f=>l(f.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm",placeholder:"/mnt/nas/3d-prints",required:!0}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("fileManager.externalPathHelp")})]}),r.jsxs("div",{className:"space-y-2",children:[r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:c,onChange:f=>d(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.readOnly")}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",n("fileManager.readOnlyHelp"),")"]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:f=>m(f.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("span",{className:"text-sm text-white",children:n("fileManager.showHiddenFiles")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:t,children:n("common.cancel")}),r.jsx(De,{type:"submit",disabled:!i.trim()||!o.trim()||a,children:a?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):n("fileManager.linkFolder")})]})]})]})})}const bst='<>:"/\\|?*';function xst(t){for(const e of t)if(bst.includes(e)||e.charCodeAt(0)<32)return e;return null}function yst({type:t,currentName:e,onClose:a,onSave:n,isLoading:i,t:s}){const o=t==="file"?e.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1]??"":"",l=t==="file"&&o?e.slice(0,-o.length):e,[c,d]=y.useState(l),u=t==="file"?xst(c):null,m=u?s("fileManager.invalidFilenameChar",{char:u}):null,p=f=>{if(f.preventDefault(),m)return;const g=t==="file"?c.trim()+o:c.trim();c.trim()&&g!==e&&n(g)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),r.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),r.jsxs("div",{className:`flex items-center bg-bambu-dark border rounded focus-within:border-bambu-green ${m?"border-red-500":"border-bambu-dark-tertiary"}`,children:[r.jsx("input",{type:"text",value:c,onChange:f=>d(f.target.value),className:"flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0",autoFocus:!0,required:!0}),o&&r.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]}),m&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:m})]}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:a,children:s("common.cancel")}),r.jsx(De,{type:"submit",disabled:!c.trim()||c.trim()===l||!!m||i,children:i?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function vst({folders:t,selectedFiles:e,currentFolderId:a,onClose:n,onMove:i,isLoading:s,t:o}){const[l,c]=y.useState(null),d=(m,p=0)=>{const f=[];for(const g of m)f.push({id:g.id,name:g.name,depth:p}),g.children.length>0&&f.push(...d(g.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:r.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>r.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===a,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===m.id?"bg-bambu-green/20 text-bambu-green":m.id===a?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[r.jsx(Tl,{className:"w-4 h-4"}),m.name,m.id===a&&r.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),r.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[r.jsx(De,{type:"button",variant:"secondary",onClick:n,children:o("common.cancel")}),r.jsx(De,{onClick:()=>i(l),disabled:s,children:s?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function wst({folder:t,onClose:e,onLink:a,isLoading:n,t:i}){const[s,o]=y.useState("project"),[l,c]=y.useState(t.project_id||t.archive_id||null);y.useState(()=>{t.archive_id&&o("archive")});const{data:d}=Qe({queryKey:["projects"],queryFn:()=>re.getProjects(),select:g=>[...g].sort((v,b)=>v.name.localeCompare(b.name))}),{data:u}=Qe({queryKey:["archives-for-link"],queryFn:()=>re.getArchives(void 0,void 0,100)}),m=()=>{a(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{a({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx(Fh,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),r.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:r.jsx(Gt,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(KZ,{className:"w-4 h-4"}),i("fileManager.project")]}),r.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[r.jsx(ao,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),r.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?d&&d.length>0?d.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:g.color||"#00ae42"}}),r.jsx("span",{className:"truncate",children:g.name})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(g=>r.jsxs("button",{onClick:()=>c(g.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===g.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[r.jsx(Mh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"truncate",children:g.print_name||g.filename})]},g.id)):r.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),r.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&r.jsxs(De,{variant:"danger",onClick:p,disabled:n,children:[r.jsx(cu,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),r.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[r.jsx(De,{variant:"secondary",onClick:e,children:i("common.cancel")}),r.jsx(De,{onClick:m,disabled:!l||n,children:n?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function hde({folder:t,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,defaultExpanded:c=!0,hasPermission:d,t:u}){const[m,p]=y.useState(c),[f,g]=y.useState(!1),v=t.children.length>0,b=t.project_id||t.archive_id,x=t.is_external;return r.jsxs("div",{children:[r.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>a(t.id),children:[v?r.jsx("button",{onClick:S=>{S.stopPropagation(),p(!m)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:r.jsx(qn,{className:`w-3.5 h-3.5 transition-transform ${m?"rotate-90":""}`})}):r.jsx("div",{className:"w-4.5"}),x?r.jsx(lC,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):r.jsx(Tl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),r.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),b&&r.jsxs("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[r.jsx(Fh,{className:"w-3 h-3"}),t.project_name?r.jsx(KZ,{className:"w-3 h-3"}):r.jsx(ao,{className:"w-3 h-3"})]}),x&&t.external_readonly&&r.jsx("span",{title:u("fileManager.readOnly"),children:r.jsx(cc,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&r.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!b&&!x&&r.jsx("button",{onClick:S=>{S.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:r.jsx(Fh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),r.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:S=>S.stopPropagation(),children:r.jsxs("div",{className:"relative",children:[r.jsx("button",{onClick:()=>g(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:r.jsx(km,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),r.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(s(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[r.jsx(xi,{className:"w-3.5 h-3.5"}),u("common.rename")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:update_all")&&(i(t),g(!1))},disabled:!d("library:update_all"),title:d("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[r.jsx(Fh,{className:"w-3.5 h-3.5"}),u(b?"fileManager.changeLink":"fileManager.linkTo")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${d("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{d("library:delete_all")&&(n(t.id),g(!1))},disabled:!d("library:delete_all"),title:d("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[r.jsx(ta,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),v&&m&&r.jsx("div",{children:t.children.map(S=>r.jsx(hde,{folder:S,selectedFolderId:e,onSelect:a,onDelete:n,onLink:i,onRename:s,depth:o+1,wrapNames:l,defaultExpanded:c,hasPermission:d,t:u},S.id))})]})}function Tw(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")}function dI(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.endsWith(".gcode.3mf")?!1:e.endsWith(".stl")||e.endsWith(".3mf")||e.endsWith(".step")||e.endsWith(".stp")}function Sst({file:t,isSelected:e,isMobile:a,onSelect:n,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onSlice:c,useSlicerApi:d,onPreview3d:u,onRename:m,onGenerateThumbnail:p,thumbnailVersion:f,hasPermission:g,canModify:v,authEnabled:b,t:x}){const[S,k]=y.useState(!1);return r.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>n(t.id),children:[r.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?r.jsx("img",{src:`${re.getLibraryFileThumbnailUrl(t.id)}${f?(re.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${f}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):r.jsx(Mh,{className:"w-12 h-12 text-bambu-gray/30"}),r.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"||t.file_type==="gcode.3mf"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),r.jsxs("div",{className:"p-3",children:[r.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),r.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[r.jsx("span",{children:ss(t.file_size)}),t.print_time_seconds&&r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx(er,{className:"w-3 h-3"}),ls(t.print_time_seconds)]})]}),t.sliced_for_model&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&r.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:x("fileManager.printedCount",{count:t.print_count})}),b&&t.created_by_username&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[r.jsx(Ym,{className:"w-3 h-3"}),t.created_by_username]})]}),r.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:N=>N.stopPropagation(),children:[r.jsx("button",{onClick:()=>k(!S),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:r.jsx(km,{className:"w-4 h-4 text-bambu-gray"})}),S&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>k(!1)}),r.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&Tw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("printers:control")&&(l(t),k(!1))},disabled:!g("printers:control"),title:g("printers:control")?void 0:x("fileManager.noPermissionPrint"),children:[r.jsx(xr,{className:"w-3.5 h-3.5"}),x("common.print")]}),o&&Tw(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("queue:create")&&(o(t.id),k(!1))},disabled:!g("queue:create"),title:g("queue:create")?void 0:x("fileManager.noPermissionAddToQueue"),children:[r.jsx(er,{className:"w-3.5 h-3.5"}),x("fileManager.schedulePrint")]}),c&&d&&dI(t.filename)&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:upload")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:upload")&&(c(t),k(!1))},disabled:!g("library:upload"),title:g("library:upload")?void 0:x("fileManager.noPermissionSlice"),children:[r.jsx(hd,{className:"w-3.5 h-3.5"}),x("slice.action")]}),u&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl"||t.file_type==="gcode.3mf")&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(u(t),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:"You do not have permission to preview files",children:[r.jsx(Ai,{className:"w-3.5 h-3.5"}),"3D Preview"]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${g("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{g("library:read")&&(s(t.id),k(!1))},disabled:!g("library:read"),title:g("library:read")?void 0:x("fileManager.noPermissionDownload"),children:[r.jsx(Ur,{className:"w-3.5 h-3.5"}),x("common.download")]}),m&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(m(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionRenameFile"),children:[r.jsx(xi,{className:"w-3.5 h-3.5"}),x("common.rename")]}),p&&t.file_type==="stl"&&r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","update",t.created_by_id)&&(p(t),k(!1))},disabled:!v("library","update",t.created_by_id),title:v("library","update",t.created_by_id)?void 0:x("fileManager.noPermissionGenerateThumbnail"),children:[r.jsx(pu,{className:"w-3.5 h-3.5"}),x("fileManager.generateThumbnail")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${v("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{v("library","delete",t.created_by_id)&&(i(t.id),k(!1))},disabled:!v("library","delete",t.created_by_id),title:v("library","delete",t.created_by_id)?void 0:x("fileManager.noPermissionDeleteFile"),children:[r.jsx(ta,{className:"w-3.5 h-3.5"}),x("common.delete")]})]})]})]}),r.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${a?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function kst(){const{t}=wt(),e=aa(),{showToast:a}=sa(),{hasPermission:n,hasAnyPermission:i,canModify:s,authEnabled:o}=lr(),[l]=lb(),c=Ri(),d=l.get("folder"),u=d?parseInt(d,10):null,[m,p]=y.useState(u),[f,g]=y.useState([]),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,N]=y.useState(!1),[C,T]=y.useState(!1),[j,F]=y.useState(!1),[P,D]=y.useState(null),[R,B]=y.useState(null),[O,L]=y.useState(null),[Y,ee]=y.useState(null),[Z,ce]=y.useState(null),[de,ue]=y.useState(null),[Q,ne]=y.useState(null),[pe,me]=y.useState({}),[be,q]=y.useState(null),[J,A]=y.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[M,H]=y.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[W,U]=y.useState(()=>localStorage.getItem("library-collapse-folders")==="true"),[se,I]=y.useState(()=>{const Ce=localStorage.getItem("library-sidebar-width");return Ce?parseInt(Ce,10):256}),[G,K]=y.useState(!1),X=y.useRef(null);y.useEffect(()=>{if(!G)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ce=Je=>{if(!X.current)return;const Re=X.current.parentElement?.getBoundingClientRect();if(!Re)return;const bt=Je.clientX-Re.left,Pe=Math.min(500,Math.max(200,bt));I(Pe)},Ke=()=>{K(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(se))};return document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",Ke),()=>{document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",Ke),document.body.style.userSelect="",document.body.style.cursor=""}},[G,se]);const[ie,oe]=y.useState(""),[he,le]=y.useState("all"),[fe,$]=y.useState(""),[z,ae]=y.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ge,xe]=y.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ve=Pse();y.useEffect(()=>{const Ce=l.get("folder");if(Ce){const Ke=parseInt(Ce,10);p(Ke)}},[l]);const{data:je}=Qe({queryKey:["settings"],queryFn:()=>re.getSettings()}),{data:Me,isLoading:Se}=Qe({queryKey:["library-folders"],queryFn:()=>re.getLibraryFolders()}),{data:Ue}=Qe({queryKey:["library-trash-count"],queryFn:async()=>{try{return(await re.listLibraryTrash(1,0)).total}catch{return 0}},staleTime:3e4}),{data:_e,isLoading:ze}=Qe({queryKey:["library-files",m],queryFn:()=>re.getLibraryFiles(m,!1)}),{data:Fe}=Qe({queryKey:["library-stats"],queryFn:()=>re.getLibraryStats()}),{data:qe}=Qe({queryKey:["users"],queryFn:()=>re.getUsers()}),Oe=y.useMemo(()=>{if(!_e)return[];const Ce=new Set(_e.map(Ke=>Ke.file_type));return Array.from(Ce).sort()},[_e]),it=y.useMemo(()=>{if(!_e)return[];let Ce=[..._e];if(ie.trim()){const Ke=ie.toLowerCase();Ce=Ce.filter(Je=>Je.filename.toLowerCase().includes(Ke)||Je.print_name&&Je.print_name.toLowerCase().includes(Ke))}if(he!=="all"&&(Ce=Ce.filter(Ke=>Ke.file_type===he)),fe.trim()){const Ke=fe.toLowerCase();Ce=Ce.filter(Je=>Je.created_by_username&&Je.created_by_username.toLowerCase().includes(Ke))}return Ce.sort((Ke,Je)=>{let Re=0;switch(z){case"name":Re=(Ke.print_name||Ke.filename).localeCompare(Je.print_name||Je.filename);break;case"date":Re=(Ia(Ke.created_at)?.getTime()??0)-(Ia(Je.created_at)?.getTime()??0);break;case"size":Re=Ke.file_size-Je.file_size;break;case"type":Re=Ke.file_type.localeCompare(Je.file_type);break;case"prints":Re=Ke.print_count-Je.print_count;break}return ge==="asc"?Re:-Re}),Ce},[_e,ie,he,fe,z,ge]),Le=y.useMemo(()=>{if(!Fe||!je)return!1;const Ce=(je.library_disk_warning_gb||5)*1024*1024*1024;return Fe.disk_free_bytesre.createLibraryFolder(Ce),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),b(!1),a(t("fileManager.toast.folderCreated"),"success")},onError:Ce=>a(Ce.message,"error")}),Te=lt({mutationFn:async Ce=>{const Ke=await re.createExternalFolder(Ce);return await re.scanExternalFolder(Ke.id),Ke},onSuccess:Ce=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),S(!1),p(Ce.id),a(t("fileManager.toast.externalFolderLinked"),"success")},onError:Ce=>a(Ce.message,"error")}),Xe=lt({mutationFn:Ce=>re.scanExternalFolder(Ce),onSuccess:Ce=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),a(t("fileManager.toast.folderScanned",{added:Ce.added,removed:Ce.removed}),"success")},onError:Ce=>a(Ce.message,"error")}),$e=lt({mutationFn:Ce=>re.deleteLibraryFolder(Ce),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),m===R?.id&&p(null),B(null),a(t("fileManager.toast.folderDeleted"),"success")},onError:Ce=>{B(null),a(Ce.message,"error")}}),Ne=lt({mutationFn:Ce=>re.deleteLibraryFile(Ce),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),g(Ce=>Ce.filter(Ke=>Ke!==R?.id)),B(null),a(t("fileManager.toast.fileDeleted"),"success")},onError:Ce=>{B(null),a(Ce.message,"error")}}),Ie=lt({mutationFn:Ce=>re.bulkDeleteLibrary(Ce,[]),onSuccess:(Ce,Ke)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),e.invalidateQueries({queryKey:["library-trash-count"]}),a(t("fileManager.toast.filesDeleted",{count:Ke.length}),"success"),g([]),B(null)},onError:Ce=>{B(null),a(Ce.message,"error")}}),et=lt({mutationFn:({fileIds:Ce,folderId:Ke})=>re.moveLibraryFiles(Ce,Ke),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),g([]),N(!1),a(t("fileManager.toast.filesMoved"),"success")},onError:Ce=>a(Ce.message,"error")}),We=lt({mutationFn:({id:Ce,data:Ke})=>re.updateLibraryFolder(Ce,Ke),onSuccess:(Ce,Ke)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),D(null);const Je=Ke.data.project_id===0&&Ke.data.archive_id===0;a(t(Je?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ce=>a(Ce.message,"error")}),Ae=lt({mutationFn:({id:Ce,filename:Ke})=>re.updateLibraryFile(Ce,{filename:Ke}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ne(null),a(t("fileManager.toast.fileRenamed"),"success")},onError:Ce=>{ne(null),a(Ce.message,"error")}}),at=lt({mutationFn:({id:Ce,name:Ke})=>re.updateLibraryFolder(Ce,{name:Ke}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ne(null),a(t("fileManager.toast.folderRenamed"),"success")},onError:Ce=>{ne(null),a(Ce.message,"error")}}),rt=lt({mutationFn:()=>re.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ce=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ce.succeeded>0){const Ke=Date.now(),Je={};Ce.results.forEach(Re=>{Re.success&&(Je[Re.file_id]=Ke)}),me(Re=>({...Re,...Je}))}Ce.succeeded>0&&Ce.failed===0?a(t("fileManager.toast.thumbnailsGenerated",{count:Ce.succeeded}),"success"):Ce.succeeded>0&&Ce.failed>0?a(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ce.succeeded,failed:Ce.failed}),"success"):Ce.processed===0?a(t("fileManager.toast.noStlMissingThumbnails"),"info"):a(t("fileManager.toast.failedToGenerateThumbnails",{error:Ce.results[0]?.error||"Unknown error"}),"error")},onError:Ce=>a(Ce.message,"error")}),Ct=lt({mutationFn:Ce=>re.batchGenerateStlThumbnails({file_ids:[Ce]}),onSuccess:Ce=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ce.succeeded>0){const Ke=Ce.results[0]?.file_id;Ke&&me(Je=>({...Je,[Ke]:Date.now()})),a(t("fileManager.toast.thumbnailGenerated"),"success")}else a(t("fileManager.toast.failedToGenerateThumbnail",{error:Ce.results[0]?.error||"Unknown error"}),"error")},onError:Ce=>a(Ce.message,"error")}),Ut=y.useCallback(Ce=>{const Ke=Ce.toLowerCase();return Ke.endsWith(".gcode")||Ke.includes(".gcode.")},[]),ft=y.useMemo(()=>_e?_e.filter(Ce=>f.includes(Ce.id)&&Ut(Ce.filename)):[],[_e,f,Ut]),Kt=y.useCallback(Ce=>{g(Ke=>Ke.includes(Ce)?Ke.filter(Je=>Je!==Ce):[...Ke,Ce])},[]),Zt=y.useCallback(()=>{it.length>0&&g(it.map(Ce=>Ce.id))},[it]),oa=y.useCallback(()=>{g([])},[]),xa=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},dt=Ce=>{re.downloadLibraryFile(Ce).catch(Ke=>{console.error("Library file download failed:",Ke)})},vt=()=>{R&&(R.type==="file"?Ne.mutate(R.id):R.type==="folder"?$e.mutate(R.id):R.type==="bulk"&&Ie.mutate(f))},Pt=$e.isPending||Ne.isPending||Ie.isPending,Nt=Ce=>{A(Ce),localStorage.setItem("library-view-mode",Ce)},It=Se||ze,Ee=y.useMemo(()=>{if(!m||!Me)return null;const Ce=Ke=>{for(const Je of Ke){if(Je.id===m)return Je;const Re=Ce(Je.children);if(Re)return Re}return null};return Ce(Me)},[m,Me]);return r.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[r.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(Tl,{className:"w-7 h-7 text-bambu-green"}),t("fileManager.title")]}),r.jsx("p",{className:"text-bambu-gray mt-1",children:t("fileManager.subtitle")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[r.jsx("button",{onClick:()=>Nt("grid"),className:`p-1.5 rounded transition-colors ${J==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:r.jsx(FS,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>Nt("list"),className:`p-1.5 rounded transition-colors ${J==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:r.jsx(LS,{className:"w-4 h-4"})})]}),r.jsxs(De,{variant:"secondary",onClick:()=>rt.mutate(),disabled:rt.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[rt.isPending?r.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):r.jsx(pu,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),r.jsxs(De,{variant:"secondary",onClick:()=>S(!0),disabled:!n("library:upload"),title:n("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[r.jsx(lC,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),r.jsxs(De,{variant:"secondary",onClick:()=>b(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[r.jsx(Qbe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),n("library:purge")&&r.jsxs(De,{variant:"secondary",onClick:()=>F(!0),title:t("libraryPurge.headerTooltip"),children:[r.jsx(ta,{className:"w-4 h-4 mr-2"}),t("libraryPurge.headerButton")]}),i("library:delete_own","library:delete_all")&&r.jsxs(Ds,{to:"/files/trash",className:"inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors",title:t("libraryTrash.headerTooltip"),children:[r.jsx(ta,{className:"w-4 h-4 mr-2"}),t("libraryTrash.headerButton"),typeof Ue=="number"&&Ue>0&&r.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green",children:Ue})]}),r.jsxs(De,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(kn,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),Le&&Fe&&je&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[r.jsx(ga,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),r.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ss(Fe.disk_free_bytes),total:ss(Fe.disk_total_bytes),threshold:je.library_disk_warning_gb})})]})]}),Fe&&r.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(jT,{className:"w-4 h-4 text-bambu-green"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Fe.total_files})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(Tl,{className:"w-4 h-4 text-blue-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),r.jsx("span",{className:"text-white font-medium",children:Fe.total_folders})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx(ub,{className:"w-4 h-4 text-amber-400"}),r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),r.jsx("span",{className:"text-white font-medium",children:ss(Fe.total_size_bytes)})]}),r.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[r.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),r.jsx("span",{className:`font-medium ${Le?"text-amber-500":"text-white"}`,children:ss(Fe.disk_free_bytes)})]})]}),r.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[r.jsx("div",{className:"lg:hidden",children:r.jsxs("select",{value:m??"",onChange:Ce=>p(Ce.target.value?parseInt(Ce.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[r.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),Me&&(()=>{const Ce=(Ke,Je=0)=>{const Re=[];for(const bt of Ke)Re.push({id:bt.id,name:bt.name,fileCount:bt.file_count,depth:Je}),bt.children.length>0&&Re.push(...Ce(bt.children,Je+1));return Re};return Ce(Me).map(Ke=>r.jsxs("option",{value:Ke.id,children:["│ ".repeat(Ke.depth),"📂 ",Ke.name," ",Ke.fileCount>0?`(${Ke.fileCount})`:""]},Ke.id))})()]})}),r.jsxs("div",{ref:X,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${se}px`},children:[r.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${G?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ce=>{Ce.preventDefault(),K(!0)},onDoubleClick:()=>{I(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:r.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${G?"opacity-100":""}`,children:[r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),r.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),r.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[r.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:()=>{const Ce=!W;U(Ce),localStorage.setItem("library-collapse-folders",String(Ce))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.expandFoldersByDefault":"fileManager.collapseFoldersByDefault"),children:t("fileManager.collapse")}),r.jsx("button",{onClick:()=>{const Ce=!M;H(Ce),localStorage.setItem("library-wrap-folders",String(Ce))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${M?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(M?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[r.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${m===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>p(null),children:[r.jsx(Mh,{className:"w-4 h-4"}),r.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),Me?.map(Ce=>r.jsx(hde,{folder:Ce,selectedFolderId:m,onSelect:p,onDelete:Ke=>B({type:"folder",id:Ke}),onLink:D,onRename:Ke=>ne({type:"folder",id:Ke.id,name:Ke.name}),wrapNames:M,defaultExpanded:!W,hasPermission:n,t},`${Ce.id}-${W?"c":"e"}`))]})]}),r.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[Ee?.is_external&&r.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[r.jsx(lC,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),Ee.external_readonly&&r.jsxs("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400 flex items-center gap-1",children:[r.jsx(cc,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),r.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:Ee.external_path||"",children:Ee.external_path})]}),r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>m&&Xe.mutate(m),disabled:Xe.isPending,title:t("fileManager.scanFolder"),children:[Xe.isPending?r.jsx(pt,{className:"w-4 h-4 animate-spin"}):r.jsx(Qa,{className:"w-4 h-4"}),r.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),_e&&_e.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[r.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),r.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ie,onChange:Ce=>oe(Ce.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(MS,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),r.jsxs("select",{value:he,onChange:Ce=>le(Ce.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"all",children:t("fileManager.allTypes")}),Oe.map(Ce=>r.jsx("option",{value:Ce,children:Ce.toUpperCase()},Ce))]})]}),o&&r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:fe,onChange:Ce=>$(Ce.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${fe?"pr-7":""}`,style:fe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),fe&&r.jsx("button",{onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:r.jsx(Gt,{className:"w-3 h-3"})}),r.jsx("datalist",{id:"usernames-list",children:qe?.map(Ce=>r.jsx("option",{value:Ce.username},Ce.id))})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("select",{value:z,onChange:Ce=>{const Ke=Ce.target.value;ae(Ke),localStorage.setItem("library-sort-field",Ke)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[r.jsx("option",{value:"name",children:t("common.name")}),r.jsx("option",{value:"date",children:t("common.date")}),r.jsx("option",{value:"size",children:t("fileManager.size")}),r.jsx("option",{value:"type",children:t("common.type")}),r.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),r.jsx("button",{onClick:()=>xe(Ce=>{const Ke=Ce==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ke),Ke}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ge==="asc"?"fileManager.ascending":"fileManager.descending"),children:ge==="asc"?r.jsx(Zfe,{className:"w-4 h-4 text-white"}):r.jsx($fe,{className:"w-4 h-4 text-white"})})]}),(ie||he!=="all"||fe)&&r.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:it.length,total:_e.length})})]}),it.length>0&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===it.length&&f.length>0?r.jsxs(De,{variant:"secondary",size:"sm",onClick:oa,children:[r.jsx(io,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):r.jsxs(De,{variant:"secondary",size:"sm",onClick:Zt,children:[r.jsx(fs,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),r.jsx("div",{className:"hidden sm:block flex-1"}),r.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[ft.length===1&&r.jsxs(De,{variant:"primary",size:"sm",onClick:()=>ee(ft[0]),disabled:!n("printers:control"),title:n("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[r.jsx(ps,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),ft.length===1&&r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>ce(ft[0]),disabled:!n("queue:create"),title:n("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[r.jsx(er,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),r.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>N(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[r.jsx(mye,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),r.jsxs(De,{variant:"danger",size:"sm",onClick:()=>{f.length===1?B({type:"file",id:f[0]}):B({type:"bulk",id:0,count:f.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[r.jsx(ta,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),r.jsxs(De,{variant:"secondary",size:"sm",onClick:oa,children:[r.jsx(Gt,{className:"w-4 h-4 sm:mr-1"}),r.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),It?r.jsx("div",{className:"flex-1 flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-3",children:[r.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):_e?.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(Mh,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(m!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(m!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),r.jsxs(De,{onClick:()=>T(!0),disabled:!n("library:upload"),title:n("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[r.jsx(ar,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):it.length===0?r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[r.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:r.jsx(br,{className:"w-12 h-12 text-bambu-gray/50"})}),r.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),r.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),r.jsx(De,{variant:"secondary",onClick:()=>{oe(""),le("all")},children:t("fileManager.clearFilters")})]}):J==="grid"?r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:it.map(Ce=>r.jsx(Sst,{file:Ce,isSelected:f.includes(Ce.id),isMobile:ve,t,onSelect:Kt,onDelete:Ke=>B({type:"file",id:Ke}),onDownload:dt,onAddToQueue:Ke=>{const Je=_e?.find(Re=>Re.id===Ke);Je&&ce(Je)},onPrint:L,onSlice:ue,useSlicerApi:je?.use_slicer_api??!1,onPreview3d:Ke=>{Tw(Ke.filename)?c(`/gcode-viewer?library_file=${Ke.id}`):q(Ke)},onRename:Ke=>ne({type:"file",id:Ke.id,name:Ke.filename}),onGenerateThumbnail:Ke=>Ct.mutate(Ke.id),thumbnailVersion:pe[Ce.id],hasPermission:n,canModify:s,authEnabled:o},Ce.id))})}):r.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-x-auto",children:[r.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[r.jsx("div",{className:"w-6"}),r.jsx("div",{children:t("common.name")}),o&&r.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),r.jsx("div",{children:t("common.type")}),r.jsx("div",{children:t("fileManager.size")}),r.jsx("div",{children:t("fileManager.prints")}),r.jsx("div",{})]}),it.map(Ce=>r.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_min-content]":"grid-cols-[auto_1fr_100px_100px_100px_min-content]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Ce.id)?"bg-bambu-green/10":""}`,onClick:()=>Kt(Ce.id),children:[r.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ce.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ce.id)&&r.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsxs("div",{className:"relative group/thumb",children:[r.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ce.thumbnail_path?r.jsx("img",{src:`${re.getLibraryFileThumbnailUrl(Ce.id)}${pe[Ce.id]?(re.getLibraryFileThumbnailUrl(Ce.id).includes("?")?"&":"?")+`v=${pe[Ce.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Mh,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ce.thumbnail_path&&r.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:r.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:r.jsx("img",{src:`${re.getLibraryFileThumbnailUrl(Ce.id)}${pe[Ce.id]?(re.getLibraryFileThumbnailUrl(Ce.id).includes("?")?"&":"?")+`v=${pe[Ce.id]}`:""}`,alt:Ce.filename,className:"w-full h-full object-contain"})})})]}),r.jsx("div",{className:"min-w-0",children:r.jsx("div",{className:"text-sm text-white truncate",children:Ce.print_name||Ce.filename})})]}),o&&r.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ce.created_by_username?r.jsxs(r.Fragment,{children:[r.jsx(Ym,{className:"w-3 h-3"}),r.jsx("span",{className:"truncate",children:Ce.created_by_username})]}):"-"}),r.jsx("div",{children:r.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ce.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ce.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ce.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ce.file_type.toUpperCase()})}),r.jsx("div",{className:"text-sm text-bambu-gray",children:ss(Ce.file_size)}),r.jsx("div",{className:"text-sm text-bambu-gray",children:Ce.print_count>0?`${Ce.print_count}x`:"-"}),r.jsxs("div",{className:"flex items-center gap-1",onClick:Ke=>Ke.stopPropagation(),children:[Tw(Ce.filename)&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>n("printers:control")&&L(Ce),className:`p-1.5 rounded transition-colors ${n("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!n("printers:control"),children:r.jsx(xr,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>{n("queue:create")&&ce(Ce)},className:`p-1.5 rounded transition-colors ${n("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!n("queue:create"),children:r.jsx(er,{className:"w-4 h-4"})})]}),(je?.use_slicer_api??!1)&&dI(Ce.filename)&&r.jsx("button",{onClick:()=>n("library:upload")&&ue(Ce),className:`p-1.5 rounded transition-colors ${n("library:upload")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:upload")?t("slice.action"):t("fileManager.noPermissionSlice"),disabled:!n("library:upload"),children:r.jsx(hd,{className:"w-4 h-4"})}),(Ce.file_type==="3mf"||Ce.file_type==="gcode"||Ce.file_type==="stl")&&r.jsx("button",{onClick:()=>{n("library:read")&&(Tw(Ce.filename)?c(`/gcode-viewer?library_file=${Ce.id}`):q(Ce))},className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!n("library:read"),children:r.jsx(Ai,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>n("library:read")&&dt(Ce.id),className:`p-1.5 rounded transition-colors ${n("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:n("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!n("library:read"),children:r.jsx(Ur,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","update",Ce.created_by_id)&&ne({type:"file",id:Ce.id,name:Ce.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ce.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ce.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ce.created_by_id),children:r.jsx(xi,{className:"w-4 h-4"})}),Ce.file_type==="stl"&&r.jsx("button",{onClick:()=>s("library","update",Ce.created_by_id)&&Ct.mutate(Ce.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ce.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ce.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ct.isPending||!s("library","update",Ce.created_by_id),children:r.jsx(pu,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>s("library","delete",Ce.created_by_id)&&B({type:"file",id:Ce.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ce.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ce.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ce.created_by_id),children:r.jsx(ta,{className:"w-4 h-4"})})]})]},Ce.id))]})})]})]}),v&&r.jsx(fst,{parentId:m,onClose:()=>b(!1),onSave:Ce=>st.mutate(Ce),isLoading:st.isPending,t}),x&&r.jsx(gst,{onClose:()=>S(!1),onSave:Ce=>Te.mutate(Ce),isLoading:Te.isPending,t}),k&&Me&&r.jsx(vst,{folders:Me,selectedFiles:f,currentFolderId:m,onClose:()=>N(!1),onMove:Ce=>et.mutate({fileIds:f,folderId:Ce}),isLoading:et.isPending,t}),C&&r.jsx(mse,{folderId:m,onClose:()=>T(!1),onUploadComplete:xa}),j&&r.jsx(hst,{onClose:()=>F(!1)}),P&&r.jsx(wst,{folder:P,onClose:()=>D(null),onLink:Ce=>We.mutate({id:P.id,data:Ce}),isLoading:We.isPending,t}),R&&r.jsx(ya,{title:R.type==="folder"?t("fileManager.deleteFolder"):R.type==="bulk"?t("fileManager.deleteFilesCount",{count:R.count}):t("fileManager.deleteFile"),message:R.type==="folder"?t("fileManager.deleteFolderConfirm"):R.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:R.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Pt,loadingText:t("fileManager.deleting"),onConfirm:vt,onCancel:()=>B(null)}),O&&r.jsx(kc,{mode:"reprint",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>L(null),onSuccess:()=>{L(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Y&&r.jsx(kc,{mode:"reprint",libraryFileId:Y.id,archiveName:Y.print_name||Y.filename,onClose:()=>ee(null),onSuccess:()=>{ee(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),Z&&r.jsx(kc,{mode:"add-to-queue",libraryFileId:Z.id,archiveName:Z.print_name||Z.filename,onClose:()=>ce(null),onSuccess:()=>{ce(null),g([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&r.jsx(VA,{source:{kind:"libraryFile",id:de.id,filename:de.filename},onClose:()=>ue(null)}),be&&r.jsx(mst,{libraryFileId:be.id,title:be.print_name||be.filename,fileType:be.file_type,onClose:()=>q(null),onSliceWithBambuddy:dI(be.filename)&&n("library:upload")?()=>{const Ce=be;q(null),ue(Ce)}:void 0}),Q&&r.jsx(yst,{type:Q.type,currentName:Q.name,onClose:()=>ne(null),onSave:Ce=>{Q.type==="file"?Ae.mutate({id:Q.id,filename:Ce}):at.mutate({id:Q.id,name:Ce})},isLoading:Ae.isPending||at.isPending,t})]})}function _st(t){const e=Ia(t);if(!e)return"";const a=Math.ceil((e.getTime()-Date.now())/(1e3*60*60*24));return a<=0?"any moment":a===1?"1 day":`${a} days`}function LX(t){const e=Ia(t);return e?e.toLocaleString():t}function Pst(){const{t}=wt(),e=Ri(),a=aa(),{showToast:n}=sa(),{hasPermission:i,authEnabled:s}=lr(),[o,l]=y.useState(null),[c,d]=y.useState(new Set),u=!s||i("library:purge"),m=Qe({queryKey:["library-trash"],queryFn:()=>re.listLibraryTrash(200,0)}),p=Qe({queryKey:["library-trash-settings"],queryFn:()=>re.getLibraryTrashSettings(),enabled:u}),[f,g]=y.useState(null);y.useEffect(()=>{p.data&&f===null&&g(p.data.retention_days)},[p.data,f]);const v=lt({mutationFn:O=>{const L=p.data;return re.updateLibraryTrashSettings({retention_days:O,auto_purge_enabled:L?.auto_purge_enabled??!1,auto_purge_days:L?.auto_purge_days??90,auto_purge_include_never_printed:L?.auto_purge_include_never_printed??!0})},onSuccess:O=>{n(t("libraryTrash.toast.retentionSaved",{days:O.retention_days}),"success"),a.invalidateQueries({queryKey:["library-trash-settings"]}),a.invalidateQueries({queryKey:["library-trash"]})},onError:O=>n(O.message||t("libraryTrash.toast.retentionFailed"),"error")}),b=lt({mutationFn:O=>re.restoreLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.restored"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),x=lt({mutationFn:O=>re.hardDeleteLibraryTrash(O),onSuccess:()=>{n(t("libraryTrash.toast.purged"),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),S=lt({mutationFn:()=>re.emptyLibraryTrash(),onSuccess:O=>{n(t("libraryTrash.toast.emptied",{count:O.deleted}),"success"),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.emptyFailed"),"error")}),k=lt({mutationFn:O=>Promise.all(O.map(L=>re.restoreLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkRestored",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]}),a.invalidateQueries({queryKey:["library-files"]}),a.invalidateQueries({queryKey:["library-folders"]})},onError:O=>n(O.message||t("libraryTrash.toast.restoreFailed"),"error")}),N=lt({mutationFn:O=>Promise.all(O.map(L=>re.hardDeleteLibraryTrash(L))),onSuccess:(O,L)=>{n(t("libraryTrash.toast.bulkPurged",{count:L.length}),"success"),d(new Set),a.invalidateQueries({queryKey:["library-trash"]}),a.invalidateQueries({queryKey:["library-trash-count"]})},onError:O=>n(O.message||t("libraryTrash.toast.purgeFailed"),"error")}),C=y.useMemo(()=>m.data?.items??[],[m.data?.items]),T=m.data?.retention_days??30,j=y.useMemo(()=>C.reduce((O,L)=>O+L.file_size,0),[C]),F=C.length>0&&C.every(O=>c.has(O.id)),P=c.size>0&&!F,D=O=>{d(L=>{const Y=new Set(L);return Y.has(O)?Y.delete(O):Y.add(O),Y})},R=()=>{d(O=>O.size===C.length?new Set:new Set(C.map(L=>L.id)))},B=()=>{o&&(o.type==="delete"?x.mutate(o.id):o.type==="bulkDelete"?N.mutate(Array.from(c)):S.mutate(),l(null))};return r.jsxs("div",{className:"p-6 max-w-screen-2xl mx-auto",children:[r.jsx("div",{className:"flex items-center gap-3 mb-4",children:r.jsxs(Ds,{to:"/files",className:"inline-flex items-center gap-1 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200",children:[r.jsx(CT,{className:"w-4 h-4"})," ",t("libraryTrash.backToFiles")]})}),r.jsxs("div",{className:"flex items-start justify-between mb-6 gap-4 flex-wrap",children:[r.jsxs("div",{children:[r.jsx("h1",{className:"text-2xl font-bold text-gray-900 dark:text-gray-100",children:t("libraryTrash.title")}),r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u?t("libraryTrash.subtitleAdmin",{days:T}):t("libraryTrash.subtitleUser",{days:T})})]}),C.length>0&&r.jsxs(De,{variant:"secondary",onClick:()=>l({type:"empty"}),className:"text-red-600 dark:text-red-400",children:[r.jsx(ta,{className:"w-4 h-4 mr-1"}),t("libraryTrash.emptyTrash")]})]}),u&&p.data&&r.jsxs("div",{className:"mb-4 border border-gray-200 dark:border-gray-700 rounded-lg p-3 flex items-center gap-3 bg-gray-50 dark:bg-gray-800/40",children:[r.jsx("label",{htmlFor:"retention-days",className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:t("libraryTrash.retentionLabel")}),r.jsx("input",{id:"retention-days",type:"number",min:1,max:365,value:f??p.data.retention_days,onChange:O=>g(Math.max(1,Math.min(365,parseInt(O.target.value||"0",10)||0))),className:"w-20 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:t("libraryTrash.days")}),r.jsxs(De,{variant:"secondary",onClick:()=>f!=null&&v.mutate(f),disabled:v.isPending||f==null||f===p.data.retention_days,className:"ml-auto",children:[r.jsx(cs,{className:"w-4 h-4 mr-1"}),t("common.save")]})]}),m.isLoading?r.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"})," ",t("libraryTrash.loading")]}):C.length===0?r.jsx("div",{className:"border border-dashed border-gray-300 dark:border-gray-700 rounded-lg p-12 text-center",children:r.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:t("libraryTrash.empty")})}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:t("libraryTrash.summary",{count:C.length,size:ss(j)})}),c.size>0&&r.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:t("libraryTrash.selectionCount",{count:c.size})}),r.jsxs(De,{variant:"secondary",onClick:()=>k.mutate(Array.from(c)),disabled:k.isPending,children:[r.jsx(hs,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkRestore")]}),r.jsxs(De,{variant:"secondary",onClick:()=>l({type:"bulkDelete",count:c.size}),disabled:N.isPending,className:"text-red-600 dark:text-red-400",children:[r.jsx(ta,{className:"w-4 h-4 mr-1"}),t("libraryTrash.bulkPurge")]})]})]}),r.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-x-auto",children:r.jsxs("table",{className:"w-full text-sm",children:[r.jsx("thead",{className:"bg-gray-50 dark:bg-gray-800 text-left text-gray-600 dark:text-gray-300",children:r.jsxs("tr",{children:[r.jsx("th",{className:"px-3 py-2 w-10",children:r.jsx("input",{type:"checkbox",checked:F,ref:O=>{O&&(O.indeterminate=P)},onChange:R,"aria-label":t("libraryTrash.selectAll"),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.filename")}),r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.folder")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.size")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.deleted")}),r.jsx("th",{className:"px-3 py-2 font-medium whitespace-nowrap",children:t("libraryTrash.col.autoPurge")}),u&&r.jsx("th",{className:"px-3 py-2 font-medium",children:t("libraryTrash.col.owner")}),r.jsx("th",{className:"px-3 py-2 font-medium text-right",children:t("libraryTrash.col.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800",children:C.map(O=>r.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[r.jsx("td",{className:"px-3 py-2",children:r.jsx("input",{type:"checkbox",checked:c.has(O.id),onChange:()=>D(O.id),"aria-label":t("libraryTrash.selectOne",{filename:O.filename}),className:"rounded border-gray-300 cursor-pointer"})}),r.jsx("td",{className:"px-3 py-2 text-gray-900 dark:text-gray-100 truncate max-w-md",title:O.filename,children:O.filename}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.folder_name??"—"}),r.jsx("td",{className:"px-3 py-2 text-right text-gray-600 dark:text-gray-400 tabular-nums whitespace-nowrap",children:ss(O.file_size)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:LX(O.deleted_at)}),r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400 whitespace-nowrap",children:r.jsx("span",{title:LX(O.auto_purge_at),children:t("libraryTrash.autoPurgeIn",{when:_st(O.auto_purge_at)})})}),u&&r.jsx("td",{className:"px-3 py-2 text-gray-600 dark:text-gray-400",children:O.created_by_username??"—"}),r.jsxs("td",{className:"px-3 py-2 text-right whitespace-nowrap",children:[r.jsxs("button",{onClick:()=>b.mutate(O.id),disabled:b.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300",children:[r.jsx(hs,{className:"w-3.5 h-3.5"}),t("libraryTrash.restore")]}),r.jsxs("button",{onClick:()=>l({type:"delete",id:O.id,filename:O.filename}),disabled:x.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 ml-2",children:[r.jsx(ta,{className:"w-3.5 h-3.5"}),t("libraryTrash.purgeNow")]})]})]},O.id))})]})})]}),o&&r.jsx(ya,{onCancel:()=>l(null),onConfirm:B,title:o.type==="delete"?t("libraryTrash.confirm.purgeTitle"):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeTitle"):t("libraryTrash.confirm.emptyTitle"),message:o.type==="delete"?t("libraryTrash.confirm.purgeBody",{filename:o.filename}):o.type==="bulkDelete"?t("libraryTrash.confirm.bulkPurgeBody",{count:o.count}):t("libraryTrash.confirm.emptyBody",{count:C.length}),confirmText:t("libraryTrash.confirm.cta"),variant:"danger"}),m.isError&&r.jsxs("div",{className:"mt-4 text-sm text-red-600 dark:text-red-400",children:[m.error?.message??t("libraryTrash.loadError"),r.jsx(De,{variant:"secondary",onClick:()=>e("/files"),className:"ml-3",children:t("libraryTrash.backToFiles")})]})]})}function Nst(t,e){const a=`token=${encodeURIComponent(e)}`;let n=0;return t.querySelectorAll('img[src*="/api/v1/"], video[src*="/api/v1/"]').forEach(i=>{const s=i.getAttribute("src")||"";if(s.includes(a))return;const o=s.replace(/([?&])token=[^&]*(&|$)/,(c,d,u)=>u==="&"?d:""),l=o.includes("?")?"&":"?";i.src=`${o}${l}${a}`,n+=1}),n}function fde(){const{authEnabled:t,user:e,loading:a}=lr(),n=aa(),i=y.useRef(!1),{data:s}=Qe({queryKey:["camera-stream-token",e?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:!a&&(!t||e!==null),staleTime:3e3*1e3,refetchInterval:3e3*1e3});y.useEffect(()=>{const o=s?.token??null;return C8(o),o&&Nst(document,o),()=>C8(null)},[s?.token]),y.useEffect(()=>{if(!t)return;const o=l=>{const c=l.target;if(!(c instanceof HTMLImageElement||c instanceof HTMLVideoElement))return;const d=c.src||"",u=uJ();!u||!d.includes(`token=${encodeURIComponent(u)}`)||i.current||(i.current=!0,n.invalidateQueries({queryKey:["camera-stream-token"]}),setTimeout(()=>{i.current=!1},5e3))};return document.addEventListener("error",o,!0),()=>document.removeEventListener("error",o,!0)},[t,n])}const xN=5,Cst=2e3,Tst=3e4,Ast=5e3;function jst(){const{t}=wt(),e=aa(),{showToast:a}=sa(),{hasPermission:n,authEnabled:i,user:s}=lr(),{printerId:o}=AS(),l=parseInt(o||"0",10),[c]=lb(),d=parseInt(c.get("fps")||"15",10),u=Math.min(Math.max(isNaN(d)?15:d,1),30);fde();const{data:m}=Qe({queryKey:["camera-stream-token",s?.id??null],queryFn:()=>re.getCameraStreamToken(),enabled:i?!!s:!0,staleTime:3e3*1e3}),p=m?.token??uJ(),[f,g]=y.useState("stream"),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,N]=y.useState(!1),[C,T]=y.useState(!0),[j,F]=y.useState(Date.now()),[P,D]=y.useState(!1),[R,B]=y.useState(!1),[O,L]=y.useState(0),[Y,ee]=y.useState(!1),[Z,ce]=y.useState(0),[de,ue]=y.useState(1),[Q,ne]=y.useState({x:0,y:0}),[pe,me]=y.useState(!1),[be,q]=y.useState({x:0,y:0}),[J,A]=y.useState(null),[M,H]=y.useState(null),W=y.useRef(null),U=y.useRef(null),se=y.useRef(null),I=y.useRef(null),G=y.useRef(null),{data:K}=Qe({queryKey:["printer",l],queryFn:()=>re.getPrinter(l),enabled:l>0}),{data:X}=Qe({queryKey:["printerStatus",l],queryFn:()=>re.getPrinterStatus(l),refetchInterval:3e4,enabled:l>0}),ie=lt({mutationFn:Ie=>re.setChamberLight(l,Ie),onMutate:async Ie=>{await e.cancelQueries({queryKey:["printerStatus",l]});const et=e.getQueryData(["printerStatus",l]);return e.setQueryData(["printerStatus",l],We=>({...We,chamber_light:Ie})),{previousStatus:et}},onSuccess:(Ie,et)=>{a(`Chamber light ${et?"on":"off"}`)},onError:(Ie,et,We)=>{We?.previousStatus&&e.setQueryData(["printerStatus",l],We.previousStatus),a(Ie.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(X?.state==="RUNNING"||X?.state==="PAUSE")&&(X?.printable_objects_count??0)>=2;y.useEffect(()=>(K&&(document.title=`${K.name} - Camera`),()=>{document.title="Bambuddy"}),[K]);const he=y.useRef(!1);y.useEffect(()=>{const Ie=`/api/v1/printers/${l}/camera/stop`;he.current=!1;const et=()=>{if(l>0&&!he.current){he.current=!0;const at={},rt=Xm();rt&&(at.Authorization=`Bearer ${rt}`),fetch(Ie,{method:"POST",keepalive:!0,headers:at}).catch(()=>{})}},We=()=>{et()};window.addEventListener("beforeunload",We);const Ae=W.current;return()=>{window.removeEventListener("beforeunload",We),Ae&&(Ae.src=""),et()}},[l]),y.useEffect(()=>{if(C&&!P){const et=setTimeout(()=>{T(!1)},f==="stream"?3e3:2e4);return()=>clearTimeout(et)}},[f,C,j,P]),y.useEffect(()=>{const Ie=()=>{const et=!!document.fullscreenElement;B(et),ue(1),ne({x:0,y:0}),f==="stream"&&!P&&(W.current&&(W.current.src=""),setTimeout(()=>{T(!0),F(Date.now())},200))};return document.addEventListener("fullscreenchange",Ie),()=>document.removeEventListener("fullscreenchange",Ie)},[f,P]),y.useEffect(()=>{let Ie;const et=()=>{clearTimeout(Ie),Ie=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",et),()=>{clearTimeout(Ie),window.removeEventListener("resize",et)}},[]),y.useEffect(()=>()=>{se.current&&clearTimeout(se.current),I.current&&clearInterval(I.current),G.current&&clearInterval(G.current)},[]);const le=y.useCallback(()=>{if(O>=xN){ee(!1),N(!0);return}const Ie=Math.min(Cst*Math.pow(2,O),Tst);ee(!0),ce(Math.ceil(Ie/1e3)),I.current=setInterval(()=>{ce(et=>et<=1?(I.current&&clearInterval(I.current),0):et-1)},1e3),se.current=setTimeout(()=>{L(et=>et+1),ee(!1),T(!0),N(!1),W.current&&(W.current.src=""),F(Date.now())},Ie)},[O]);y.useEffect(()=>{if(f!=="stream"||C||Y||P){G.current&&(clearInterval(G.current),G.current=null);return}return G.current=setInterval(async()=>{try{const Ie=await re.getCameraStatus(l);(Ie.stalled||!Ie.active&&!k)&&(console.log(`Stream issue detected: stalled=${Ie.stalled}, active=${Ie.active}, reconnecting...`),G.current&&(clearInterval(G.current),G.current=null),T(!1),le())}catch{}},Ast),()=>{G.current&&(clearInterval(G.current),G.current=null)}},[f,C,k,Y,P,l,le]);const fe=()=>{T(!1),f==="stream"&&O{if(T(!1),N(!1),L(0),ee(!1),se.current&&clearTimeout(se.current),I.current&&clearInterval(I.current),W.current&&!localStorage.getItem("cameraWindowState")){const Ie=W.current,et=Ie.naturalWidth,We=Ie.naturalHeight;if(et>0&&We>0){const rt=window.outerWidth-window.innerWidth,Ct=window.outerHeight-window.innerHeight,Ut=et+16+rt,ft=We+45+16+Ct;try{window.resizeTo(Ut,ft)}catch{}}}},z=()=>{if(l>0){const Ie={},et=Xm();et&&(Ie.Authorization=`Bearer ${et}`),fetch(`/api/v1/printers/${l}/camera/stop`,{method:"POST",headers:Ie}).catch(()=>{})}},ae=Ie=>{f===Ie||P||(D(!0),T(!0),N(!1),L(0),ee(!1),ue(1),ne({x:0,y:0}),se.current&&clearTimeout(se.current),I.current&&clearInterval(I.current),W.current&&(W.current.src=""),f==="stream"&&z(),setTimeout(()=>{g(Ie),F(Date.now()),D(!1)},100))},ge=()=>{P||(D(!0),T(!0),N(!1),L(0),ee(!1),se.current&&clearTimeout(se.current),I.current&&clearInterval(I.current),W.current&&(W.current.src=""),f==="stream"&&z(),setTimeout(()=>{F(Date.now()),D(!1)},100))},xe=()=>{U.current&&(document.fullscreenElement?document.exitFullscreen():U.current.requestFullscreen())},ve=()=>{ue(Ie=>Math.min(Ie+.5,4))},je=()=>{ue(Ie=>{const et=Math.max(Ie-.5,1);return et===1&&ne({x:0,y:0}),et})},Me=Ie=>{Ie.preventDefault(),Ie.deltaY<0?ve():je()},Se=Ie=>{de>1&&(Ie.preventDefault(),me(!0),q({x:Ie.clientX-Q.x,y:Ie.clientY-Q.y}))},Ue=y.useCallback(()=>{if(!U.current)return{x:300,y:200};const Ie=U.current.getBoundingClientRect(),et=Ie.width*(de-1)/2,We=Ie.height*(de-1)/2;return{x:Math.max(50,et),y:Math.max(50,We)}},[de]),_e=Ie=>{if(pe&&de>1){const et=Ie.clientX-be.x,We=Ie.clientY-be.y,Ae=Ue();ne({x:Math.max(-Ae.x,Math.min(Ae.x,et)),y:Math.max(-Ae.y,Math.min(Ae.y,We))})}},ze=()=>{me(!1)},Fe=Ie=>{if(Ie.length<2)return 0;const et=Ie[0].clientX-Ie[1].clientX,We=Ie[0].clientY-Ie[1].clientY;return Math.sqrt(et*et+We*We)},qe=Ie=>Ie.length<2?{x:Ie[0].clientX,y:Ie[0].clientY}:{x:(Ie[0].clientX+Ie[1].clientX)/2,y:(Ie[0].clientY+Ie[1].clientY)/2},Oe=Ie=>{Ie.touches.length===2?(Ie.preventDefault(),A(Fe(Ie.touches)),H(qe(Ie.touches))):Ie.touches.length===1&&de>1&&(Ie.preventDefault(),me(!0),q({x:Ie.touches[0].clientX-Q.x,y:Ie.touches[0].clientY-Q.y}))},it=Ie=>{if(Ie.touches.length===2&&J!==null){Ie.preventDefault();const et=Fe(Ie.touches),We=et/J;ue(at=>{const rt=Math.max(1,Math.min(4,at*We));return rt===1&&ne({x:0,y:0}),rt}),A(et);const Ae=qe(Ie.touches);if(M){const at=Ue();ne(rt=>({x:Math.max(-at.x,Math.min(at.x,rt.x+(Ae.x-M.x))),y:Math.max(-at.y,Math.min(at.y,rt.y+(Ae.y-M.y)))}))}H(Ae)}else if(Ie.touches.length===1&&pe&&de>1){Ie.preventDefault();const et=Ie.touches[0].clientX-be.x,We=Ie.touches[0].clientY-be.y,Ae=Ue();ne({x:Math.max(-Ae.x,Math.min(Ae.x,et)),y:Math.max(-Ae.y,Math.min(Ae.y,We))})}},Le=Ie=>{Ie.touches.length<2&&(A(null),H(null)),Ie.touches.length===0&&me(!1)},st=()=>{ue(1),ne({x:0,y:0})},Te=i&&!p,Xe=Ie=>p?`${Ie}&token=${encodeURIComponent(p)}`:Fn(Ie),$e=P||Te?"":Xe(f==="stream"?`/api/v1/printers/${l}/camera/stream?fps=${u}&t=${j}`:`/api/v1/printers/${l}/camera/snapshot?t=${j}`),Ne=C||P||Y;return l?r.jsxs("div",{ref:U,className:"min-h-screen bg-black flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[r.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[r.jsx(vy,{className:"w-4 h-4"}),K?.name||`Printer ${l}`]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[r.jsx("button",{onClick:()=>ae("stream"),disabled:Ne,className:`px-3 py-1 text-xs rounded transition-colors ${f==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),r.jsx("button",{onClick:()=>ae("snapshot"),disabled:Ne,className:`px-3 py-1 text-xs rounded transition-colors ${f==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),r.jsx("button",{onClick:()=>ie.mutate(!X?.chamber_light),disabled:!X?.connected||ie.isPending||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${X?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:n("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:r.jsx(yO,{on:X?.chamber_light??!1,className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>b(!0),disabled:!oe||!n("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&n("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:n("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:r.jsx(YT,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:ge,disabled:Ne,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(f==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:r.jsx(Qa,{className:`w-4 h-4 text-bambu-gray ${Ne?"animate-spin":""}`})}),r.jsx("button",{onClick:()=>S(!0),className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t("camera.diagnose.button"),children:r.jsx(Al,{className:"w-4 h-4 text-bambu-gray"})}),r.jsx("button",{onClick:xe,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(R?"camera.exitFullscreen":"camera.fullscreen"),children:R?r.jsx(eJ,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(tye,{className:"w-4 h-4 text-bambu-gray"})})]})]}),r.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:Me,onMouseMove:_e,onMouseUp:ze,onMouseLeave:ze,onTouchStart:Oe,onTouchMove:it,onTouchEnd:Le,style:{touchAction:"none"},children:r.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(C||P)&&!Y&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:r.jsxs("div",{className:"text-center",children:[r.jsx(Qa,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),r.jsx("p",{className:"text-sm text-bambu-gray",children:t(f==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),Y&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(fu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),r.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:Z,attempt:Math.min(O+1,xN),max:xN})}),r.jsx("button",{onClick:ge,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),k&&!Y&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:r.jsxs("div",{className:"text-center p-4",children:[r.jsx(ga,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),r.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),r.jsxs("div",{className:"flex gap-2 justify-center",children:[r.jsx("button",{onClick:ge,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")}),r.jsx("button",{onClick:()=>S(!0),className:"px-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white rounded transition-colors",children:t("camera.diagnose.button")})]})]})}),r.jsx("img",{ref:W,src:$e,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${de}) translate(${Q.x/de}px, ${Q.y/de}px) rotate(${K?.camera_rotation||0}deg)`,...K?.camera_rotation===90||K?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:de>1?pe?"grabbing":"grab":"default"},onError:$e?fe:void 0,onLoad:$e?$:void 0,onMouseDown:Se,draggable:!1},j),r.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[r.jsx("button",{onClick:je,disabled:de<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:r.jsx(OI,{className:"w-4 h-4 text-white"})}),r.jsxs("button",{onClick:st,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(de*100),"%"]}),r.jsx("button",{onClick:ve,disabled:de>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:r.jsx(II,{className:"w-4 h-4 text-white"})})]})]})}),r.jsx(vO,{printerId:l,isOpen:v,onClose:()=>b(!1)}),x&&r.jsx(Kee,{printerId:l,printerName:K?.name||null,onClose:()=>S(!1)})]}):r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Mst(t,e,a){if(!t)return"";if(!e)return t;const n=e.match(/plate_(\d+)\.gcode/);return n&&parseInt(n[1],10)>1?`${t} — ${a("printers.plateNumber","Plate {{number}}",{number:n[1]})}`:t}function Est(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],a=parseInt(t.get("fps")||"15",10),n=Math.min(Math.max(isNaN(a)?15:a,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:n,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function Dst(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function Fst(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function Lst(){const{printerId:t}=AS(),[e]=lb(),{t:a}=wt(),n=aa(),i=parseInt(t||"0",10),[s,o]=y.useState(Date.now()),l=y.useMemo(()=>Est(e),[e]),c=Fst(l.size),{data:d}=Qe({queryKey:["printer",i],queryFn:()=>re.getPrinter(i),enabled:i>0}),{data:u}=Qe({queryKey:["printerStatus",i],queryFn:()=>re.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=Qe({queryKey:["settings"],queryFn:re.getSettings}),p=m?.time_format||"system";y.useEffect(()=>{if(!i)return;let x=null,S=!1;return(async()=>{let k;try{k=(await re.getWebSocketToken()).token}catch{}if(S)return;const N=window.location.protocol==="https:"?"wss:":"ws:",C=k?`?token=${encodeURIComponent(k)}`:"",T=`${N}//${window.location.host}/api/v1/ws${C}`;x=new WebSocket(T),x.onmessage=j=>{try{const F=JSON.parse(j.data);F.type==="printer_status"&&F.printer_id===i&&n.setQueryData(["printerStatus",i],F.status)}catch{}},x.onerror=()=>{}})(),()=>{S=!0,x&&x.close()}},[i,n]),y.useEffect(()=>(document.title=d?`${d.name} - ${a("streamOverlay.title")}`:a("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,a]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-white",children:a("streamOverlay.invalidPrinterId")})});if(!u)return r.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:r.jsx("p",{className:"text-gray-400",children:a("common.loading")})});const g=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Fn(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return r.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&r.jsx("img",{src:b,alt:a("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",style:d?.camera_rotation?{transform:`rotate(${d.camera_rotation}deg)`}:void 0,onError:f},s),r.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:r.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),r.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:r.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&r.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[r.jsx(xr,{className:`${c.icon} text-white/70`}),r.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&r.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Mst(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,a)}),l.showStatus&&r.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Dst(u,a)}),l.showProgress&&g&&r.jsxs("div",{className:"mb-3",children:[r.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[r.jsx("span",{className:"text-white/70",children:a("streamOverlay.progress")}),r.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),r.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:r.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),g&&(l.showLayers||l.showEta)&&r.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&u.layer_num!=null&&u.total_layers!=null&&u.total_layers>0&&r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(cn,{className:c.icon}),r.jsxs("span",{className:c.text,children:[r.jsx("span",{className:"text-white",children:u.layer_num}),r.jsx("span",{className:"mx-1",children:"/"}),r.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(eu,{className:c.icon}),r.jsx("span",{className:`${c.text} text-white`,children:ls(u.remaining_time*60)})]}),r.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[r.jsx(er,{className:c.icon}),r.jsxs("span",{className:`${c.text} text-white`,children:[a("streamOverlay.eta")," ",qI(u.remaining_time,p,a)]})]})]})]}),!g&&r.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?a("streamOverlay.printerIdle"):a("streamOverlay.printerOffline")})]})})]})}function Rst(){const{t}=wt(),{id:e}=AS(),{mode:a}=pb(),{data:n,isLoading:i,error:s}=Qe({queryKey:["external-link",e],queryFn:()=>re.getExternalLink(Number(e)),enabled:!!e});return i?r.jsx("div",{className:"flex items-center justify-center h-full",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!n?r.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[r.jsx(ga,{className:"w-12 h-12"}),r.jsx("p",{children:t("common.linkNotFound")})]}):r.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:a},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function RX(){const{id:t}=AS(),e=Ri(),a=aa(),{t:n}=wt(),{showToast:i}=sa(),s=!!t,[o,l]=y.useState(""),[c,d]=y.useState(""),[u,m]=y.useState([]),[p,f]=y.useState(""),[g,v]=y.useState(!1),{data:b,isLoading:x}=Qe({queryKey:["group",t],queryFn:()=>re.getGroup(Number(t)),enabled:s}),{data:S,isLoading:k}=Qe({queryKey:["permissions"],queryFn:()=>re.getPermissions()});s&&b&&!g&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const N=lt({mutationFn:Z=>re.createGroup(Z),onSuccess:()=>{a.invalidateQueries({queryKey:["groups"]}),a.invalidateQueries({queryKey:["group"]}),i(n("groups.toast.created")),e("/settings?tab=users")},onError:Z=>{i(Z.message,"error")}}),C=lt({mutationFn:Z=>re.updateGroup(Number(t),Z),onSuccess:Z=>{a.invalidateQueries({queryKey:["groups"]}),Z&&a.setQueryData(["group",t],Z),i(n("groups.toast.updated")),e("/settings?tab=users")},onError:Z=>{i(Z.message,"error")}}),T=N.isPending||C.isPending,j=()=>{if(!o.trim()){i(n("groups.toast.enterGroupName"),"error");return}s?C.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):N.mutate({name:o,description:c||void 0,permissions:u})},F=Z=>{m(ce=>ce.includes(Z)?ce.filter(de=>de!==Z):[...ce,Z])},P=(Z,ce)=>{const de=Z.permissions.map(ue=>ue.value);m(ue=>{const Q=ue.filter(ne=>!de.includes(ne));return ce?[...Q,...de]:Q})},D=Z=>Z.permissions.every(ce=>u.includes(ce.value)),R=Z=>{const ce=Z.permissions.filter(de=>u.includes(de.value)).length;return ce>0&&ce{S&&m(S.all_permissions)},O=()=>{m([])},L=p.toLowerCase(),Y=y.useMemo(()=>S?L?S.categories.map(Z=>({...Z,permissions:Z.permissions.filter(ce=>ce.label.toLowerCase().includes(L))})).filter(Z=>Z.permissions.length>0):S.categories:[],[S,L]),ee=S?.all_permissions.length??0;return x||k?r.jsx("div",{className:"flex items-center justify-center py-16",children:r.jsx(pt,{className:"w-8 h-8 text-bambu-green animate-spin"})}):r.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:r.jsx(CT,{className:"w-5 h-5"})}),r.jsx("h1",{className:"text-xl font-bold text-white",children:n(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[r.jsx(ga,{className:"w-4 h-4 shrink-0"}),n("groups.form.systemGroupWarning")]}),r.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.groupName")}),r.jsx("input",{type:"text",value:o,onChange:Z=>l(Z.target.value),disabled:s&&b?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:n("groups.form.groupNamePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:n("groups.form.description")}),r.jsx("input",{type:"text",value:c,onChange:Z=>d(Z.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:n("groups.form.descriptionPlaceholder")})]})]}),r.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("span",{className:"text-sm text-bambu-gray",children:[n("groups.editor.permissionsSelected",{count:u.length})," / ",ee]}),r.jsx(De,{size:"sm",variant:"ghost",onClick:B,children:n("groups.editor.selectAll")}),r.jsx(De,{size:"sm",variant:"ghost",onClick:O,children:n("groups.editor.clearAll")})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),r.jsx("input",{type:"text",value:p,onChange:Z=>f(Z.target.value),placeholder:n("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),Y.length===0?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:n("groups.editor.noResults")}):r.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Y.map(Z=>{const ce=S.categories.find(pe=>pe.name===Z.name),de=ce.permissions.filter(pe=>u.includes(pe.value)).length,ue=ce.permissions.length,Q=D(ce),ne=R(ce);return r.jsxs(At,{children:[r.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("button",{type:"button",onClick:()=>P(ce,!Q),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${Q?"bg-bambu-green border-bambu-green":ne?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[Q&&r.jsx(_r,{className:"w-3 h-3 text-white"}),ne&&!Q&&r.jsx(cC,{className:"w-3 h-3 text-white"})]}),r.jsx(gl,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-white font-medium text-sm",children:Z.name})]}),r.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[de,"/",ue]})]}),r.jsx("div",{className:"p-3 space-y-1",children:Z.permissions.map(pe=>r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:u.includes(pe.value),onChange:()=>F(pe.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),r.jsx("span",{className:"text-sm text-bambu-gray",children:pe.label})]},pe.value))})]},Z.name)})}),r.jsx("div",{className:"h-16"}),r.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[r.jsx(De,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:n("common.cancel")}),r.jsx(De,{onClick:j,disabled:T||!o.trim(),children:T?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),n("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(cs,{className:"w-4 h-4"}),n("common.save")]})})]})]})}const zst=1.65,zX=["#1DB954","#3B82F6","#F59E0B","#EF4444","#8B5CF6"];function Aw(t,e,a){return`${t}||${e??""}||${a??""}`}function Gm(t,e){const a=new Date(t);return a.setDate(a.getDate()+Math.round(e)),a}function CS(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function jw(t){return t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Ist(t){if(t.length<2)return null;const e=[...t].sort((c,d)=>new Date(c.created_at).getTime()-new Date(d.created_at).getTime()),a=Date.now(),n=Math.LN2/30,i=[];for(let c=1;cc+d.weight,0);if(s===0)return null;const o=i.reduce((c,d)=>c+d.rate*d.weight,0)/s,l=i.reduce((c,d)=>c+d.weight*(d.rate-o)**2,0)/s;return{rate:o,stdDev:Math.sqrt(l)}}function Ost(t){const e=t.reduce((s,o)=>s+Math.max(0,o.weight_used-(o.weight_used_baseline??0)),0);if(e===0)return null;const a=Date.now(),n=t.reduce((s,o)=>{const l=new Date(o.created_at).getTime();return lre.getAllUsageHistory(5e3),staleTime:6e4,enabled:o}),{data:j=[]}=Qe({queryKey:["shopping-list"],queryFn:re.getShoppingList,staleTime:3e4,enabled:o}),F=N?.forecast_global_lead_time_days??0,P=y.useMemo(()=>{const ce=new Map;for(const de of C)ce.set(Aw(de.material,de.subtype,de.brand),de);return ce},[C]),D=y.useMemo(()=>{const ce=new Map;for(const de of T){const ue=ce.get(de.spool_id)??[];ue.push(de),ce.set(de.spool_id,ue)}return ce},[T]),R=y.useMemo(()=>{const ce=new Map;for(const de of t){if(de.archived_at)continue;const ue=Aw(de.material,de.subtype,de.brand),Q=ce.get(ue)??{key:ue,material:de.material,subtype:de.subtype,brand:de.brand,spools:[]};Q.spools.push(de),ce.set(ue,Q)}return[...ce.values()]},[t]),B=y.useMemo(()=>{const ce=new Date;return ce.setHours(0,0,0,0),R.map(de=>{const ue=P.get(de.key)??null,Q=ue?.lead_time_days??0,ne=Math.max(F,Q),pe=ue?.safety_margin_value??14,me=ue?.safety_margin_unit??"days",be=de.spools.reduce((z,ae)=>z+Math.max(0,ae.label_weight-ae.weight_used),0),q=de.spools.reduce((z,ae)=>z+ae.label_weight,0),J=de.spools.reduce((z,ae)=>z+Math.max(0,ae.weight_used-(ae.weight_used_baseline??0)),0),A=[];for(const z of de.spools)A.push(...D.get(z.id)??[]);let M=null,H=null,W="none";const U=Ist(A);if(U!==null)M=U.rate,H=U.stdDev,W="history";else{const z=Ost(de.spools);z!==null&&(M=z,W="delta")}const se=H??(M!==null?M*.2:0),I=zst*se*Math.sqrt(ne),G=me==="g"?pe:M!==null?M*pe:pe*5,K=I+G,X=M!==null?M*ne+K:0,ie=M&&M>0?Math.floor(be/M):null,oe=ie!==null?Gm(ce,ie):null,he=M&&M>0?Math.floor((be-X)/M):null,le=he!==null?Gm(ce,Math.max(0,he)):null,fe=ie!==null&&ne>0&&ie<=ne,$=!fe&&he!==null&&he<=0;return{group:de,settings:ue,totalRemainingG:be,totalLabelG:q,totalSpools:de.spools.length,totalUsedG:J,dailyRateG:M,dailyRateStdDev:H,rateTier:W,effectiveLeadTimeDays:ne,safetyStockG:K,reorderPointG:X,daysRemaining:ie,daysUntilROP:he,projectedEmptyDate:oe,reorderTriggerDate:le,reorderAlert:$,stockBreakAlert:fe}})},[R,P,D,F]),O=y.useMemo(()=>{const ce=[...B];return ce.sort((de,ue)=>{let Q=0,ne=0;switch(u){case"material":Q=[de.group.material,de.group.subtype??"",de.group.brand??""].join(" ").toLowerCase(),ne=[ue.group.material,ue.group.subtype??"",ue.group.brand??""].join(" ").toLowerCase();break;case"used":Q=de.totalUsedG,ne=ue.totalUsedG;break;case"days_left":Q=de.daysRemaining??999999,ne=ue.daysRemaining??999999;break;case"stock":Q=de.totalRemainingG,ne=ue.totalRemainingG;break}const pe=Qne?1:0;return p==="asc"?pe:-pe}),ce},[B,u,p]),L=y.useMemo(()=>B.filter(ce=>!ce.settings?.alerts_snoozed&&(ce.stockBreakAlert||ce.reorderAlert)),[B]),Y=y.useMemo(()=>[...B].filter(ce=>ce.dailyRateG!==null).sort((ce,de)=>de.totalUsedG-ce.totalUsedG).slice(0,5),[B]);if(!o)return r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray gap-3",children:[r.jsx(cc,{className:"w-8 h-8 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noReadAccess")})]});function ee(ce){u===ce?f(de=>de==="asc"?"desc":"asc"):(m(ce),f(ce==="days_left"?"asc":"desc"))}const Z=j.length>0?j.length:null;return r.jsxs("div",{className:"space-y-5",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[L.length>0&&r.jsxs("button",{onClick:()=>d(ce=>!ce),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors ${L.some(ce=>ce.stockBreakAlert)?"bg-red-500/15 border-red-500/30 text-red-300 hover:bg-red-500/25":"bg-yellow-500/15 border-yellow-500/30 text-yellow-300 hover:bg-yellow-500/25"}`,children:[r.jsx(ga,{className:"w-4 h-4"}),n("forecast.alertCount",{count:L.length}),c?r.jsx(Zo,{className:"w-3.5 h-3.5"}):r.jsx(Fa,{className:"w-3.5 h-3.5"})]}),l&&r.jsx($st,{value:F,onSave:ce=>{re.updateSettings({forecast_global_lead_time_days:ce}).then(()=>{e.invalidateQueries({queryKey:["settings"]}),a(n("forecast.globalLeadTimeSaved"),"success")})}}),r.jsxs("button",{onClick:()=>x(ce=>!ce),className:"relative flex items-center gap-2 px-3 py-1.5 rounded-lg border border-bambu-dark-tertiary text-bambu-gray hover:bg-bambu-dark-tertiary text-sm transition-colors ml-auto",children:[r.jsx(mb,{className:"w-4 h-4"}),r.jsx("span",{className:"hidden sm:inline",children:n("forecast.shoppingList")}),Z&&r.jsx("span",{className:"absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-bambu-green text-white text-[10px] font-bold flex items-center justify-center",children:Z})]})]}),c&&L.length>0&&r.jsx("div",{className:"space-y-2",children:L.map(ce=>r.jsx(Hst,{forecast:ce,onCart:()=>v(ce)},ce.group.key))}),b&&r.jsx(Yst,{items:j,forecasts:B,globalLeadTime:F,canWrite:l,onClose:()=>x(!1),onRemove:ce=>{re.removeFromShoppingList(ce).then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))},onClear:()=>{re.clearShoppingList().then(()=>e.invalidateQueries({queryKey:["shopping-list"]})).catch(()=>a(n("forecast.failedSaveSettings"),"error"))}}),Y.length>0&&r.jsx(Gst,{forecasts:Y,days:S,onDaysChange:k}),B.length===0?r.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-bambu-gray",children:[r.jsx(US,{className:"w-10 h-10 mb-3 opacity-40"}),r.jsx("p",{className:"text-sm",children:n("forecast.noSpools")})]}):r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"w-8 px-4 py-3"}),r.jsx(yN,{col:"material",active:u,dir:p,onSort:ee,children:n("forecast.sku")}),r.jsx(yN,{col:"stock",active:u,dir:p,onSort:ee,children:n("forecast.stock")}),r.jsx(yN,{col:"used",active:u,dir:p,onSort:ee,children:n("forecast.dailyRate")}),r.jsx(yN,{col:"days_left",active:u,dir:p,onSort:ee,children:n("forecast.daysLeft")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.emptyBy")}),r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:n("forecast.reorderBy")}),r.jsx("th",{className:"w-24 px-4 py-3"})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:O.map(ce=>r.jsx(Vst,{forecast:ce,globalLeadTime:F,canWrite:l,onSaved:()=>e.invalidateQueries({queryKey:["sku-settings"]}),onCart:()=>v(ce),showToast:a},ce.group.key))})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-4 px-4 py-3 text-xs text-bambu-gray border-t border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green inline-block"}),n("forecast.trendLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-400 inline-block"}),n("forecast.estimatedLegend")]}),r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-gray/40 inline-block"}),n("forecast.noDataLegend")]})]})]}),g&&r.jsx(Xst,{forecast:g,onClose:()=>v(null),onAdd:ce=>{re.addToShoppingList(ce).then(()=>{e.invalidateQueries({queryKey:["shopping-list"]}),a(n("forecast.addedToCart"),"success"),v(null),x(!0)}).catch(()=>a(n("forecast.failedAddItem"),"error"))}})]})}function yN({col:t,active:e,dir:a,onSort:n,children:i}){const s=e===t;return r.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide cursor-pointer select-none hover:text-white transition-colors",onClick:()=>n(t),children:r.jsxs("span",{className:"inline-flex items-center",children:[i,s?a==="asc"?r.jsx(Vm,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(Wh,{className:"w-3 h-3 ml-1 text-bambu-green"}):r.jsx(TT,{className:"w-3 h-3 ml-1 opacity-40"})]})})}function Hst({forecast:t,onCart:e}){const{t:a}=wt(),n=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),i=t.stockBreakAlert;return r.jsxs("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border text-sm ${i?"bg-red-500/10 border-red-500/30 text-red-300":"bg-yellow-500/10 border-yellow-500/30 text-yellow-300"}`,children:[r.jsx(ga,{className:"w-4 h-4 flex-shrink-0"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"font-medium",children:n}),i?r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.stockBreakRisk")," — ",a("forecast.stockBreakDetail",{days:t.daysRemaining,lt:t.effectiveLeadTimeDays})]}):r.jsxs("span",{className:"ml-2 text-xs opacity-80",children:[a("forecast.reorderNow")," — ",a("forecast.reorderTriggerPassed",{date:t.reorderTriggerDate?CS(t.reorderTriggerDate):"—"})]})]}),r.jsxs("button",{onClick:e,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-current text-xs opacity-70 hover:opacity-100 transition-opacity",children:[r.jsx(mb,{className:"w-3 h-3"})," ",a("forecast.order")]})]})}const qst=[{label:"1W",value:7},{label:"1M",value:30},{label:"6M",value:180}];function Gst({forecasts:t,days:e,onDaysChange:a}){const{t:n}=wt(),i=Array.from({length:e+1},(u,m)=>m),s=t.map((u,m)=>({key:u.group.key,label:[u.group.brand,u.group.material,u.group.subtype].filter(Boolean).join(" "),color:zX[m%zX.length],rop:u.reorderPointG,points:Bst(u,e)})),o=i.map(u=>{const m={day:u,label:jw(Gm(new Date,u))};for(const p of s){const f=p.points.find(g=>g.day===u);m[p.key]=f?.stock??0}return m}),l=(()=>{for(let u=e;u>=0;u--)if(s.some(m=>o[u]?.[m.key]>0))return u;return e})(),c=o.slice(0,l+1),d=s.filter(u=>u.rop>0);return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[r.jsx(US,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:n("forecast.chartTitle")}),r.jsx("span",{className:"text-xs text-bambu-gray ml-1 hidden sm:inline",children:n("forecast.dashedLinesROP")}),r.jsx("div",{className:"ml-auto flex items-center bg-bambu-dark-tertiary rounded-lg p-0.5",children:qst.map(u=>r.jsx("button",{onClick:()=>a(u.value),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${e===u.value?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:u.label},u.value))})]}),r.jsx(nu,{width:"100%",height:220,children:r.jsxs(_B,{data:c,margin:{top:4,right:8,bottom:0,left:0},children:[r.jsx("defs",{children:s.map(u=>r.jsxs("linearGradient",{id:`grad-${u.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"5%",stopColor:u.color,stopOpacity:.25}),r.jsx("stop",{offset:"95%",stopColor:u.color,stopOpacity:.02})]},u.key))}),r.jsx(jm,{strokeDasharray:"3 3",stroke:"#374151",strokeOpacity:.5}),r.jsx(Mm,{dataKey:"label",tick:{fill:"#6B7280",fontSize:10},interval:Math.max(0,Math.ceil(l/8)-1),axisLine:!1,tickLine:!1}),r.jsx(Em,{tick:{fill:"#6B7280",fontSize:10},axisLine:!1,tickLine:!1,tickFormatter:u=>u>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:48}),r.jsx(su,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:12},labelStyle:{color:"#9CA3AF"},itemStyle:{color:"#E5E7EB"},formatter:(u,m)=>{if(typeof u!="number")return"";const p=s.find(f=>f.key===String(m));return`${u}g — ${p?.label??m}`}}),r.jsx(KO,{formatter:u=>{const m=s.find(p=>p.key===u);return r.jsx("span",{style:{color:"#9CA3AF",fontSize:11},children:m?.label??u})}}),s.map(u=>r.jsx(GA,{type:"monotone",dataKey:u.key,stroke:u.color,strokeWidth:2,fill:`url(#grad-${u.key})`,dot:!1,activeDot:{r:3}},u.key)),d.map(u=>r.jsx(ou,{y:u.rop,stroke:u.color,strokeDasharray:"4 3",strokeOpacity:.6},`rop-${u.key}`))]})})]})}function $st({value:t,onSave:e}){const{t:a}=wt(),[n,i]=y.useState(!1),[s,o]=y.useState(String(t));function l(){const c=parseInt(s,10);isNaN(c)||c<0||(e(c),i(!1))}return r.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-bambu-dark-tertiary/40 rounded-lg border border-bambu-dark-tertiary text-xs text-bambu-gray",children:[r.jsx(ji,{className:"w-3.5 h-3.5 flex-shrink-0","aria-label":a("forecast.globalLeadTimeHint")}),r.jsxs("span",{className:"hidden sm:inline",children:[a("forecast.globalLeadTime"),":"]}),n?r.jsxs("form",{className:"flex items-center gap-1.5",onSubmit:c=>{c.preventDefault(),l()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:c=>o(c.target.value),className:"w-14 px-1.5 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0}),r.jsx("span",{className:"text-bambu-gray",children:"d"}),r.jsx("button",{type:"submit",className:"px-2 py-0.5 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80",children:a("forecast.save")}),r.jsx("button",{type:"button",onClick:()=>i(!1),className:"text-xs text-bambu-gray hover:text-white",children:"✕"})]}):r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("span",{className:"font-semibold text-white",children:[t,"d"]}),r.jsx("button",{onClick:()=>{o(String(t)),i(!0)},className:"p-0.5 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(bc,{className:"w-3 h-3"})})]})]})}function Vst({forecast:t,globalLeadTime:e,canWrite:a,onSaved:n,onCart:i,showToast:s}){const{t:o}=wt(),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),[f,g]=y.useState(String(t.settings?.lead_time_days??0)),[v,b]=y.useState(String(t.settings?.safety_margin_value??14)),[x,S]=y.useState(t.settings?.safety_margin_unit??"days");y.useEffect(()=>{d||g(String(t.settings?.lead_time_days??0))},[t.settings?.lead_time_days,d]),y.useEffect(()=>{m||(b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"))},[t.settings?.safety_margin_value,t.settings?.safety_margin_unit,m]);const k=lt({mutationFn:re.upsertSkuSettings,onSuccess:()=>{n(),s(o("forecast.settingsSaved"),"success")},onError:()=>s(o("forecast.failedSaveSettings"),"error")}),N=t.settings?.alerts_snoozed??!1,C=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),T=t.group.spools[0]?.rgba?jl(t.group.spools[0].rgba):{backgroundColor:"#4B5563"},j=t.totalLabelG>0?Math.round(t.totalRemainingG/t.totalLabelG*100):0,F=N||t.daysRemaining===null?"text-bambu-gray":t.stockBreakAlert?"text-red-400":t.reorderAlert||t.daysRemaining<30?"text-yellow-400":"text-green-400";function P(O,L,Y,ee=N){k.mutate({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,lead_time_days:O,safety_margin_value:L,safety_margin_unit:Y,alerts_snoozed:ee})}function D(O){O.stopPropagation(),P(t.settings?.lead_time_days??0,t.settings?.safety_margin_value??14,t.settings?.safety_margin_unit??"days",!N)}const R=t.rateTier==="history"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-green/15 text-bambu-green",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),o("forecast.trend")]}):t.rateTier==="delta"?r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-400/15 text-blue-400",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-400"}),o("forecast.estimated")]}):r.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray/60",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-gray/40"}),o("forecast.noData")]}),B=N?"":t.stockBreakAlert?"bg-red-500/5":t.reorderAlert?"bg-yellow-500/5":"";return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{className:`cursor-pointer hover:bg-bambu-dark-tertiary/40 transition-colors ${B} ${N?"opacity-50":""}`,onClick:()=>c(O=>!O),children:[r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"block w-3 h-3 rounded-full border border-black/20",style:T})}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm font-medium text-white",children:C}),r.jsx("div",{className:"text-xs text-bambu-gray",children:o("forecast.spoolCount",{count:t.totalSpools})})]}),r.jsxs("td",{className:"px-4 py-3 min-w-[120px]",children:[r.jsx("div",{className:"h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden mb-1 w-24",children:r.jsx("div",{className:`h-full rounded-full ${j>50?"bg-bambu-green":j>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(j,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(t.totalRemainingG),"g"]})]}),r.jsxs("td",{className:"px-4 py-3",children:[r.jsx("div",{className:"text-sm text-white",children:t.dailyRateG!==null?`${t.dailyRateG.toFixed(1)}g/d`:"—"}),r.jsx("div",{className:"mt-0.5",children:R})]}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-semibold ${F}`,children:t.daysRemaining!==null?`${t.daysRemaining}d`:r.jsx("span",{className:"text-bambu-gray font-normal",children:"—"})})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:t.projectedEmptyDate?CS(t.projectedEmptyDate):"—"})}),r.jsx("td",{className:"px-4 py-3",children:r.jsx("span",{className:`text-sm font-medium ${!N&&t.reorderAlert?"text-yellow-400":"text-bambu-gray"}`,children:t.reorderTriggerDate?CS(t.reorderTriggerDate):"—"})}),r.jsx("td",{className:"px-4 py-3",onClick:O=>O.stopPropagation(),children:r.jsxs("div",{className:"flex items-center justify-end gap-1",children:[a&&r.jsx("button",{onClick:i,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:o("forecast.addToCart"),children:r.jsx(mb,{className:"w-4 h-4"})}),!N&&(t.stockBreakAlert?r.jsx(ga,{className:"w-4 h-4 text-red-400","aria-label":o("forecast.stockBreakRisk")}):t.reorderAlert?r.jsx(ga,{className:"w-4 h-4 text-yellow-400","aria-label":o("forecast.reorderNow")}):t.daysRemaining!==null?r.jsx(_r,{className:"w-4 h-4 text-bambu-green/50"}):null),a&&r.jsx("button",{onClick:D,className:`p-1 rounded transition-colors ${N?"text-bambu-gray/70 hover:text-white":"text-bambu-dark-tertiary hover:text-bambu-gray"}`,title:o(N?"forecast.alertsEnabled":"forecast.alertsSnoozed"),children:r.jsx(WZ,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:O=>{O.stopPropagation(),c(L=>!L)},className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",children:l?r.jsx(Zo,{className:"w-4 h-4"}):r.jsx(Fa,{className:"w-4 h-4"})})]})})]}),l&&r.jsx("tr",{className:"bg-bambu-dark-tertiary/10",children:r.jsx("td",{colSpan:8,className:"px-6 py-4",children:r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[r.jsx(AL,{label:o("forecast.effectiveLeadTime"),value:`${t.effectiveLeadTimeDays}d`,hint:o("forecast.effectiveLeadTimeHint",{global:e,sku:t.settings?.lead_time_days??0})}),r.jsx(AL,{label:o("forecast.safetyMarginLabel"),value:`${Math.round(t.safetyStockG)}g`,hint:o("forecast.safetyMarginHint")}),r.jsx(AL,{label:o("forecast.reorderPoint"),value:`${Math.round(t.reorderPointG)}g`,hint:o("forecast.reorderPointHint")})]}),a&&r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[r.jsx(Wst,{label:o("forecast.skuLeadTimeOverride"),hint:o("forecast.skuLeadTimeHint"),unit:o("forecast.leadTime"),editing:d,value:t.settings?.lead_time_days??0,inputValue:f,onInputChange:g,onEdit:()=>{g(String(t.settings?.lead_time_days??0)),u(!0)},onSave:()=>{const O=parseInt(f,10);!isNaN(O)&&O>=0&&(P(O,t.settings?.safety_margin_value??14,x),u(!1))},onCancel:()=>u(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel")}),r.jsx(Kst,{value:t.settings?.safety_margin_value??14,unit:x,editing:m,inputValue:v,dailyRateG:t.dailyRateG,onInputChange:b,onUnitChange:O=>S(O),onEdit:()=>{b(String(t.settings?.safety_margin_value??14)),S(t.settings?.safety_margin_unit??"days"),p(!0)},onSave:()=>{const O=parseInt(v,10);!isNaN(O)&&O>=0&&(P(t.settings?.lead_time_days??0,O,x),p(!1))},onCancel:()=>p(!1),isPending:k.isPending,saveLabel:o("forecast.save"),cancelLabel:o("forecast.cancel"),safetyMarginLabel:o("forecast.safetyMarginLabel")})]}),t.group.spools.length>1&&r.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:o("forecast.individualSpools")}),r.jsx("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:"#"}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.remaining")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.used")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("forecast.labelWeight")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.group.spools.map(O=>{const L=Math.max(0,O.label_weight-O.weight_used),Y=O.label_weight>0?L/O.label_weight*100:0;return r.jsxs("tr",{className:"hover:bg-bambu-dark-tertiary/30 transition-colors",children:[r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-xs font-mono text-bambu-gray/70",children:["#",O.id]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("div",{className:"w-24 h-1.5 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0",children:r.jsx("div",{className:`h-full rounded-full ${Y>50?"bg-bambu-green":Y>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(Y,100)}%`}})}),r.jsxs("span",{className:"text-sm text-white",children:[Math.round(L),"g"]})]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[Math.round(Math.max(0,O.weight_used-(O.weight_used_baseline??0))),"g"]})}),r.jsx("td",{className:"px-4 py-2",children:r.jsxs("span",{className:"text-sm text-bambu-gray",children:[O.label_weight,"g"]})})]},O.id)})})]})})]})]})})})]})}function AL({label:t,value:e,hint:a}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3",title:a,children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-1",children:t}),r.jsx("div",{className:"text-lg font-semibold text-white",children:e})]})}function Wst({label:t,hint:e,unit:a,editing:n,value:i,inputValue:s,onInputChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel"}){return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:t}),r.jsx("span",{title:e,children:r.jsx(ji,{className:"w-3 h-3 text-bambu-gray/50"})})]}),n?r.jsxs("form",{className:"flex items-center gap-2",onSubmit:f=>{f.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:365,value:s,onChange:f=>o(f.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:i}),r.jsx("span",{className:"text-xs text-bambu-gray",children:a}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(bc,{className:"w-3 h-3"})})]})]})}function Kst({value:t,unit:e,editing:a,inputValue:n,dailyRateG:i,onInputChange:s,onUnitChange:o,onEdit:l,onSave:c,onCancel:d,isPending:u,saveLabel:m="Save",cancelLabel:p="Cancel",safetyMarginLabel:f="Safety Margin"}){const{t:g}=wt(),v=e==="g"?t:i!==null?Math.round(i*t):null,b=e==="days"?g("forecast.safetyMarginHintDays",{approx:v!==null?g("forecast.safetyMarginHintDaysApprox",{g:v}):""}):g("forecast.safetyMarginHintG",{approx:i!==null?g("forecast.safetyMarginHintGApprox",{days:Math.round(t/i)}):""});return r.jsxs("div",{className:"bg-bambu-dark-tertiary/40 rounded-lg p-3 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-xs font-medium text-white",children:f}),r.jsx("span",{title:b,children:r.jsx(ji,{className:"w-3 h-3 text-bambu-gray/50"})})]}),a?r.jsxs("form",{className:"flex items-center gap-2 flex-wrap",onSubmit:x=>{x.preventDefault(),c()},children:[r.jsx("input",{type:"number",min:0,max:e==="g"?1e4:365,value:n,onChange:x=>s(x.target.value),className:"w-20 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",autoFocus:!0,disabled:u}),r.jsxs("div",{className:"flex bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded overflow-hidden text-xs",children:[r.jsx("button",{type:"button",onClick:()=>o("days"),className:`px-2 py-1 transition-colors ${e==="days"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"days"}),r.jsx("button",{type:"button",onClick:()=>o("g"),className:`px-2 py-1 transition-colors ${e==="g"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"g"})]}),r.jsx("button",{type:"submit",disabled:u,className:"px-2 py-1 bg-bambu-green text-white text-xs rounded hover:bg-bambu-green/80 disabled:opacity-50",children:m}),r.jsx("button",{type:"button",onClick:d,disabled:u,className:"px-2 py-1 text-xs text-bambu-gray hover:text-white",children:p})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-lg font-semibold text-white",children:t}),r.jsx("span",{className:"text-xs text-bambu-gray",children:e}),v!==null&&e==="days"&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",v,"g"]}),e==="g"&&i!==null&&r.jsxs("span",{className:"text-xs text-bambu-gray/60",children:["≈ ",Math.round(t/i),"d"]}),r.jsx("button",{onClick:l,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(bc,{className:"w-3 h-3"})})]})]})}function Yst({items:t,forecasts:e,globalLeadTime:a,canWrite:n,onClose:i,onRemove:s,onClear:o}){const{t:l}=wt(),c=aa(),[d,u]=y.useState("list"),m=lt({mutationFn:async({id:b,status:x,item:S,avgSpoolG:k})=>{if(await re.updateShoppingListStatus(b,x),x==="received"&&S){const N=k??1e3,C={material:S.material,subtype:S.subtype,brand:S.brand,label_weight:N,core_weight:0,core_weight_catalog_id:null,color_name:null,rgba:null,extra_colors:null,effect_type:null,nozzle_temp_min:null,nozzle_temp_max:null,note:S.note??null,tag_uid:null,tray_uuid:null,data_origin:"manual",tag_type:null,cost_per_kg:null,last_scale_weight:null,last_weighed_at:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,added_full:null,last_used:null,encode_time:null,category:"Stock",low_stock_threshold_pct:null};await re.bulkCreateSpools(C,S.quantity_spools),await re.removeFromShoppingList(b)}},onSuccess:()=>{c.invalidateQueries({queryKey:["shopping-list"]}),c.invalidateQueries({queryKey:["spools"]})}}),p=y.useMemo(()=>{const b=new Map;for(const x of e)b.set(x.group.key,x);return b},[e]),f=y.useMemo(()=>t.map(b=>({item:b,forecast:p.get(Aw(b.material,b.subtype,b.brand))??null})),[t,p]),g=y.useMemo(()=>f.filter(({forecast:b})=>!b||b.dailyRateG===null?!1:b.stockBreakAlert||b.daysRemaining!==null&&b.daysRemaining<=b.effectiveLeadTimeDays),[f]);function v(){const b=[l("forecast.qty"),l("forecast.material"),"Brand","Subtype",`${l("forecast.weight")} (g)`,`${l("forecast.leadTime")} (d)`,l("forecast.expectedRestock"),l("forecast.status"),l("forecast.note")],x=t.map(T=>{const j=p.get(Aw(T.material,T.subtype,T.brand))??null,F=j&&j.totalSpools>0?j.totalLabelG/j.totalSpools:1e3,P=Math.round(T.quantity_spools*F),D=j?.effectiveLeadTimeDays??a??0,R=D>0?CS(Gm(new Date,D)):"";return[T.quantity_spools,T.material,T.brand??"",T.subtype??"",P,D||"",R,T.status,T.note??""].map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")}),S=[b.join(","),...x].join(` -`),k=new Blob([S],{type:"text/csv"}),N=URL.createObjectURL(k),C=document.createElement("a");C.href=N,C.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,C.click(),setTimeout(()=>URL.revokeObjectURL(N),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(mb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(qr,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Nge,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Ur,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),n&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Gt,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(qr,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(R=>R.item.id===b.id),k=p.get(Aw(b.material,b.subtype,b.brand))??null,N=k&&k.totalSpools>0?k.totalLabelG/k.totalSpools:1e3,C=Math.round(b.quantity_spools*N),T=k?.effectiveLeadTimeDays??a??0,j=T>0?Gm(new Date,T):null,F=b.status==="purchased"||b.status==="received",P=b.status==="received",D=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!F&&r.jsx(ga,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:C>=1e3?`${(C/1e3).toFixed(1)}kg`:`${C}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:j?CS(j):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${P?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(P?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:n&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:D||P,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(hs,{className:"w-3.5 h-3.5"}):r.jsx(pbe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:N}),disabled:D||!F||P,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(bye,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(ta,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(Qst,{item:b,forecast:x,globalLeadTime:a,canWrite:n,onRemove:()=>s(b.id)},b.id))})]})}function Qst({item:t,forecast:e,globalLeadTime:a,canWrite:n,onRemove:i}){const{t:s}=wt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),v=g+f,b=Math.ceil(v/u),x=Math.min(m+b+5,365),S=[];for(let k=0;k<=x;k++){const N=jw(Gm(new Date,k));if(k===m)S.push({day:k,label:N,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:k,label:N,stock:Math.round(v),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const C=k{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(su,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(GA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ou,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ou,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ou,{x:jw(Gm(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ou,{x:jw(Gm(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Xst({forecast:t,onClose:e,onAdd:a}){const{t:n}=wt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,k)=>S+k.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function v(b){b.preventDefault(),a({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(mb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:n("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:v,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:n("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:n("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:n("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:n("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:n("forecast.cancel")})]})]})]})})}const uI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},Zst=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function gde(t,e=!1,a=!1){const n={};return e||a?(!t.material&&!t.spoolman_filament_id&&(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const bde=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Jst=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],Mw=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","CF","GF","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],xde=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"},{name:"Clear",hex:"00000000"}],eot=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],IX=[...xde,...eot],yde="bambuddy-recent-colors",tot=8,aot=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function sf(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const a=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let n="",i=-1;for(const c of a){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){n=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&n&&(o=e.substring(i+n.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of Mw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of Mw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:n,variant:l}}function vde(t,e){const a=new Set(Jst);for(const n of t){const{brand:i}=sf(n.name);i&&i.length>1&&a.add(i)}if(e)for(const n of e)if(n.filament_vendor&&n.filament_vendor.length>1)a.add(n.filament_vendor);else{const{brand:i}=sf(n.name);i&&i.length>1&&a.add(i)}return Array.from(a).sort((n,i)=>n.localeCompare(i))}function rot(t){const e=t.filter(n=>n.preset_type==="filament");return e.length===0?[]:e.map(n=>{const i=String(n.id),s=n.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:n.name,displayName:n.name,isCustom:!1,allCodes:o}}).sort((n,i)=>n.displayName.localeCompare(i.displayName))}function wde(t,e,a,n){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=a&&a.length>0?rot(a):[],c=[];if(n&&n.length>0)for(const u of n){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?aot:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Sde(t,e){if(!t)return;let a=e.find(n=>n.code===t);if(a||(a=e.find(n=>n.allCodes.includes(t))),!a){const n=t.toLowerCase();a=e.find(i=>i.code.toLowerCase()===n||i.allCodes.some(s=>s.toLowerCase()===n))}return a}function kde(){try{const t=localStorage.getItem(yde);if(t)return JSON.parse(t)}catch{}return[]}function _de(t,e){const a=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),n=[t,...a].slice(0,tot);try{localStorage.setItem(yde,JSON.stringify(n))}catch{}return n}function jL(t,e){if(!e.material)return!1;const n=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=sf(n);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||n.toLowerCase().includes(e.subtype.toLowerCase())))}function Pde({formData:t,updateField:e,cloudAuthenticated:a,loadingCloudPresets:n,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=wt(),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,N]=y.useState(!1),[C,T]=y.useState(!1),[j,F]=y.useState(""),[P,D]=y.useState(""),[R,B]=y.useState(""),[O,L]=y.useState(String(t.label_weight)),[Y,ee]=y.useState(!1),Z=y.useRef(null),ce=y.useRef(null),de=y.useRef(null),ue=y.useRef(null);y.useEffect(()=>{const q=J=>{Z.current&&!Z.current.contains(J.target)&&b(!1),ue.current&&!ue.current.contains(J.target)&&T(!1),ce.current&&!ce.current.contains(J.target)&&S(!1),de.current&&!de.current.contains(J.target)&&N(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const Q=y.useMemo(()=>{if(!i)return l;const q=i.toLowerCase();return l.filter(J=>J.displayName.toLowerCase().includes(q)||J.code.toLowerCase().includes(q))},[l,i]),ne=y.useMemo(()=>{if(!j)return c;const q=j.toLowerCase();return c.filter(A=>A.toLowerCase().includes(q)).sort((A,M)=>{const H=A.toLowerCase()===q,W=M.toLowerCase()===q;return H&&!W?-1:!H&&W?1:A.localeCompare(M)})},[c,j]),pe=y.useMemo(()=>{if(!P)return Mw;const q=P.toLowerCase();return Mw.filter(J=>J.toLowerCase().includes(q))},[P]),me=y.useMemo(()=>{if(!R)return d;const q=R.toLowerCase();return d.filter(A=>A.toLowerCase().includes(q)).sort((A,M)=>{const H=A.toLowerCase()===q,W=M.toLowerCase()===q;return H&&!W?-1:!H&&W?1:A.localeCompare(M)})},[R,d]);y.useEffect(()=>{Y||L(String(t.label_weight))},[t.label_weight,Y]);const be=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const J=sf(q.name);J.material&&e("material",J.material),J.brand&&e("brand",J.brand),J.variant&&e("subtype",J.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:n?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):a?r.jsxs(r.Fragment,{children:[r.jsx(Kh,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(t3,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:Z,children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchPresets"),value:i,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:Q.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):Q.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>be(q),children:q.displayName},`${q.code}::${q.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.selectMaterial"),value:C?R:t.material,onChange:q=>{B(q.target.value),T(!0)},onFocus:()=>{T(!0),B("")}}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):me.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),T(!1),B("")},children:q},q)),R&&!me.includes(R)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",R),T(!1),B("")},children:g("inventory.useCustomMaterial",{material:R})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchBrand"),value:x?j:t.brand,onChange:q=>{F(q.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ne.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ne.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),S(!1),F("")},children:q},q)),j&&!ne.includes(j)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",j),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:j})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:de,children:[r.jsx("input",{type:"text",value:k?P:t.subtype,onChange:q=>{D(q.target.value),N(!0)},onFocus:()=>{N(!0),D("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):pe.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),N(!1),D("")},children:q},q)),P&&!Mw.some(q=>q.toLowerCase()===P.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",P),N(!1),D("")},children:g("inventory.useCustomBrand",{brand:P})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:O,min:0,onFocus:()=>ee(!0),onChange:q=>L(q.target.value),onBlur:()=>{ee(!1);const q=O.trim(),J=Number(q);if(!q||!Number.isFinite(J)||J<0){L(String(t.label_weight));return}const A=Math.round(J);e("label_weight",A),L(String(A))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const J=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(J)}})]})]})}function not(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),a=[],n=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?a.push(i.toLowerCase()):n.push(i);return{value:a.join(","),invalid:n}}function Nde({formData:t,updateField:e,recentColors:a,onColorUsed:n,catalogColors:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=(t.rgba.replace("#","")+"FF").substring(0,8).toUpperCase(),m=u.substring(0,6),f=u.substring(6,8)==="00",[g,v]=y.useState(f?u:m);y.useEffect(()=>{v(f?u:m)},[m,u,f]);const b=L=>{const Y=(L.replace("#","")+"FF").substring(0,8).toUpperCase();return u===Y},x=L=>jl(L),S=(L,Y,ee,Z)=>{const ce=L.replace("#","").toUpperCase(),de=ce.length===8?ce:ce+"FF";if(e("rgba",de),e("color_name",Y),ee!==void 0){const ue=ee??"";F(ue),D([]),R.current=ue,e("extra_colors",ue)}Z!==void 0&&e("effect_type",Z??""),n({name:Y,hex:L})},k=y.useMemo(()=>{if(i.length===0)return[];const L=t.brand?.trim(),Y=t.material?.toLowerCase().trim(),ee=t.subtype?.toLowerCase().trim();if(!L&&!Y)return[];const Z=L?L.toLowerCase().split(/[\s\-_]+/).filter(ue=>ue.length>=2):[],ce=ue=>{if(Z.length===0)return!0;const Q=ue.toLowerCase();return Z.some(ne=>Q.includes(ne))};if(L&&!Y){const ue=i.filter(Q=>ce(Q.manufacturer));if(ue.length>0)return ue.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}const de=Y&&ee?`${Y} ${ee}`:"";if(de){const ue=i.filter(ne=>ce(ne.manufacturer)&&ne.material?.toLowerCase()===de);if(ue.length>0)return ue.map(ne=>({name:ne.color_name,hex:ne.hex_color.replace("#","").substring(0,6),manufacturer:ne.manufacturer,material:typeof ne.material=="string"?ne.material:void 0,extra_colors:ne.extra_colors??null,effect_type:ne.effect_type??null}));const Q=de.replace(/\+$/,"");if(Q!==de){const ne=i.filter(pe=>ce(pe.manufacturer)&&pe.material?.toLowerCase()===Q);if(ne.length>0)return ne.map(pe=>({name:pe.color_name,hex:pe.hex_color.replace("#","").substring(0,6),manufacturer:pe.manufacturer,material:typeof pe.material=="string"?pe.material:void 0}))}}if(Y){const ue=i.filter(Q=>ce(Q.manufacturer)&&(!Q.material||Q.material.toLowerCase().startsWith(Y)));if(ue.length>0)return ue.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),N=y.useMemo(()=>{if(!c)return k;if(k.length===0)return[];const L=c.toLowerCase();return k.filter(ee=>ee.name.toLowerCase().includes(L)||(ee.manufacturer?.toLowerCase().includes(L)??!1)||(ee.material?.toLowerCase().includes(L)??!1))},[c,k]),C=k.length>0,T=y.useMemo(()=>c?IX.filter(L=>L.name.toLowerCase().includes(c.toLowerCase())):o?IX:xde,[c,o]),[j,F]=y.useState(t.extra_colors),[P,D]=y.useState([]),R=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==R.current&&(F(t.extra_colors),D([]),R.current=t.extra_colors)},[t.extra_colors]);const B=y.useMemo(()=>fj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),O=L=>{if(F(L),!L.trim()){D([]),R.current="",e("extra_colors","");return}const{value:Y,invalid:ee}=not(L);D(ee),R.current=Y,e("extra_colors",Y)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:B,"data-testid":"color-preview-banner"}),a.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(er,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.name},L.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:L=>d(L.target.value)})]}),C?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[N.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name,L.extra_colors,L.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.manufacturer&&L.material?`${L.name} (${L.manufacturer} — ${L.material})`:L.manufacturer?`${L.name} (${L.manufacturer})`:L.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:L.manufacturer&&L.material?`${L.name} (${L.manufacturer} — ${L.material})`:L.manufacturer?`${L.name} (${L.manufacturer})`:L.name})},`${L.hex}-${L.name}-${L.manufacturer??""}`)),N.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(Zo,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Fa,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[T.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:L.name})},L.hex)),T.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:L=>e("color_name",L.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:g.toUpperCase(),onChange:L=>{const Y=L.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase(),ee=Y.length>8?Y.substring(0,8):Y;v(ee),ee.length===6?e("rgba",ee+"FF"):ee.length===8&&e("rgba",ee)},onBlur:()=>{if(g.length===7){const L=g+"0";v(L),e("rgba",L)}else if(g.length>0&&g.length<6){const L=g.padEnd(6,"0");v(L),e("rgba",L+"FF")}}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${m}`,onChange:L=>{const Y=L.target.value.replace("#","").toUpperCase();e("rgba",Y+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:j,onChange:L=>O(L.target.value),"data-testid":"extra-colors-input"}),P.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:P.join(", ")})}),!P.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(zg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:t.effect_type,onChange:L=>e("effect_type",L.target.value),"data-testid":"effect-type-select",children:lI.map(L=>r.jsx("option",{value:L.value,children:s(L.labelKey)},L.value||"none"))}),r.jsx(w5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function iot({catalog:t,value:e,onChange:a,catalogId:n,onCatalogIdChange:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),y.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(n){const b=t.find(x=>x.id===n);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&n!==null&&i(null)},[e,t,n,i]);const p=y.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=y.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(n){const v=t.find(b=>b.id===n);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,n,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(aJ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:g,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(n?v.id===n:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),a(v.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:v.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&a(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Cde({formData:t,updateField:e,spoolCatalog:a,currencySymbol:n,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=wt(),{showToast:c}=sa(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[v,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{v||g(String(x))},[v,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(iot,{catalog:a,value:t.core_weight,onChange:k=>e("core_weight",k),catalogId:t.core_weight_catalog_id,onCatalogIdChange:k=>e("core_weight_catalog_id",k)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:k=>{g(k.target.value)},onBlur:()=>{b(!1);const k=f.trim(),N=Number(k);if(!k||!Number.isFinite(N)||N<0||N>t.label_weight){g(String(x));return}const C=Math.round(N);e("weight_used",Math.max(0,t.label_weight-C)),g(String(C))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:k=>{u(k.target.value)},onBlur:()=>{p(!1);const k=d.trim(),N=Number(k),C=t.core_weight,T=t.core_weight+t.label_weight;if(!k||!Number.isFinite(N)||NT){c(l("inventory.measuredWeightError",{min:C,max:T}),"error"),u(String(S));return}const j=Math.round(N),F=Math.max(0,Math.min(t.label_weight,j-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(j))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:n}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:k=>{const N=k.target.value===""?null:parseFloat(k.target.value);e("cost_per_kg",N)},style:{paddingLeft:`${Math.max(2,n.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:k=>e("category",k.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(k=>r.jsx("option",{value:k},k))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:k=>{const N=k.target.value;if(N===""){e("low_stock_threshold_pct",null);return}const C=Number(N);Number.isFinite(C)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(C))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:k=>e("note",k.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:k=>e("storage_location",k.target.value)})]})]})}function sot({filaments:t,isLoading:e,selectedId:a,onSelect:n}){const{t:i}=wt(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===a)??null,[t,a]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{n(b),o(!1),c("")},v=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(qr,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Fa,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===a?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function Tde({formData:t,printersWithCalibrations:e,selectedProfiles:a,setSelectedProfiles:n,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=wt(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const v=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;n(x=>{const S=new Set(x);if(S.has(v))S.delete(v);else{for(const k of Array.from(S)){const N=k.split(":");`${N[0]}:${N[2]}`===b&&S.delete(k)}S.add(v)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const v=g.filter(x=>jL(x,t)),b=new Map;for(const x of v){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const N=[...S].sort((C,T)=>T.k_value-C.k_value)[0];p.add(`${f.id}:${N.cali_idx}:${x}`)}}n(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(v=>jL(v,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=a.has(g);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(zg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),v=f.filter(N=>jL(N,t)),b=v.length,x=v.some(N=>N.extruder_id!==void 0&&N.extruder_id!==null&&N.extruder_id>0),S=v.filter(N=>N.extruder_id===1),k=v.filter(N=>N.extruder_id===0||N.extruder_id===void 0||N.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(Fa,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(qn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(N=>m(p,N))})]}),k.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:k.map(N=>m(p,N))})]})]}):r.jsx("div",{className:"space-y-2",children:v.map(N=>m(p,N))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),a.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:a.size})," ",o("inventory.profilesSelected")]})})]})}function oot(t){const e=Ia(t);return e?e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}):""}const lot={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function cot({spoolId:t}){const{t:e}=wt(),a=aa(),{showToast:n}=sa(),{data:i,isLoading:s}=Qe({queryKey:["spool-usage",t],queryFn:()=>re.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>re.clearSpoolUsageHistory(t),onSuccess:()=>{a.invalidateQueries({queryKey:["spool-usage",t]}),n(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(er,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(ta,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:oot(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:lot[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const OX={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function dot({isOpen:t,onClose:e,spool:a,mode:n,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=wt(),u=aa(),{showToast:m}=sa(),p=n==="edit",f=n==="copy",[g,v]=y.useState(uI),[b,x]=y.useState({}),[S,k]=y.useState("filament"),[N,C]=y.useState(!1),[T,j]=y.useState(!1),[F,P]=y.useState(!1),[D,R]=y.useState(1),[B,O]=y.useState(!1),[L,Y]=y.useState(!1),[ee,Z]=y.useState([]),[ce,de]=y.useState(""),[ue,Q]=y.useState([]),[ne,pe]=y.useState([]),[me,be]=y.useState([]),[q,J]=y.useState([]),[A,M]=y.useState([]),[H,W]=y.useState([]),[U,se]=y.useState(new Set),[I,G]=y.useState(new Set),K=i.length>0?i:H,X=U.size,{data:ie=[],isLoading:oe,error:he}=Qe({queryKey:["spoolman-inventory-filaments"],queryFn:()=>re.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{M(kde())},[]),y.useEffect(()=>{t&&((async()=>{Y(!0);try{const at=await re.getCloudStatus();if(O(at.is_authenticated),at.is_authenticated){const rt=await re.getFilamentPresets();Z(rt)}}catch(at){console.error("Failed to fetch cloud presets:",at),O(!1)}finally{Y(!1)}})(),l||re.getSpoolCatalog().then(Q).catch(console.error),re.getColorCatalog().then(J).catch(console.error),re.getLocalPresets().then(at=>pe(at.filament)).catch(console.error),re.getBuiltinFilaments().then(be).catch(console.error),i.length===0&&(async()=>{try{const at=await re.getPrinters(),rt=await Promise.all(at.map(Ut=>re.getPrinterStatus(Ut.id).catch(()=>null))),Ct=[];for(let Ut=0;Ut({cali_idx:dt.slot_id,filament_id:dt.filament_id,setting_id:dt.setting_id||"",name:dt.name,k_value:parseFloat(dt.k_value)||0,n_coef:parseFloat(dt.n_coef)||0,extruder_id:dt.extruder_id,nozzle_diameter:dt.nozzle_diameter}))}catch{}Ct.push({printer:{...ft,connected:Zt},calibrations:oa})}W(Ct)}catch(at){console.error("Failed to fetch printer calibrations:",at)}})())},[t,i.length]);const le=y.useMemo(()=>wde(ee,new Set,ne,me),[ee,ne,me]),fe=y.useMemo(()=>{const Ae=vde(ee,ne),at=q.map(Ct=>Ct.manufacturer?.trim()).filter(Ct=>!!Ct),rt=new Set([...Ae,...at]);return Array.from(rt).sort((Ct,Ut)=>Ct.localeCompare(Ut))},[ee,ne,q]),$=y.useMemo(()=>{const Ae=q.map(rt=>rt.material?.trim()).filter(rt=>!!rt),at=new Set([...bde,...Ae]);return Array.from(at).sort((rt,Ct)=>rt.localeCompare(Ct))},[q]),z=y.useMemo(()=>{const Ae=[];for(const at of q){const rt=at.manufacturer?.trim(),Ct=at.material?.trim();rt&&Ct&&Ae.push({brand:rt,material:Ct})}for(const at of ee){const rt=sf(at.name);rt.brand&&rt.material&&Ae.push({brand:rt.brand,material:rt.material})}for(const at of ne){const rt=sf(at.name),Ct=at.filament_vendor?.trim()||rt.brand,Ut=rt.material;Ct&&Ut&&Ae.push({brand:Ct,material:Ut})}return Ae},[ee,q,ne]),ae=y.useMemo(()=>{const Ae=new Map;for(const at of z){const rt=at.brand.toLowerCase(),Ct=at.material.toLowerCase();Ae.has(rt)||Ae.set(rt,new Set),Ae.get(rt).add(Ct)}return Ae},[z]),ge=y.useMemo(()=>{const Ae=new Map;for(const at of z){const rt=at.brand.toLowerCase(),Ct=at.material.toLowerCase();Ae.has(Ct)||Ae.set(Ct,new Set),Ae.get(Ct).add(rt)}return Ae},[z]),xe=y.useMemo(()=>{if(!g.material)return fe;const Ae=g.material.toLowerCase(),at=ge.get(Ae);return!at||at.size===0?fe:fe.filter(rt=>at.has(rt.toLowerCase()))},[fe,g.material,ge]),ve=y.useMemo(()=>{if(!g.brand)return $;const Ae=g.brand.toLowerCase(),at=ae.get(Ae);return!at||at.size===0?$:$.filter(rt=>at.has(rt.toLowerCase()))},[$,g.brand,ae]),je=y.useMemo(()=>Sde(g.slicer_filament,le),[g.slicer_filament,le]);y.useEffect(()=>{if(t){if(a){const Ae=a.rgba&&/^[0-9A-Fa-f]{8}$/.test(a.rgba)?a.rgba:"808080FF";if(v({material:a.material||"",subtype:a.subtype||"",brand:a.brand||"",color_name:a.color_name_is_synthesized?"":a.color_name||"",rgba:Ae,extra_colors:a.extra_colors||"",effect_type:a.effect_type||"",label_weight:a.label_weight||1e3,core_weight:a.core_weight||250,core_weight_catalog_id:a.core_weight_catalog_id??null,weight_used:f?0:a.weight_used||0,slicer_filament:a.slicer_filament||"",note:a.note||"",cost_per_kg:a.cost_per_kg??null,category:a.category||"",low_stock_threshold_pct:a.low_stock_threshold_pct??null,storage_location:a.storage_location||"",spoolman_filament_id:null}),de(a.slicer_filament_name||a.slicer_filament||""),a.k_profiles&&a.k_profiles.length>0){const at=new Set;for(const rt of a.k_profiles)rt.cali_idx!==null&&rt.cali_idx!==void 0&&at.add(`${rt.printer_id}:${rt.cali_idx}:${rt.extruder??"null"}`);se(at)}else se(new Set)}else v(uI),de(""),se(new Set),P(!1),R(1);x({}),k("filament"),C(!1),j(!1)}},[t,a,n,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Ae=>String(Ae.printer.id))))},[t,K]);const Me=(Ae,at)=>{const rt=Zst.has(Ae);l&&rt&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),v(Ct=>({...Ct,[Ae]:at,...l&&rt&&Ct.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Ae==="weight_used"&&C(!0),Ae==="storage_location"&&j(!0),b[Ae]&&x(Ct=>({...Ct,[Ae]:void 0}))},Se=Ae=>{const at=Ae.material||"",rt=Ae.name||"",Ct=at&&rt.startsWith(at)?rt.slice(at.length).trim():rt,Ut=(Ae.color_hex??"").replace("#","").toUpperCase(),ft=/^[0-9A-F]{6}$/.test(Ut)?Ut:"808080";v(Kt=>({...Kt,spoolman_filament_id:Ae.id,material:at,subtype:Ct,brand:Ae.vendor?.name||"",rgba:`${ft}FF`,color_name:Ae.color_name||"",label_weight:Ae.weight??Kt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},Ue=Ae=>{M(at=>_de(Ae,at))},_e=lt({mutationFn:Ae=>l?re.createSpoolmanInventorySpool(Ae):re.createSpool(Ae),onSuccess:async Ae=>{Ae?.id&&!await Ie(Ae.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Ae]),m(d("inventory.spoolCreated"),"success"),e())},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),ze=lt({mutationFn:({data:Ae,qty:at})=>l?re.bulkCreateSpoolmanInventorySpools(Ae,at):re.bulkCreateSpools(Ae,at),onSuccess:async Ae=>{const at=l&&"created"in Ae?Ae:null,rt=at?at.created:Ae;if(U.size>0)for(const Ct of rt)await Ie(Ct.id);await u.invalidateQueries({queryKey:c}),o&&o(rt),at&&at.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:rt.length,total:at.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:rt.length}),"success"),e()},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Fe=lt({mutationFn:Ae=>l?re.updateSpoolmanInventorySpool(a.id,Ae):re.updateSpool(a.id,Ae),onSuccess:async()=>{a?.id&&!await Ie(a.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),qe=lt({mutationFn:()=>l?re.updateSpoolmanInventorySpool(a.id,OX):re.updateSpool(a.id,OX),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:Oe}=Qe({queryKey:["spool-assignments"],queryFn:()=>re.getAssignments(),enabled:t&&p&&!l}),{data:it}=Qe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>re.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Le=(()=>{if(a)return l?it?.find(Ae=>Ae.spoolman_spool_id===a.id):Oe?.find(Ae=>Ae.spool_id===a.id)})(),{data:st}=Qe({queryKey:["inventory-spools"],queryFn:()=>re.getSpools(!0),enabled:t}),{data:Te}=Qe({queryKey:["settings"],queryFn:re.getSettings,enabled:t}),Xe=(()=>{const Ae=new Set;for(const at of st??[]){const rt=at.category?.trim();rt&&Ae.add(rt)}return Array.from(Ae).sort((at,rt)=>at.localeCompare(rt))})(),$e=Te?.low_stock_threshold??20,Ne=lt({mutationFn:async()=>{if(!Le)throw new Error("No assignment");if(l){if(!a)throw new Error("No spool");await re.unassignSpoolmanSlot(a.id);return}await re.unassignSpool(Le.printer_id,Le.ams_id,Le.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ae=>{m(Ae.message,"error")}}),Ie=async Ae=>{const at=l?re.saveSpoolmanKProfiles:re.saveSpoolKProfiles;if(U.size===0)try{return await at(Ae,[]),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const rt=[];let Ct=0;for(const Ut of U){const[ft,Kt,Zt]=Ut.split(":"),oa=parseInt(ft),xa=parseInt(Kt),dt=Zt==="null"?0:parseInt(Zt),vt=K.find(Pt=>Pt.printer.id===oa);if(vt){const Pt=vt.calibrations.find(Nt=>Nt.cali_idx===xa);Pt?rt.push({printer_id:oa,extruder:dt,nozzle_diameter:Pt.nozzle_diameter||"0.4",k_value:Pt.k_value,name:Pt.name||null,cali_idx:Pt.cali_idx,setting_id:Pt.setting_id||null}):Ct++}else Ct++}if(Ct>0)return console.error(`saveKProfiles: ${Ct} profile key(s) could not be resolved`,Array.from(U)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(rt.length>0)try{return await at(Ae,rt),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Ae=at=>{at.key==="Escape"&&e()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[t,e]),!t)return null;const et=()=>{const Ae=gde(g,F,l);if(!Ae.isValid){x(Ae.errors),(Ae.errors.slicer_filament||Ae.errors.material||Ae.errors.brand||Ae.errors.subtype)&&k("filament");return}const at=je?.displayName||ce||null,rt={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:at,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||N)&&(rt.weight_used=g.weight_used),(!p||T)&&(rt.storage_location=g.storage_location||null),p?Fe.mutate(rt):D>1?ze.mutate({data:rt,qty:D}):_e.mutate(rt)},We=_e.isPending||ze.isPending||Fe.isPending||qe.isPending||Ne.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-baseline gap-2",children:[d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool"),p&&a&&r.jsxs("span",{className:"text-sm font-mono text-bambu-gray",children:["#",a.id]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),n==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{P(!F),F||k("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>k("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(RS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>k("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(rge,{className:"w-4 h-4"}),d("inventory.paProfileTab"),X>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:X})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:he?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(sot,{filaments:ie,isLoading:oe,selectedId:g.spoolman_filament_id,onSelect:Se})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Pde,{formData:g,updateField:Me,cloudAuthenticated:B,loadingCloudPresets:L,presetInputValue:ce,setPresetInputValue:de,selectedPresetOption:je,filamentOptions:le,availableBrands:xe,availableMaterials:ve,quickAdd:F,quantity:D,onQuantityChange:R,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Nde,{formData:g,updateField:Me,recentColors:A,onColorUsed:Ue,catalogColors:q})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Cde,{formData:g,updateField:Me,spoolCatalog:ue,currencySymbol:s,availableCategories:Xe,globalLowStockThreshold:$e,spoolmanMode:l})]}),p&&a&&!l&&r.jsx("div",{children:r.jsx(cot,{spoolId:a.id})})]}):r.jsx(Tde,{formData:g,updateField:Me,printersWithCalibrations:K,selectedProfiles:U,setSelectedProfiles:se,expandedPrinters:I,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(De,{variant:"secondary",onClick:()=>qe.mutate(),disabled:We||!a?.tag_uid,children:[r.jsx(Km,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(De,{variant:"secondary",onClick:()=>Ne.mutate(),disabled:We||!Le,children:[r.jsx(cu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(De,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(De,{onClick:et,disabled:We,children:We?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(cs,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function uot({isOpen:t,onClose:e,columns:a,defaultColumns:n,onSave:i}){const{t:s}=wt(),[o,l]=y.useState(a),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(a.map(N=>({...N})))},[t,a]),y.useEffect(()=>{if(!t)return;const N=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t,e]),!t)return null;const m=N=>{l(C=>C.map((T,j)=>j===N?{...T,visible:!T.visible}:T))},p=(N,C)=>{C<0||C>=o.length||l(T=>{const j=[...T],[F]=j.splice(N,1);return j.splice(C,0,F),j})},f=(N,C)=>{u.current=C,d(C),N.dataTransfer.effectAllowed="move"},g=(N,C)=>{N.preventDefault(),N.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==C&&(p(T,C),u.current=C,d(C))},v=N=>{N.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(n.map(N=>({...N})))},S=()=>{i(o),e()},k=o.filter(N=>N.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:N=>N.stopPropagation(),children:r.jsxs(Mt,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((N,C)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===C?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${N.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,C),onDragOver:T=>g(T,C),onDrop:v,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Dh,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:N.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(C,C-1),disabled:C===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(Zo,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(C,C+1),disabled:C===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Fa,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(C),className:`p-1.5 rounded transition-colors ${N.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:N.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:N.visible?r.jsx(Cl,{className:"w-4 h-4"}):r.jsx(db,{className:"w-4 h-4"})})]},N.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(De,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(hs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(De,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(De,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const mot=[{value:"ams_holder_74x33",i18nKey:"amsHolderSmall",fallbackLabel:"AMS holder — small (74 × 33 mm)",fallbackHint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},{value:"ams_holder_75x55",i18nKey:"amsHolderLarge",fallbackLabel:"AMS holder — large (75 × 55 mm)",fallbackHint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function pot(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank","noopener,noreferrer")){const n=document.createElement("a");n.href=e,n.download="bambuddy-labels.pdf",document.body.appendChild(n),n.click(),document.body.removeChild(n)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function hot(t){return jl(t)}function fot(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,a=t.brand?` · ${t.brand}`:"";return`${e}${a}`}function got(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function BX(t){if(!t)return[1,0];const e=t.replace(/^#/,"").slice(0,6);if(e.length!==6)return[1,0];const a=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);if([a,n,i].some(Number.isNaN))return[1,0];const s=a/255,o=n/255,l=i/255,c=Math.max(s,o,l),d=Math.min(s,o,l),u=(c+d)/2,m=c-d;if((m===0?0:m/(1-Math.abs(2*u-1)))<.1)return[1,u];let f=0;return c===s?f=(o-l)/m%6:c===o?f=(l-s)/m+2:f=(s-o)/m+4,f=f*60,f<0&&(f+=360),[0,f]}function bot({isOpen:t,onClose:e,availableSpools:a,initialSelectedIds:n,spoolmanMode:i}){const{t:s}=wt(),{showToast:o}=sa(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState(""),[v,b]=y.useState("id");y.useEffect(()=>{if(t){const B=new Set(a.map(O=>O.id));u(new Set(n.filter(O=>B.has(O)))),p(""),g(""),b("id"),c(null)}},[t]);const x=y.useMemo(()=>{const B=[...a];return v==="color"?(B.sort((O,L)=>{const Y=BX(O.rgba),ee=BX(L.rgba);return Y[0]!==ee[0]?Y[0]-ee[0]:Y[1]!==ee[1]?Y[1]-ee[1]:O.id-L.id}),B):(B.sort((O,L)=>O.id-L.id),B)},[a,v]),S=y.useMemo(()=>{const B=new Set;for(const O of x)O.material&&B.add(O.material.toUpperCase());return[...B].sort()},[x]),k=y.useMemo(()=>{const B=m.trim().toLowerCase();return x.filter(O=>!(f&&(O.material||"").toUpperCase()!==f||B&&!got(O).includes(B)))},[x,m,f]),N=k.length>0&&k.every(B=>d.has(B.id));if(!t)return null;const C=d.size,T=C===0;function j(B){u(O=>{const L=new Set(O);return L.has(B)?L.delete(B):L.add(B),L})}function F(){u(B=>{const O=new Set(B);for(const L of k)O.add(L.id);return O})}function P(){u(B=>{const O=new Set(B);for(const L of k)O.delete(L.id);return O})}function D(){u(new Set)}async function R(B){if(T||l)return;const O=x.filter(L=>d.has(L.id)).map(L=>L.id);c(B);try{const L=i?await re.printSpoolmanSpoolLabels({spool_ids:O,template:B}):await re.printSpoolLabels({spool_ids:O,template:B});pot(L),e()}catch(L){const Y=L instanceof Error?L.message:String(L);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:Y}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(xr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),C>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:C}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:B=>p(B.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),S.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),S.map(B=>r.jsx("button",{type:"button",onClick:()=>g(B),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===B?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:B},B))]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.sortBy.label")}),r.jsx("button",{type:"button",onClick:()=>b("id"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="id"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.id")}),r.jsx("button",{type:"button",onClick:()=>b("color"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="color"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.color")})]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:N?P:F,disabled:k.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:N?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:k.length})}),r.jsx("button",{type:"button",onClick:D,disabled:C===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:k.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:x.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:k.map(B=>{const O=d.has(B.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[O?r.jsx(fs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(io,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:O,onChange:()=>j(B.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:hot(B.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:fot(B)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",B.id]})]})},B.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:mot.map(B=>{const O=l===B.value,L=s(`inventory.labels.templates.${B.i18nKey}.label`,B.fallbackLabel),Y=s(`inventory.labels.templates.${B.i18nKey}.hint`,B.fallbackHint);return r.jsxs("button",{disabled:T||l!==null,onClick:()=>R(B.value),title:`${L} — ${Y}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:L}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:Y})]}),O&&r.jsx(pt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},B.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(De,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function xot(t){const e=t[0];let a=0,n=0,i=0;for(const s of t)a+=s.label_weight,n+=s.weight_used,i+=s.core_weight;return{...e,label_weight:a,weight_used:n,core_weight:i}}function UX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Ade="bambuddy-inventory-columns",QN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function yot(){try{const t=localStorage.getItem(Ade);if(t){const e=JSON.parse(t),a=new Set(QN.map(o=>o.id)),n=new Set(e.map(o=>o.id)),i=e.filter(o=>a.has(o.id)),s=QN.filter(o=>!n.has(o.id));return[...i,...s]}}catch{}return QN.map(t=>({...t}))}function vot(t){try{localStorage.setItem(Ade,JSON.stringify(t))}catch{}}function lu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const wot={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function ML(t,e="system"){if(!t)return"-";const a=Ia(t);return a?u3(a,e):"-"}const Sot={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},mI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:ML(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:ML(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?ML(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(w5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:LT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const a=e[t.id];if(!a)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const n=a.printer_name||`Printer ${a.printer_id}`,i=a.ams_id===254||a.ams_id===255,s=!i&&a.ams_id>=128,o=fk(a.ams_id,a.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[n," ",o,a.ams_label?` (${a.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:lu(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:lu(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:lu(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?lu(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const a=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:a?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const a=t.last_scale_weight;if(a==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const n=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+n;let s,o;a0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(a)}g +`),k=new Blob([S],{type:"text/csv"}),N=URL.createObjectURL(k),C=document.createElement("a");C.href=N,C.download=`shopping-list-${new Date().toISOString().slice(0,10)}.csv`,C.click(),setTimeout(()=>URL.revokeObjectURL(N),100)}return r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(mb,{className:"w-4 h-4 text-bambu-green"}),r.jsx("h3",{className:"text-sm font-semibold text-white",children:l("forecast.shoppingList")}),r.jsx("span",{className:"text-xs text-bambu-gray",children:l("forecast.shoppingListItems",{count:t.length})}),t.length>0&&r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-md p-0.5 ml-1",children:[r.jsxs("button",{onClick:()=>u("list"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="list"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(qr,{className:"w-3 h-3"}),l("forecast.listView")]}),r.jsxs("button",{onClick:()=>u("logistics"),className:`flex items-center gap-1.5 px-2 py-0.5 text-xs font-medium rounded transition-colors ${d==="logistics"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:[r.jsx(Nge,{className:"w-3 h-3"}),l("forecast.logisticsView"),g.length>0&&r.jsx("span",{className:"w-3.5 h-3.5 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center",children:g.length})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 text-xs text-bambu-gray hover:text-white transition-colors px-2 py-1 rounded border border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary",children:[r.jsx(Ur,{className:"w-3 h-3"}),l("forecast.downloadCsv")]}),n&&r.jsx("button",{onClick:o,className:"text-xs text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded border border-red-500/20 hover:bg-red-500/10",children:l("forecast.clearAll")})]}),r.jsx("button",{onClick:i,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Gt,{className:"w-4 h-4"})})]})]}),t.length===0?r.jsxs("div",{className:"flex flex-col items-center py-8 text-bambu-gray",children:[r.jsx(qr,{className:"w-8 h-8 mb-2 opacity-30"}),r.jsx("p",{className:"text-sm",children:l("forecast.shoppingListEmpty")})]}):d==="list"?r.jsx("div",{className:"overflow-x-auto",children:r.jsxs("table",{className:"w-full",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/20",children:[r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.qty")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.material")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.weight")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.leadTime")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.expectedRestock")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.status")}),r.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.note")}),r.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-bambu-gray uppercase tracking-wide",children:l("forecast.actions")})]})}),r.jsx("tbody",{className:"divide-y divide-bambu-dark-tertiary",children:t.map(b=>{const x=[b.brand,b.material,b.subtype].filter(Boolean).join(" "),S=g.some(R=>R.item.id===b.id),k=p.get(Aw(b.material,b.subtype,b.brand))??null,N=k&&k.totalSpools>0?k.totalLabelG/k.totalSpools:1e3,C=Math.round(b.quantity_spools*N),T=k?.effectiveLeadTimeDays??a??0,j=T>0?Gm(new Date,T):null,F=b.status==="purchased"||b.status==="received",P=b.status==="received",D=m.isPending;return r.jsxs("tr",{className:`hover:bg-bambu-dark-tertiary/30 transition-colors ${S&&!F?"bg-red-500/5":""}`,children:[r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("span",{className:"text-sm font-semibold text-bambu-green",children:[b.quantity_spools,"×"]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-white",children:x}),S&&!F&&r.jsx(ga,{className:"w-3.5 h-3.5 text-red-400 flex-shrink-0","aria-label":l("forecast.stockBreakBefore")})]})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-white",children:C>=1e3?`${(C/1e3).toFixed(1)}kg`:`${C}g`})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:T>0?`${T}d`:"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-sm text-bambu-gray",children:j?CS(j):"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${P?"bg-bambu-green/20 text-bambu-green":F?"bg-blue-400/20 text-blue-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:l(P?"forecast.received":F?"forecast.purchased":"forecast.pending")})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:b.note||"—"})}),r.jsx("td",{className:"px-4 py-2.5",children:r.jsx("div",{className:"flex items-center justify-end gap-1",children:n&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:F?"pending":"purchased"}),disabled:D||P,title:l(F?"forecast.resetToPending":"forecast.markPurchased"),className:`p-1 rounded transition-colors disabled:opacity-30 ${F?"text-blue-400 hover:text-bambu-gray":"text-bambu-gray hover:text-blue-400"}`,children:F?r.jsx(hs,{className:"w-3.5 h-3.5"}):r.jsx(pbe,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>m.mutate({id:b.id,status:"received",item:b,avgSpoolG:N}),disabled:D||!F||P,title:l("forecast.markReceived"),className:"p-1 rounded transition-colors text-bambu-gray hover:text-bambu-green disabled:opacity-30",children:r.jsx(bye,{className:"w-3.5 h-3.5"})}),r.jsx("button",{onClick:()=>s(b.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:l("forecast.remove"),children:r.jsx(ta,{className:"w-3.5 h-3.5"})})]})})})]},b.id)})})]})}):r.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:f.filter(({item:b})=>b.status!=="received").map(({item:b,forecast:x})=>r.jsx(Qst,{item:b,forecast:x,globalLeadTime:a,canWrite:n,onRemove:()=>s(b.id)},b.id))})]})}function Qst({item:t,forecast:e,globalLeadTime:a,canWrite:n,onRemove:i}){const{t:s}=wt(),o=[t.brand,t.material,t.subtype].filter(Boolean).join(" "),l=y.useMemo(()=>{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=e.dailyRateG,m=e.effectiveLeadTimeDays,p=e.totalSpools>0?e.totalLabelG/e.totalSpools:1e3,f=t.quantity_spools*p,g=Math.max(0,e.totalRemainingG-u*m),v=g+f,b=Math.ceil(v/u),x=Math.min(m+b+5,365),S=[];for(let k=0;k<=x;k++){const N=jw(Gm(new Date,k));if(k===m)S.push({day:k,label:N,stock:Math.round(g),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG)}),S.push({day:k,label:N,stock:Math.round(v),rop:Math.round(e.reorderPointG),safetyStock:Math.round(e.safetyStockG),arrival:!0});else{const C=k{if(!e||e.dailyRateG===null||e.dailyRateG<=0)return null;const u=Math.floor(e.totalRemainingG/e.dailyRateG);return uu>=1e3?`${(u/1e3).toFixed(1)}kg`:`${u}g`,width:44}),r.jsx(su,{contentStyle:{background:"#1a1a2e",border:"1px solid #374151",borderRadius:8,fontSize:11},labelStyle:{color:"#9CA3AF"},formatter:(u,m)=>typeof u!="number"?"":m==="stock"?`${u}g — ${s("forecast.stock")}`:m==="rop"?`${u}g — ${s("forecast.reorderPoint")}`:m==="safetyStock"?`${u}g — ${s("forecast.safetyMarginLabel")}`:`${u}`}),r.jsx(GA,{type:"linear",dataKey:"stock",stroke:"#1DB954",strokeWidth:2,fill:`url(#cart-post-${t.id})`,dot:!1,activeDot:{r:3}}),e.reorderPointG>0&&r.jsx(ou,{y:e.reorderPointG,stroke:"#F59E0B",strokeDasharray:"5 3",strokeOpacity:.8,label:{value:"ROP",position:"insideTopRight",fill:"#F59E0B",fontSize:9}}),e.safetyStockG>0&&r.jsx(ou,{y:e.safetyStockG,stroke:"#6B7280",strokeDasharray:"3 3",strokeOpacity:.6,label:{value:"SS",position:"insideTopRight",fill:"#6B7280",fontSize:9}}),r.jsx(ou,{x:jw(Gm(new Date,l.lt)),stroke:"#3B82F6",strokeWidth:1.5,strokeDasharray:"4 3",strokeOpacity:.9,label:{value:`+${l.arrivalG>=1e3?`${(l.arrivalG/1e3).toFixed(1)}kg`:`${Math.round(l.arrivalG)}g`} arrives (d${l.lt})`,position:"insideTopLeft",fill:"#3B82F6",fontSize:9}}),c!==null&&r.jsx(ou,{x:jw(Gm(new Date,c)),stroke:"#EF4444",strokeWidth:1.5,strokeOpacity:.9,label:{value:"OUT",position:"insideTopLeft",fill:"#EF4444",fontSize:9}})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-[10px] text-bambu-gray",children:[r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-yellow-400 border-dashed"})," ",s("forecast.ropLabel")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t border-bambu-gray border-dashed"})," ",s("forecast.safetyStockLegend")]}),r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-blue-400 border-dashed"})," ",s("forecast.stockArrivalLegend")]}),d&&r.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[r.jsx("span",{className:"inline-block w-4 border-t-2 border-red-400"})," ",s("forecast.stockoutLegend")]})]})]}):null]})}function Xst({forecast:t,onClose:e,onAdd:a}){const{t:n}=wt(),i=[t.group.brand,t.group.material,t.group.subtype].filter(Boolean).join(" "),[s,o]=y.useState("qty"),[l,c]=y.useState("1"),[d,u]=y.useState("30"),[m,p]=y.useState(""),f=y.useMemo(()=>{if(!t.dailyRateG||t.dailyRateG<=0)return null;const b=t.dailyRateG*Number(d),x=t.group.spools.length>0?t.group.spools.reduce((S,k)=>S+k.label_weight,0)/t.group.spools.length:1e3;return Math.ceil(b/x)},[t,d]),g=s==="qty"?parseInt(l,10)||1:f??1;function v(b){b.preventDefault(),a({material:t.group.material,subtype:t.group.subtype,brand:t.group.brand,quantity_spools:g,note:m||null})}return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-2xl border border-bambu-dark-tertiary w-full max-w-sm shadow-2xl",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 pt-5 pb-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(mb,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-base font-semibold text-white",children:n("forecast.addToCartTitle")})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:v,className:"p-5 space-y-4",children:[r.jsx("div",{className:"text-sm text-bambu-gray",children:i}),r.jsxs("div",{className:"flex bg-bambu-dark-tertiary rounded-lg p-0.5",children:[r.jsx("button",{type:"button",onClick:()=>o("qty"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="qty"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byQuantity")}),r.jsx("button",{type:"button",onClick:()=>o("duration"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${s==="duration"?"bg-bambu-dark-secondary text-white shadow":"text-bambu-gray hover:text-white"}`,children:n("forecast.byDuration")})]}),s==="qty"?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.numberOfSpools")}),r.jsx("input",{type:"number",min:1,max:99,value:l,onChange:b=>c(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.lastHowManyDays")}),r.jsx("input",{type:"number",min:1,max:365,value:d,onChange:b=>u(b.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",autoFocus:!0})]}),t.dailyRateG!==null?r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark-tertiary/50 rounded-lg",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:"≈"}),r.jsx("span",{className:"text-sm font-semibold text-bambu-green",children:n("forecast.spoolCount",{count:f??0})}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:["at ",t.dailyRateG.toFixed(1),"g/day"]})]}):r.jsx("div",{className:"text-xs text-yellow-400 px-1",children:n("forecast.noUsageQty")})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:n("forecast.noteOptional")}),r.jsx("input",{type:"text",maxLength:200,value:m,onChange:b=>p(b.target.value),placeholder:n("forecast.notePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/40 focus:outline-none focus:border-bambu-green"})]}),r.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[r.jsx("button",{type:"submit",className:"flex-1 py-2 bg-bambu-green text-white text-sm font-medium rounded-lg hover:bg-bambu-green/80 transition-colors",children:n("forecast.addNSpools",{count:g})}),r.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 text-sm text-bambu-gray hover:text-white border border-bambu-dark-tertiary rounded-lg transition-colors",children:n("forecast.cancel")})]})]})]})})}const uI={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",extra_colors:"",effect_type:"",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null,category:"",low_stock_threshold_pct:null,storage_location:"",spoolman_filament_id:null},Zst=new Set(["material","subtype","brand","rgba","color_name","label_weight"]);function gde(t,e=!1,a=!1){const n={};return e||a?(!t.material&&!t.spoolman_filament_id&&(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const bde=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],Jst=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],Mw=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","CF","GF","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],xde=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"},{name:"Clear",hex:"00000000"}],eot=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],IX=[...xde,...eot],yde="bambuddy-recent-colors",tot=8,aot=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function sf(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const a=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let n="",i=-1;for(const c of a){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){n=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&n&&(o=e.substring(i+n.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of Mw)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of Mw){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:n,variant:l}}function vde(t,e){const a=new Set(Jst);for(const n of t){const{brand:i}=sf(n.name);i&&i.length>1&&a.add(i)}if(e)for(const n of e)if(n.filament_vendor&&n.filament_vendor.length>1)a.add(n.filament_vendor);else{const{brand:i}=sf(n.name);i&&i.length>1&&a.add(i)}return Array.from(a).sort((n,i)=>n.localeCompare(i))}function rot(t){const e=t.filter(n=>n.preset_type==="filament");return e.length===0?[]:e.map(n=>{const i=String(n.id),s=n.filament_type||i,o=Array.from(new Set([i,s]));return{code:i,name:n.name,displayName:n.name,isCustom:!1,allCodes:o}}).sort((n,i)=>n.displayName.localeCompare(i.displayName))}function wde(t,e,a,n){const i=[],s=[],o=new Set;for(const u of t)if(u.is_custom){const m=u.name.toUpperCase();(e.size===0||Array.from(e).some(f=>m.includes(f))||!m.includes("@"))&&(i.push({code:u.setting_id,name:u.name,displayName:`${u.name} (Custom)`,isCustom:!0,allCodes:[u.setting_id]}),o.add(u.setting_id))}else s.push({code:u.setting_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.setting_id]}),o.add(u.setting_id);const l=a&&a.length>0?rot(a):[],c=[];if(n&&n.length>0)for(const u of n){const m=u.filament_id.startsWith("GF")?"GFS"+u.filament_id.slice(2):u.filament_id;o.has(u.filament_id)||o.has(m)||c.push({code:u.filament_id,name:u.name,displayName:u.name,isCustom:!1,allCodes:[u.filament_id,m]})}const d=[...i,...s,...l,...c];return d.length===0?aot:d.sort((u,m)=>u.displayName.localeCompare(m.displayName))}function Sde(t,e){if(!t)return;let a=e.find(n=>n.code===t);if(a||(a=e.find(n=>n.allCodes.includes(t))),!a){const n=t.toLowerCase();a=e.find(i=>i.code.toLowerCase()===n||i.allCodes.some(s=>s.toLowerCase()===n))}return a}function kde(){try{const t=localStorage.getItem(yde);if(t)return JSON.parse(t)}catch{}return[]}function _de(t,e){const a=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),n=[t,...a].slice(0,tot);try{localStorage.setItem(yde,JSON.stringify(n))}catch{}return n}function jL(t,e){if(!e.material)return!1;const n=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=sf(n);return!(!(i.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(i.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(i.brand.toLowerCase()))||e.subtype&&!(i.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(i.variant.toLowerCase())||n.toLowerCase().includes(e.subtype.toLowerCase())))}function Pde({formData:t,updateField:e,cloudAuthenticated:a,loadingCloudPresets:n,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:g}=wt(),[v,b]=y.useState(!1),[x,S]=y.useState(!1),[k,N]=y.useState(!1),[C,T]=y.useState(!1),[j,F]=y.useState(""),[P,D]=y.useState(""),[R,B]=y.useState(""),[O,L]=y.useState(String(t.label_weight)),[Y,ee]=y.useState(!1),Z=y.useRef(null),ce=y.useRef(null),de=y.useRef(null),ue=y.useRef(null);y.useEffect(()=>{const q=J=>{Z.current&&!Z.current.contains(J.target)&&b(!1),ue.current&&!ue.current.contains(J.target)&&T(!1),ce.current&&!ce.current.contains(J.target)&&S(!1),de.current&&!de.current.contains(J.target)&&N(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[]);const Q=y.useMemo(()=>{if(!i)return l;const q=i.toLowerCase();return l.filter(J=>J.displayName.toLowerCase().includes(q)||J.code.toLowerCase().includes(q))},[l,i]),ne=y.useMemo(()=>{if(!j)return c;const q=j.toLowerCase();return c.filter(A=>A.toLowerCase().includes(q)).sort((A,M)=>{const H=A.toLowerCase()===q,W=M.toLowerCase()===q;return H&&!W?-1:!H&&W?1:A.localeCompare(M)})},[c,j]),pe=y.useMemo(()=>{if(!P)return Mw;const q=P.toLowerCase();return Mw.filter(J=>J.toLowerCase().includes(q))},[P]),me=y.useMemo(()=>{if(!R)return d;const q=R.toLowerCase();return d.filter(A=>A.toLowerCase().includes(q)).sort((A,M)=>{const H=A.toLowerCase()===q,W=M.toLowerCase()===q;return H&&!W?-1:!H&&W?1:A.localeCompare(M)})},[R,d]);y.useEffect(()=>{Y||L(String(t.label_weight))},[t.label_weight,Y]);const be=q=>{e("slicer_filament",q.code),s(q.displayName),b(!1);const J=sf(q.name);J.material&&e("material",J.material),J.brand&&e("brand",J.brand),J.variant&&e("subtype",J.variant)};return r.jsxs("div",{className:"space-y-4",children:[!u&&r.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:n?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-3 h-3 animate-spin"})," ",g("inventory.loadingPresets")]}):a?r.jsxs(r.Fragment,{children:[r.jsx(Kh,{className:"w-3 h-3 text-bambu-green"})," ",g("inventory.cloudConnected")]}):r.jsxs(r.Fragment,{children:[r.jsx(t3,{className:"w-3 h-3"})," ",g("inventory.cloudNotConnected")]})}),!u&&r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.slicerPreset")," *"]}),r.jsxs("div",{className:"relative",ref:Z,children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchPresets"),value:i,onChange:q=>{s(q.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:Q.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noPresetsFound")}):Q.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===q.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>be(q),children:q.displayName},`${q.code}::${q.name}`))})]}),o&&r.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[g("inventory.selectedPreset"),": ",r.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.material")," *"]}),r.jsxs("div",{className:"relative",ref:ue,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.selectMaterial"),value:C?R:t.material,onChange:q=>{B(q.target.value),T(!0)},onFocus:()=>{T(!0),B("")}}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),C&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[me.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):me.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",q),T(!1),B("")},children:q},q)),R&&!me.includes(R)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",R),T(!1),B("")},children:g("inventory.useCustomMaterial",{material:R})})]})]}),f?.material&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.brand"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:ce,children:[r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:g("inventory.searchBrand"),value:x?j:t.brand,onChange:q=>{F(q.target.value),S(!0)},onFocus:()=>{S(!0),F("")}}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),x&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ne.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):ne.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",q),S(!1),F("")},children:q},q)),j&&!ne.includes(j)&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",j),S(!1),F("")},children:g("inventory.useCustomBrand",{brand:j})})]})]}),f?.brand&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[g("inventory.subtype"),!u&&" *"]}),r.jsxs("div",{className:"relative",ref:de,children:[r.jsx("input",{type:"text",value:k?P:t.subtype,onChange:q=>{D(q.target.value),N(!0)},onFocus:()=>{N(!0),D("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),r.jsx(Fa,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[pe.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:g("inventory.noResults")}):pe.map(q=>r.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===q?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",q),N(!1),D("")},children:q},q)),P&&!Mw.some(q=>q.toLowerCase()===P.toLowerCase().trim())&&r.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",P),N(!1),D("")},children:g("inventory.useCustomBrand",{brand:P})})]})]}),f?.subtype&&r.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.labelWeight")}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:O,min:0,onFocus:()=>ee(!0),onChange:q=>L(q.target.value),onBlur:()=>{ee(!1);const q=O.trim(),J=Number(q);if(!q||!Number.isFinite(J)||J<0){L(String(t.label_weight));return}const A=Math.round(J);e("label_weight",A),L(String(A))}}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:g("inventory.quantity")}),r.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:m,min:1,max:100,onChange:q=>{const J=Math.max(1,Math.min(100,parseInt(q.target.value)||1));p(J)}})]})]})}function not(t){const e=t.split(/[\s,]+/).map(i=>i.trim().replace(/^#/,"")).filter(Boolean),a=[],n=[];for(const i of e)(i.length===6||i.length===8)&&/^[0-9a-fA-F]+$/.test(i)?a.push(i.toLowerCase()):n.push(i);return{value:a.join(","),invalid:n}}function Nde({formData:t,updateField:e,recentColors:a,onColorUsed:n,catalogColors:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=(t.rgba.replace("#","")+"FF").substring(0,8).toUpperCase(),m=u.substring(0,6),f=u.substring(6,8)==="00",[g,v]=y.useState(f?u:m);y.useEffect(()=>{v(f?u:m)},[m,u,f]);const b=L=>{const Y=(L.replace("#","")+"FF").substring(0,8).toUpperCase();return u===Y},x=L=>jl(L),S=(L,Y,ee,Z)=>{const ce=L.replace("#","").toUpperCase(),de=ce.length===8?ce:ce+"FF";if(e("rgba",de),e("color_name",Y),ee!==void 0){const ue=ee??"";F(ue),D([]),R.current=ue,e("extra_colors",ue)}Z!==void 0&&e("effect_type",Z??""),n({name:Y,hex:L})},k=y.useMemo(()=>{if(i.length===0)return[];const L=t.brand?.trim(),Y=t.material?.toLowerCase().trim(),ee=t.subtype?.toLowerCase().trim();if(!L&&!Y)return[];const Z=L?L.toLowerCase().split(/[\s\-_]+/).filter(ue=>ue.length>=2):[],ce=ue=>{if(Z.length===0)return!0;const Q=ue.toLowerCase();return Z.some(ne=>Q.includes(ne))};if(L&&!Y){const ue=i.filter(Q=>ce(Q.manufacturer));if(ue.length>0)return ue.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}const de=Y&&ee?`${Y} ${ee}`:"";if(de){const ue=i.filter(ne=>ce(ne.manufacturer)&&ne.material?.toLowerCase()===de);if(ue.length>0)return ue.map(ne=>({name:ne.color_name,hex:ne.hex_color.replace("#","").substring(0,6),manufacturer:ne.manufacturer,material:typeof ne.material=="string"?ne.material:void 0,extra_colors:ne.extra_colors??null,effect_type:ne.effect_type??null}));const Q=de.replace(/\+$/,"");if(Q!==de){const ne=i.filter(pe=>ce(pe.manufacturer)&&pe.material?.toLowerCase()===Q);if(ne.length>0)return ne.map(pe=>({name:pe.color_name,hex:pe.hex_color.replace("#","").substring(0,6),manufacturer:pe.manufacturer,material:typeof pe.material=="string"?pe.material:void 0}))}}if(Y){const ue=i.filter(Q=>ce(Q.manufacturer)&&(!Q.material||Q.material.toLowerCase().startsWith(Y)));if(ue.length>0)return ue.map(Q=>({name:Q.color_name,hex:Q.hex_color.replace("#","").substring(0,6),manufacturer:Q.manufacturer,material:typeof Q.material=="string"?Q.material:void 0,extra_colors:Q.extra_colors??null,effect_type:Q.effect_type??null}))}return[]},[i,t.brand,t.material,t.subtype]),N=y.useMemo(()=>{if(!c)return k;if(k.length===0)return[];const L=c.toLowerCase();return k.filter(ee=>ee.name.toLowerCase().includes(L)||(ee.manufacturer?.toLowerCase().includes(L)??!1)||(ee.material?.toLowerCase().includes(L)??!1))},[c,k]),C=k.length>0,T=y.useMemo(()=>c?IX.filter(L=>L.name.toLowerCase().includes(c.toLowerCase())):o?IX:xde,[c,o]),[j,F]=y.useState(t.extra_colors),[P,D]=y.useState([]),R=y.useRef(t.extra_colors);y.useEffect(()=>{t.extra_colors!==R.current&&(F(t.extra_colors),D([]),R.current=t.extra_colors)},[t.extra_colors]);const B=y.useMemo(()=>fj({rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"bar"}),[t.rgba,t.extra_colors,t.effect_type,t.subtype]),O=L=>{if(F(L),!L.trim()){D([]),R.current="",e("extra_colors","");return}const{value:Y,invalid:ee}=not(L);D(ee),R.current=Y,e("extra_colors",Y)};return r.jsxs("div",{className:"space-y-3",children:[r.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:B,"data-testid":"color-preview-banner"}),a.length>0&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[r.jsx(er,{className:"w-3 h-3"}),r.jsx("span",{children:s("inventory.recentColors")})]}),r.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.name},L.hex))})]}),r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),r.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:L=>d(L.target.value)})]}),C?r.jsxs("div",{className:"space-y-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[N.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name,L.extra_colors,L.effect_type),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.manufacturer&&L.material?`${L.name} (${L.manufacturer} — ${L.material})`:L.manufacturer?`${L.name} (${L.manufacturer})`:L.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:L.manufacturer&&L.material?`${L.name} (${L.manufacturer} — ${L.material})`:L.manufacturer?`${L.name} (${L.manufacturer})`:L.name})},`${L.hex}-${L.name}-${L.manufacturer??""}`)),N.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[r.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&r.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?r.jsxs(r.Fragment,{children:[s("inventory.showLess")," ",r.jsx(Zo,{className:"w-3 h-3"})]}):r.jsxs(r.Fragment,{children:[s("inventory.showAll")," ",r.jsx(Fa,{className:"w-3 h-3"})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[T.map(L=>r.jsx("button",{type:"button",onClick:()=>S(L.hex,L.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${b(L.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:x(L.hex),title:L.name,children:r.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:L.name})},L.hex)),T.length===0&&r.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:L=>e("color_name",L.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),r.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:g.toUpperCase(),onChange:L=>{const Y=L.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"").toUpperCase(),ee=Y.length>8?Y.substring(0,8):Y;v(ee),ee.length===6?e("rgba",ee+"FF"):ee.length===8&&e("rgba",ee)},onBlur:()=>{if(g.length===7){const L=g+"0";v(L),e("rgba",L)}else if(g.length>0&&g.length<6){const L=g.padEnd(6,"0");v(L),e("rgba",L+"FF")}}})]}),r.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${m}`,onChange:L=>{const Y=L.target.value.replace("#","").toUpperCase();e("rgba",Y+"FF")},title:s("inventory.pickColor")})]})]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.extraColorsLabel")}),r.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.extraColorsPlaceholder"),value:j,onChange:L=>O(L.target.value),"data-testid":"extra-colors-input"}),P.length>0&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:s("inventory.extraColorsInvalid",{tokens:P.join(", ")})}),!P.length&&r.jsx("p",{className:"text-xs text-bambu-gray/70 mt-1",children:s("inventory.extraColorsHint")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1 flex items-center gap-1.5",children:[r.jsx(zg,{className:"w-3.5 h-3.5"}),s("inventory.colorEffectLabel")]}),r.jsxs("div",{className:"flex gap-2 items-stretch",children:[r.jsx("select",{className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:t.effect_type,onChange:L=>e("effect_type",L.target.value),"data-testid":"effect-type-select",children:lI.map(L=>r.jsx("option",{value:L.value,children:s(L.labelKey)},L.value||"none"))}),r.jsx(w5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,subtype:t.subtype,effectSize:"preview",className:"w-10 h-10",shape:"square"})]})]})]})]})}function iot({catalog:t,value:e,onChange:a,catalogId:n,onCatalogIdChange:i}){const{t:s}=wt(),[o,l]=y.useState(!1),[c,d]=y.useState(""),u=y.useRef(null),m=y.useRef(null);y.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),y.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(n){const b=t.find(x=>x.id===n);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&n!==null&&i(null)},[e,t,n,i]);const p=y.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(b=>b.name.toLowerCase().includes(v)||b.weight.toString().includes(v))},[t,c]),f=y.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),g=y.useMemo(()=>{if(o)return c;if(n){const v=t.find(b=>b.id===n);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,n,t,f]);return r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(aJ,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[r.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[r.jsx("input",{ref:m,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:g,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&r.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:p.length===0?r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>r.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(n?v.id===n:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),a(v.weight),l(!1),d("")},children:[r.jsx("span",{className:"truncate",children:v.name}),r.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const b=parseInt(v.target.value);!isNaN(b)&&b>=0&&a(b)}}),r.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Cde({formData:t,updateField:e,spoolCatalog:a,currencySymbol:n,availableCategories:i,globalLowStockThreshold:s,spoolmanMode:o=!1}){const{t:l}=wt(),{showToast:c}=sa(),[d,u]=y.useState(""),[m,p]=y.useState(!1),[f,g]=y.useState(""),[v,b]=y.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),S=t.core_weight+x;return y.useEffect(()=>{m||u(String(S))},[m,S]),y.useEffect(()=>{v||g(String(x))},[v,x]),r.jsxs("div",{className:"space-y-4",children:[o?r.jsx("p",{className:"text-xs text-bambu-gray px-1",children:l("inventory.spoolWeightManagedBySpoolman")}):r.jsx(iot,{catalog:a,value:t.core_weight,onChange:k=>e("core_weight",k),catalogId:t.core_weight_catalog_id,onCatalogIdChange:k=>e("core_weight_catalog_id",k)}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.currentWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:f,min:0,max:t.label_weight,onFocus:()=>b(!0),onChange:k=>{g(k.target.value)},onBlur:()=>{b(!1);const k=f.trim(),N=Number(k);if(!k||!Number.isFinite(N)||N<0||N>t.label_weight){g(String(x));return}const C=Math.round(N);e("weight_used",Math.max(0,t.label_weight-C)),g(String(C))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.measuredWeight")}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"number",value:d,min:0,onFocus:()=>p(!0),onChange:k=>{u(k.target.value)},onBlur:()=>{p(!1);const k=d.trim(),N=Number(k),C=t.core_weight,T=t.core_weight+t.label_weight;if(!k||!Number.isFinite(N)||NT){c(l("inventory.measuredWeightError",{min:C,max:T}),"error"),u(String(S));return}const j=Math.round(N),F=Math.max(0,Math.min(t.label_weight,j-t.core_weight));e("weight_used",Math.max(0,t.label_weight-F)),u(String(j))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),r.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),r.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.costPerKg","Cost per kg")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:n}),r.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:k=>{const N=k.target.value===""?null:parseFloat(k.target.value);e("cost_per_kg",N)},style:{paddingLeft:`${Math.max(2,n.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-category",children:l("inventory.category")}),r.jsx("input",{id:"spool-category",type:"text",list:"spool-category-options",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.categoryPlaceholder"),value:t.category,maxLength:50,onChange:k=>e("category",k.target.value)}),i.length>0&&r.jsx("datalist",{id:"spool-category-options",children:i.map(k=>r.jsx("option",{value:k},k))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",htmlFor:"spool-low-stock-threshold",children:l("inventory.lowStockThresholdOverride")}),r.jsx("div",{className:"flex items-center gap-2",children:r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{id:"spool-low-stock-threshold",type:"number",className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:String(s),value:t.low_stock_threshold_pct??"",min:1,max:99,step:1,onChange:k=>{const N=k.target.value;if(N===""){e("low_stock_threshold_pct",null);return}const C=Number(N);Number.isFinite(C)&&e("low_stock_threshold_pct",Math.min(99,Math.max(1,Math.round(C))))}}),r.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-bambu-gray pointer-events-none",children:"%"})]})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:l("inventory.lowStockThresholdOverrideHelp",{global:s})})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.note")}),r.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:l("inventory.notePlaceholder"),value:t.note,onChange:k=>e("note",k.target.value)})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:l("inventory.storageLocation")}),r.jsx("input",{type:"text",maxLength:255,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:l("inventory.storageLocationPlaceholder"),value:t.storage_location,onChange:k=>e("storage_location",k.target.value)})]})]})}function sot({filaments:t,isLoading:e,selectedId:a,onSelect:n}){const{t:i}=wt(),[s,o]=y.useState(!1),[l,c]=y.useState(""),d=y.useRef(null),u=y.useRef(null),m=y.useMemo(()=>t.find(b=>b.id===a)??null,[t,a]);y.useEffect(()=>{const b=x=>{d.current&&!d.current.contains(x.target)&&(o(!1),c(""))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=y.useMemo(()=>{const b=l.toLowerCase().trim();return b?t.filter(x=>x.name.toLowerCase().includes(b)||(x.material?.toLowerCase().includes(b)??!1)||(x.vendor?.name.toLowerCase().includes(b)??!1)||(x.color_name?.toLowerCase().includes(b)??!1)):t},[t,l]);y.useEffect(()=>{s&&u.current?.focus()},[s]);const f=()=>{o(!0),c("")},g=b=>{n(b),o(!1),c("")},v=b=>b?`#${b.replace("#","")}`:"#808080";return r.jsxs("div",{ref:d,className:"relative",children:[r.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.pickFromSpoolmanCatalog")}),r.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-left focus:outline-none focus:border-bambu-green hover:border-bambu-gray transition-colors",children:[e?r.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin shrink-0"}):m?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(m.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"text-white text-sm truncate flex-1",children:[m.vendor?.name?`${m.vendor.name} — `:"",m.name]})]}):r.jsxs(r.Fragment,{children:[r.jsx(qr,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("span",{className:"text-bambu-gray text-sm flex-1",children:i("inventory.spoolmanFilamentCatalog")})]}),r.jsx(Fa,{className:"w-4 h-4 text-bambu-gray shrink-0 ml-auto"})]}),s&&r.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl",children:[r.jsx("div",{className:"p-2 border-b border-bambu-dark-tertiary",children:r.jsx("input",{ref:u,type:"text",value:l,onChange:b=>c(b.target.value),placeholder:i("inventory.pickFromSpoolmanCatalog"),className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})}),r.jsx("ul",{className:"max-h-56 overflow-y-auto py-1",children:e?r.jsxs("li",{className:"flex items-center justify-center gap-2 py-4 text-bambu-gray text-sm",children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),r.jsx("span",{children:i("common.loading","Loading…")})]}):p.length===0?r.jsx("li",{className:"py-4 text-center text-bambu-gray text-sm",children:i("inventory.noSpoolmanFilaments")}):p.map(b=>r.jsx("li",{children:r.jsxs("button",{type:"button",onClick:()=>g(b),className:`w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bambu-dark-tertiary transition-colors ${b.id===a?"bg-bambu-dark-tertiary":""}`,children:[r.jsx("span",{className:"w-4 h-4 rounded-full shrink-0 border border-white/20",style:{backgroundColor:v(b.color_hex)},"aria-label":i("inventory.spoolmanFilamentColorSwatch")}),r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsxs("span",{className:"block text-white text-sm truncate",children:[b.vendor?.name?`${b.vendor.name} — `:"",b.name]}),r.jsxs("span",{className:"block text-bambu-gray text-xs truncate",children:[[b.material,b.color_name].filter(Boolean).join(" · "),b.weight?` · ${b.weight}g`:""]})]})]})},b.id))})]})]})}function Tde({formData:t,printersWithCalibrations:e,selectedProfiles:a,setSelectedProfiles:n,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=wt(),l=p=>{s(f=>{const g=new Set(f);return g.has(p)?g.delete(p):g.add(p),g})},c=(p,f,g)=>{const v=`${p}:${f}:${g??"null"}`,b=`${p}:${g??"null"}`;n(x=>{const S=new Set(x);if(S.has(v))S.delete(v);else{for(const k of Array.from(S)){const N=k.split(":");`${N[0]}:${N[2]}`===b&&S.delete(k)}S.add(v)}return S})},d=()=>{const p=new Set;for(const{printer:f,calibrations:g}of e){if(!f.connected)continue;const v=g.filter(x=>jL(x,t)),b=new Map;for(const x of v){const S=`${x.extruder_id??"null"}`;b.has(S)||b.set(S,[]),b.get(S).push(x)}for(const[x,S]of b)if(S.length>0){const N=[...S].sort((C,T)=>T.k_value-C.k_value)[0];p.add(`${f.id}:${N.cali_idx}:${x}`)}}n(p)};if(!t.material)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return r.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:r.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:g})=>f.connected?p+g.filter(v=>jL(v,t)).length:p,0),m=(p,f)=>{const g=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=a.has(g);return r.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[r.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(p.id),f.cali_idx,f.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),r.jsx("div",{className:"flex items-center gap-2 shrink-0",children:r.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",f.k_value.toFixed(3)]})})]},`${f.cali_idx}-${f.extruder_id}`)};return r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),u>0&&r.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[r.jsx(zg,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),r.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const g=i.has(String(p.id)),v=f.filter(N=>jL(N,t)),b=v.length,x=v.some(N=>N.extruder_id!==void 0&&N.extruder_id!==null&&N.extruder_id>0),S=v.filter(N=>N.extruder_id===1),k=v.filter(N=>N.extruder_id===0||N.extruder_id===void 0||N.extruder_id===null);return r.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[r.jsxs("button",{type:"button",onClick:()=>l(String(p.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[g?r.jsx(Fa,{className:"w-4 h-4 text-bambu-gray"}):r.jsx(qn,{className:"w-4 h-4 text-bambu-gray"}),r.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?r.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[b," ",o(b!==1?"inventory.matches":"inventory.match")]}):r.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),r.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${p.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:p.connected?o("inventory.connected"):o("inventory.offline")})]}),g&&r.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):x?r.jsxs(r.Fragment,{children:[S.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),r.jsx("div",{className:"space-y-2",children:S.map(N=>m(p,N))})]}),k.length>0&&r.jsxs("div",{className:"space-y-2",children:[r.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),r.jsx("div",{className:"space-y-2",children:k.map(N=>m(p,N))})]})]}):r.jsx("div",{className:"space-y-2",children:v.map(N=>m(p,N))}):r.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),a.size>0&&r.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"font-semibold",children:a.size})," ",o("inventory.profilesSelected")]})})]})}function oot(t){const e=Ia(t);return e?e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}):""}const lot={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function cot({spoolId:t}){const{t:e}=wt(),a=aa(),{showToast:n}=sa(),{data:i,isLoading:s}=Qe({queryKey:["spool-usage",t],queryFn:()=>re.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>re.clearSpoolUsageHistory(t),onSuccess:()=>{a.invalidateQueries({queryKey:["spool-usage",t]}),n(e("inventory.historyCleared"),"success")}});return s?r.jsx("div",{className:"flex justify-center py-4",children:r.jsx(pt,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?r.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[r.jsx(er,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),r.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[r.jsx(ta,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),r.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>r.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"text-bambu-gray",children:oot(l.created_at)}),l.print_name&&r.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[r.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),r.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),r.jsx("span",{className:lot[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}const OX={tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null};function dot({isOpen:t,onClose:e,spool:a,mode:n,printersWithCalibrations:i=[],currencySymbol:s,onSpoolsCreated:o,spoolmanMode:l=!1,spoolsQueryKey:c=["inventory-spools"]}){const{t:d}=wt(),u=aa(),{showToast:m}=sa(),p=n==="edit",f=n==="copy",[g,v]=y.useState(uI),[b,x]=y.useState({}),[S,k]=y.useState("filament"),[N,C]=y.useState(!1),[T,j]=y.useState(!1),[F,P]=y.useState(!1),[D,R]=y.useState(1),[B,O]=y.useState(!1),[L,Y]=y.useState(!1),[ee,Z]=y.useState([]),[ce,de]=y.useState(""),[ue,Q]=y.useState([]),[ne,pe]=y.useState([]),[me,be]=y.useState([]),[q,J]=y.useState([]),[A,M]=y.useState([]),[H,W]=y.useState([]),[U,se]=y.useState(new Set),[I,G]=y.useState(new Set),K=i.length>0?i:H,X=U.size,{data:ie=[],isLoading:oe,error:he}=Qe({queryKey:["spoolman-inventory-filaments"],queryFn:()=>re.getSpoolmanInventoryFilaments(),enabled:l&&t,staleTime:6e4,retry:!1});y.useEffect(()=>{M(kde())},[]),y.useEffect(()=>{t&&((async()=>{Y(!0);try{const at=await re.getCloudStatus();if(O(at.is_authenticated),at.is_authenticated){const rt=await re.getFilamentPresets();Z(rt)}}catch(at){console.error("Failed to fetch cloud presets:",at),O(!1)}finally{Y(!1)}})(),l||re.getSpoolCatalog().then(Q).catch(console.error),re.getColorCatalog().then(J).catch(console.error),re.getLocalPresets().then(at=>pe(at.filament)).catch(console.error),re.getBuiltinFilaments().then(be).catch(console.error),i.length===0&&(async()=>{try{const at=await re.getPrinters(),rt=await Promise.all(at.map(Ut=>re.getPrinterStatus(Ut.id).catch(()=>null))),Ct=[];for(let Ut=0;Ut({cali_idx:dt.slot_id,filament_id:dt.filament_id,setting_id:dt.setting_id||"",name:dt.name,k_value:parseFloat(dt.k_value)||0,n_coef:parseFloat(dt.n_coef)||0,extruder_id:dt.extruder_id,nozzle_diameter:dt.nozzle_diameter}))}catch{}Ct.push({printer:{...ft,connected:Zt},calibrations:oa})}W(Ct)}catch(at){console.error("Failed to fetch printer calibrations:",at)}})())},[t,i.length]);const le=y.useMemo(()=>wde(ee,new Set,ne,me),[ee,ne,me]),fe=y.useMemo(()=>{const Ae=vde(ee,ne),at=q.map(Ct=>Ct.manufacturer?.trim()).filter(Ct=>!!Ct),rt=new Set([...Ae,...at]);return Array.from(rt).sort((Ct,Ut)=>Ct.localeCompare(Ut))},[ee,ne,q]),$=y.useMemo(()=>{const Ae=q.map(rt=>rt.material?.trim()).filter(rt=>!!rt),at=new Set([...bde,...Ae]);return Array.from(at).sort((rt,Ct)=>rt.localeCompare(Ct))},[q]),z=y.useMemo(()=>{const Ae=[];for(const at of q){const rt=at.manufacturer?.trim(),Ct=at.material?.trim();rt&&Ct&&Ae.push({brand:rt,material:Ct})}for(const at of ee){const rt=sf(at.name);rt.brand&&rt.material&&Ae.push({brand:rt.brand,material:rt.material})}for(const at of ne){const rt=sf(at.name),Ct=at.filament_vendor?.trim()||rt.brand,Ut=rt.material;Ct&&Ut&&Ae.push({brand:Ct,material:Ut})}return Ae},[ee,q,ne]),ae=y.useMemo(()=>{const Ae=new Map;for(const at of z){const rt=at.brand.toLowerCase(),Ct=at.material.toLowerCase();Ae.has(rt)||Ae.set(rt,new Set),Ae.get(rt).add(Ct)}return Ae},[z]),ge=y.useMemo(()=>{const Ae=new Map;for(const at of z){const rt=at.brand.toLowerCase(),Ct=at.material.toLowerCase();Ae.has(Ct)||Ae.set(Ct,new Set),Ae.get(Ct).add(rt)}return Ae},[z]),xe=y.useMemo(()=>{if(!g.material)return fe;const Ae=g.material.toLowerCase(),at=ge.get(Ae);return!at||at.size===0?fe:fe.filter(rt=>at.has(rt.toLowerCase()))},[fe,g.material,ge]),ve=y.useMemo(()=>{if(!g.brand)return $;const Ae=g.brand.toLowerCase(),at=ae.get(Ae);return!at||at.size===0?$:$.filter(rt=>at.has(rt.toLowerCase()))},[$,g.brand,ae]),je=y.useMemo(()=>Sde(g.slicer_filament,le),[g.slicer_filament,le]);y.useEffect(()=>{if(t){if(a){const Ae=a.rgba&&/^[0-9A-Fa-f]{8}$/.test(a.rgba)?a.rgba:"808080FF";if(v({material:a.material||"",subtype:a.subtype||"",brand:a.brand||"",color_name:a.color_name_is_synthesized?"":a.color_name||"",rgba:Ae,extra_colors:a.extra_colors||"",effect_type:a.effect_type||"",label_weight:a.label_weight||1e3,core_weight:a.core_weight||250,core_weight_catalog_id:a.core_weight_catalog_id??null,weight_used:f?0:a.weight_used||0,slicer_filament:a.slicer_filament||"",note:a.note||"",cost_per_kg:a.cost_per_kg??null,category:a.category||"",low_stock_threshold_pct:a.low_stock_threshold_pct??null,storage_location:a.storage_location||"",spoolman_filament_id:null}),de(a.slicer_filament_name||a.slicer_filament||""),a.k_profiles&&a.k_profiles.length>0){const at=new Set;for(const rt of a.k_profiles)rt.cali_idx!==null&&rt.cali_idx!==void 0&&at.add(`${rt.printer_id}:${rt.cali_idx}:${rt.extruder??"null"}`);se(at)}else se(new Set)}else v(uI),de(""),se(new Set),P(!1),R(1);x({}),k("filament"),C(!1),j(!1)}},[t,a,n,f]),y.useEffect(()=>{t&&K.length>0&&G(new Set(K.map(Ae=>String(Ae.printer.id))))},[t,K]);const Me=(Ae,at)=>{const rt=Zst.has(Ae);l&&rt&&g.spoolman_filament_id!==null&&m(d("inventory.spoolmanFilamentUnlinked"),"info"),v(Ct=>({...Ct,[Ae]:at,...l&&rt&&Ct.spoolman_filament_id!==null?{spoolman_filament_id:null}:{}})),Ae==="weight_used"&&C(!0),Ae==="storage_location"&&j(!0),b[Ae]&&x(Ct=>({...Ct,[Ae]:void 0}))},Se=Ae=>{const at=Ae.material||"",rt=Ae.name||"",Ct=at&&rt.startsWith(at)?rt.slice(at.length).trim():rt,Ut=(Ae.color_hex??"").replace("#","").toUpperCase(),ft=/^[0-9A-F]{6}$/.test(Ut)?Ut:"808080";v(Kt=>({...Kt,spoolman_filament_id:Ae.id,material:at,subtype:Ct,brand:Ae.vendor?.name||"",rgba:`${ft}FF`,color_name:Ae.color_name||"",label_weight:Ae.weight??Kt.label_weight})),m(d("inventory.spoolmanFilamentSelected"),"success")},Ue=Ae=>{M(at=>_de(Ae,at))},_e=lt({mutationFn:Ae=>l?re.createSpoolmanInventorySpool(Ae):re.createSpool(Ae),onSuccess:async Ae=>{Ae?.id&&!await Ie(Ae.id)||(await u.invalidateQueries({queryKey:c}),o&&o([Ae]),m(d("inventory.spoolCreated"),"success"),e())},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),ze=lt({mutationFn:({data:Ae,qty:at})=>l?re.bulkCreateSpoolmanInventorySpools(Ae,at):re.bulkCreateSpools(Ae,at),onSuccess:async Ae=>{const at=l&&"created"in Ae?Ae:null,rt=at?at.created:Ae;if(U.size>0)for(const Ct of rt)await Ie(Ct.id);await u.invalidateQueries({queryKey:c}),o&&o(rt),at&&at.failed_count>0?m(d("inventory.spoolsPartiallyCreated",{created:rt.length,total:at.requested_count}),"warning"):m(d("inventory.spoolsCreated",{count:rt.length}),"success"),e()},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),Fe=lt({mutationFn:Ae=>l?re.updateSpoolmanInventorySpool(a.id,Ae):re.updateSpool(a.id,Ae),onSuccess:async()=>{a?.id&&!await Ie(a.id)||(await u.invalidateQueries({queryKey:c}),m(d("inventory.spoolUpdated"),"success"),e())},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.saveFailed"),"error")}}),qe=lt({mutationFn:()=>l?re.updateSpoolmanInventorySpool(a.id,OX):re.updateSpool(a.id,OX),onSuccess:async()=>{await u.invalidateQueries({queryKey:c}),m(d("inventory.rfidCleared","RFID tag cleared"),"success"),e()},onError:Ae=>{Ae instanceof Bi&&Ae.status===503?m(d("inventory.spoolmanUnreachable"),"error"):m(d("inventory.tagClearFailed"),"error")}}),{data:Oe}=Qe({queryKey:["spool-assignments"],queryFn:()=>re.getAssignments(),enabled:t&&p&&!l}),{data:it}=Qe({queryKey:["spoolman-slot-assignments-all"],queryFn:()=>re.getSpoolmanSlotAssignments(),enabled:t&&p&&l}),Le=(()=>{if(a)return l?it?.find(Ae=>Ae.spoolman_spool_id===a.id):Oe?.find(Ae=>Ae.spool_id===a.id)})(),{data:st}=Qe({queryKey:["inventory-spools"],queryFn:()=>re.getSpools(!0),enabled:t}),{data:Te}=Qe({queryKey:["settings"],queryFn:re.getSettings,enabled:t}),Xe=(()=>{const Ae=new Set;for(const at of st??[]){const rt=at.category?.trim();rt&&Ae.add(rt)}return Array.from(Ae).sort((at,rt)=>at.localeCompare(rt))})(),$e=Te?.low_stock_threshold??20,Ne=lt({mutationFn:async()=>{if(!Le)throw new Error("No assignment");if(l){if(!a)throw new Error("No spool");await re.unassignSpoolmanSlot(a.id);return}await re.unassignSpool(Le.printer_id,Le.ams_id,Le.tray_id)},onSuccess:async()=>{l?(await u.invalidateQueries({queryKey:["spoolman-slot-assignments-all"]}),await u.invalidateQueries({queryKey:["spoolman-slot-assignments"]})):await u.invalidateQueries({queryKey:["spool-assignments"]}),m(d("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:Ae=>{m(Ae.message,"error")}}),Ie=async Ae=>{const at=l?re.saveSpoolmanKProfiles:re.saveSpoolKProfiles;if(U.size===0)try{return await at(Ae,[]),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}const rt=[];let Ct=0;for(const Ut of U){const[ft,Kt,Zt]=Ut.split(":"),oa=parseInt(ft),xa=parseInt(Kt),dt=Zt==="null"?0:parseInt(Zt),vt=K.find(Pt=>Pt.printer.id===oa);if(vt){const Pt=vt.calibrations.find(Nt=>Nt.cali_idx===xa);Pt?rt.push({printer_id:oa,extruder:dt,nozzle_diameter:Pt.nozzle_diameter||"0.4",k_value:Pt.k_value,name:Pt.name||null,cali_idx:Pt.cali_idx,setting_id:Pt.setting_id||null}):Ct++}else Ct++}if(Ct>0)return console.error(`saveKProfiles: ${Ct} profile key(s) could not be resolved`,Array.from(U)),m(d("inventory.kProfileSaveFailed"),"warning"),!1;if(rt.length>0)try{return await at(Ae,rt),!0}catch(Ut){return console.error("Failed to save K-profiles:",Ut),m(d("inventory.kProfileSaveFailed"),"warning"),!1}return!0};if(y.useEffect(()=>{if(!t)return;const Ae=at=>{at.key==="Escape"&&e()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[t,e]),!t)return null;const et=()=>{const Ae=gde(g,F,l);if(!Ae.isValid){x(Ae.errors),(Ae.errors.slicer_filament||Ae.errors.material||Ae.errors.brand||Ae.errors.subtype)&&k("filament");return}const at=je?.displayName||ce||null,rt={material:g.material||null,subtype:g.subtype||null,brand:g.brand||null,color_name:g.color_name||null,rgba:g.rgba||null,extra_colors:g.extra_colors||null,effect_type:g.effect_type||null,label_weight:g.label_weight,...l?{}:{core_weight:g.core_weight,core_weight_catalog_id:g.core_weight_catalog_id},slicer_filament:g.slicer_filament||null,slicer_filament_name:at,nozzle_temp_min:null,nozzle_temp_max:null,note:g.note||null,cost_per_kg:g.cost_per_kg,category:g.category.trim()||null,low_stock_threshold_pct:g.low_stock_threshold_pct,...l?{spoolman_filament_id:g.spoolman_filament_id}:{}};(!p||N)&&(rt.weight_used=g.weight_used),(!p||T)&&(rt.storage_location=g.storage_location||null),p?Fe.mutate(rt):D>1?ze.mutate({data:rt,qty:D}):_e.mutate(rt)},We=_e.isPending||ze.isPending||Fe.isPending||qe.isPending||Ne.isPending;return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-baseline gap-2",children:[d(p?"inventory.editSpool":f?"inventory.copySpool":"inventory.addSpool"),p&&a&&r.jsxs("span",{className:"text-sm font-mono text-bambu-gray",children:["#",a.id]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Gt,{className:"w-5 h-5"})})]}),n==="create"&&r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(Cc,{className:"w-4 h-4 text-amber-400"}),r.jsx("span",{className:"text-sm text-white",children:d("inventory.quickAdd")})]}),r.jsx("button",{type:"button",onClick:()=>{P(!F),F||k("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${F?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:r.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${F?"translate-x-4":"translate-x-0.5"}`})})]}),r.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[r.jsxs("button",{onClick:()=>k("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(RS,{className:"w-4 h-4"}),d("inventory.filamentInfoTab")]}),!F&&r.jsxs("button",{onClick:()=>k("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${S==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[r.jsx(rge,{className:"w-4 h-4"}),d("inventory.paProfileTab"),X>0&&r.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:X})]})]}),r.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:S==="filament"?r.jsxs("div",{className:"space-y-6",children:[l&&!p&&r.jsx("div",{children:he?r.jsx("p",{className:"text-sm text-red-400 px-1",children:d("inventory.spoolmanCatalogLoadFailed")}):r.jsx(sot,{filaments:ie,isLoading:oe,selectedId:g.spoolman_filament_id,onSelect:Se})}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.filamentInfo")}),r.jsx(Pde,{formData:g,updateField:Me,cloudAuthenticated:B,loadingCloudPresets:L,presetInputValue:ce,setPresetInputValue:de,selectedPresetOption:je,filamentOptions:le,availableBrands:xe,availableMaterials:ve,quickAdd:F,quantity:D,onQuantityChange:R,errors:b})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.color")}),r.jsx(Nde,{formData:g,updateField:Me,recentColors:A,onColorUsed:Ue,catalogColors:q})]}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:d("inventory.additional")}),r.jsx(Cde,{formData:g,updateField:Me,spoolCatalog:ue,currencySymbol:s,availableCategories:Xe,globalLowStockThreshold:$e,spoolmanMode:l})]}),p&&a&&!l&&r.jsx("div",{children:r.jsx(cot,{spoolId:a.id})})]}):r.jsx(Tde,{formData:g,updateField:Me,printersWithCalibrations:K,selectedProfiles:U,setSelectedProfiles:se,expandedPrinters:I,setExpandedPrinters:G})}),r.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[p&&r.jsxs("div",{className:"flex gap-2 mr-auto",children:[r.jsxs(De,{variant:"secondary",onClick:()=>qe.mutate(),disabled:We||!a?.tag_uid,children:[r.jsx(Km,{className:"w-4 h-4"}),d("inventory.clearRfid","Clear RFID Tag")]}),r.jsxs(De,{variant:"secondary",onClick:()=>Ne.mutate(),disabled:We||!Le,children:[r.jsx(cu,{className:"w-4 h-4"}),d("inventory.unassignSpool","Unassign")]})]}),r.jsxs("div",{className:"flex gap-2 ml-auto",children:[r.jsx(De,{variant:"secondary",onClick:e,children:d("common.cancel")}),r.jsx(De,{onClick:et,disabled:We,children:We?r.jsxs(r.Fragment,{children:[r.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("common.saving")]}):r.jsxs(r.Fragment,{children:[r.jsx(cs,{className:"w-4 h-4"}),d(p?"common.save":f?"inventory.copySpool":"inventory.addSpool")]})})]})]})]})]})}function uot({isOpen:t,onClose:e,columns:a,defaultColumns:n,onSave:i}){const{t:s}=wt(),[o,l]=y.useState(a),[c,d]=y.useState(null),u=y.useRef(null);if(y.useEffect(()=>{t&&l(a.map(N=>({...N})))},[t,a]),y.useEffect(()=>{if(!t)return;const N=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t,e]),!t)return null;const m=N=>{l(C=>C.map((T,j)=>j===N?{...T,visible:!T.visible}:T))},p=(N,C)=>{C<0||C>=o.length||l(T=>{const j=[...T],[F]=j.splice(N,1);return j.splice(C,0,F),j})},f=(N,C)=>{u.current=C,d(C),N.dataTransfer.effectAllowed="move"},g=(N,C)=>{N.preventDefault(),N.dataTransfer.dropEffect="move";const T=u.current;T!==null&&T!==C&&(p(T,C),u.current=C,d(C))},v=N=>{N.preventDefault()},b=()=>{u.current=null,d(null)},x=()=>{l(n.map(N=>({...N})))},S=()=>{i(o),e()},k=o.filter(N=>N.visible).length;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:r.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:N=>N.stopPropagation(),children:r.jsxs(Mt,{className:"p-6 flex flex-col min-h-0",children:[r.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),r.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),r.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),r.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((N,C)=>r.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===C?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${N.visible?"":"opacity-50"}`,draggable:!0,onDragStart:T=>f(T,C),onDragOver:T=>g(T,C),onDrop:v,onDragEnd:b,children:[r.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:r.jsx(Dh,{className:"w-4 h-4"})}),r.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:N.label}),r.jsxs("div",{className:"flex items-center gap-0.5",children:[r.jsx("button",{onClick:()=>p(C,C-1),disabled:C===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:r.jsx(Zo,{className:"w-4 h-4"})}),r.jsx("button",{onClick:()=>p(C,C+1),disabled:C===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:r.jsx(Fa,{className:"w-4 h-4"})})]}),r.jsx("button",{onClick:()=>m(C),className:`p-1.5 rounded transition-colors ${N.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:N.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:N.visible?r.jsx(Cl,{className:"w-4 h-4"}):r.jsx(db,{className:"w-4 h-4"})})]},N.id))}),r.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs(De,{variant:"secondary",onClick:x,className:"mr-auto",children:[r.jsx(hs,{className:"w-4 h-4"}),s("inventory.reset")]}),r.jsx(De,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),r.jsx(De,{onClick:S,children:s("inventory.applyChanges")})]})]})})})}const mot=[{value:"ams_holder_74x33",i18nKey:"amsHolderSmall",fallbackLabel:"AMS holder — small (74 × 33 mm)",fallbackHint:"Single label per page; matches the printable label from MakerWorld model 752566 (AMS Filament Label Holder)."},{value:"ams_holder_75x55",i18nKey:"amsHolderLarge",fallbackLabel:"AMS holder — large (75 × 55 mm)",fallbackHint:"Single label per page; fits the cardstock-insert variant of the AMS Filament Label Holder. Roomy enough for swatch, brand, material, ID, and QR code."},{value:"box_40x30",i18nKey:"box40x30",fallbackLabel:"Box label (40 × 30 mm)",fallbackHint:"Single label per page; common DK/Brother roll size, good for filament-bag and storage-bin labels."},{value:"box_62x29",i18nKey:"box",fallbackLabel:"Box label (62 × 29 mm)",fallbackHint:"Single label per page; sized for Brother PT/QL and Dymo small labels."},{value:"avery_l7160",i18nKey:"averyL7160",fallbackLabel:"Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)",fallbackHint:"EU sheet stock; 21 labels per A4 page."},{value:"avery_5160",i18nKey:"avery5160",fallbackLabel:"Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)",fallbackHint:"US sheet stock; 30 labels per Letter page."}];function pot(t){const e=window.URL.createObjectURL(t);if(!window.open(e,"_blank")){const n=document.createElement("a");n.href=e,n.download="bambuddy-labels.pdf",document.body.appendChild(n),n.click(),document.body.removeChild(n)}setTimeout(()=>window.URL.revokeObjectURL(e),6e4)}function hot(t){return jl(t)}function fot(t){const e=t.color_name??`${t.material}${t.subtype?` ${t.subtype}`:""}`,a=t.brand?` · ${t.brand}`:"";return`${e}${a}`}function got(t){return[t.color_name,t.material,t.subtype,t.brand,`#${t.id}`].filter(Boolean).join(" ").toLowerCase()}function BX(t){if(!t)return[1,0];const e=t.replace(/^#/,"").slice(0,6);if(e.length!==6)return[1,0];const a=parseInt(e.slice(0,2),16),n=parseInt(e.slice(2,4),16),i=parseInt(e.slice(4,6),16);if([a,n,i].some(Number.isNaN))return[1,0];const s=a/255,o=n/255,l=i/255,c=Math.max(s,o,l),d=Math.min(s,o,l),u=(c+d)/2,m=c-d;if((m===0?0:m/(1-Math.abs(2*u-1)))<.1)return[1,u];let f=0;return c===s?f=(o-l)/m%6:c===o?f=(l-s)/m+2:f=(s-o)/m+4,f=f*60,f<0&&(f+=360),[0,f]}function bot({isOpen:t,onClose:e,availableSpools:a,initialSelectedIds:n,spoolmanMode:i}){const{t:s}=wt(),{showToast:o}=sa(),[l,c]=y.useState(null),[d,u]=y.useState(new Set),[m,p]=y.useState(""),[f,g]=y.useState(""),[v,b]=y.useState("id");y.useEffect(()=>{if(t){const B=new Set(a.map(O=>O.id));u(new Set(n.filter(O=>B.has(O)))),p(""),g(""),b("id"),c(null)}},[t]);const x=y.useMemo(()=>{const B=[...a];return v==="color"?(B.sort((O,L)=>{const Y=BX(O.rgba),ee=BX(L.rgba);return Y[0]!==ee[0]?Y[0]-ee[0]:Y[1]!==ee[1]?Y[1]-ee[1]:O.id-L.id}),B):(B.sort((O,L)=>O.id-L.id),B)},[a,v]),S=y.useMemo(()=>{const B=new Set;for(const O of x)O.material&&B.add(O.material.toUpperCase());return[...B].sort()},[x]),k=y.useMemo(()=>{const B=m.trim().toLowerCase();return x.filter(O=>!(f&&(O.material||"").toUpperCase()!==f||B&&!got(O).includes(B)))},[x,m,f]),N=k.length>0&&k.every(B=>d.has(B.id));if(!t)return null;const C=d.size,T=C===0;function j(B){u(O=>{const L=new Set(O);return L.has(B)?L.delete(B):L.add(B),L})}function F(){u(B=>{const O=new Set(B);for(const L of k)O.add(L.id);return O})}function P(){u(B=>{const O=new Set(B);for(const L of k)O.delete(L.id);return O})}function D(){u(new Set)}async function R(B){if(T||l)return;const O=x.filter(L=>d.has(L.id)).map(L=>L.id);c(B);try{const L=i?await re.printSpoolmanSpoolLabels({spool_ids:O,template:B}):await re.printSpoolLabels({spool_ids:O,template:B});pot(L),e()}catch(L){const Y=L instanceof Error?L.message:String(L);o(s("inventory.labels.error","Could not generate labels: {{msg}}",{msg:Y}),"error")}finally{c(null)}}return r.jsxs("div",{className:"fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto",children:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),r.jsxs("div",{className:"relative w-full max-w-3xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(xr,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:s("inventory.labels.title","Print spool labels")}),C>0&&r.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s("inventory.labels.selectedCount","{{count}} selected",{count:C}),")"]})]}),r.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors","aria-label":s("common.close","Close"),children:r.jsx(Gt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-2 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"relative",children:[r.jsx(br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"search",value:m,onChange:B=>p(B.target.value),placeholder:s("inventory.labels.searchPlaceholder","Search name, brand, or #ID"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),S.length>1&&r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.filterByMaterial","Material:")}),r.jsx("button",{type:"button",onClick:()=>g(""),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===""?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.allMaterials","All")}),S.map(B=>r.jsx("button",{type:"button",onClick:()=>g(B),className:`px-2 py-0.5 text-xs rounded-full border transition ${f===B?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:B},B))]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:s("inventory.labels.sortBy.label")}),r.jsx("button",{type:"button",onClick:()=>b("id"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="id"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.id")}),r.jsx("button",{type:"button",onClick:()=>b("color"),className:`px-2 py-0.5 text-xs rounded-full border transition ${v==="color"?"bg-bambu-green text-bambu-dark border-bambu-green":"bg-bambu-dark text-bambu-gray border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:s("inventory.labels.sortBy.color")})]})]}),r.jsxs("div",{className:"px-4 pt-3 pb-2 flex items-center justify-between gap-3 flex-wrap",children:[r.jsx("span",{className:"text-sm text-bambu-gray",children:s("inventory.labels.pickSpools","Pick which spools to print labels for:")}),r.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[r.jsx("button",{type:"button",onClick:N?P:F,disabled:k.length===0,className:"text-bambu-green hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:N?s("inventory.labels.deselectVisible","Deselect visible"):s("inventory.labels.selectVisible","Select all visible ({{count}})",{count:k.length})}),r.jsx("button",{type:"button",onClick:D,disabled:C===0,className:"text-bambu-gray hover:text-white hover:underline disabled:opacity-50 disabled:no-underline disabled:cursor-not-allowed",children:s("inventory.labels.clearAll","Clear all")})]})]}),r.jsx("div",{className:"flex-1 overflow-y-auto px-2 pb-2 min-h-0",children:k.length===0?r.jsx("div",{className:"text-center text-sm text-bambu-gray py-6",children:x.length===0?s("inventory.labels.noSpoolsToShow","No spools to show. Adjust your filter and try again."):s("inventory.labels.noMatches","No spools match the current search or filter.")}):r.jsx("ul",{className:"space-y-0.5",children:k.map(B=>{const O=d.has(B.id);return r.jsx("li",{children:r.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary/50 cursor-pointer",children:[O?r.jsx(fs,{className:"w-4 h-4 text-bambu-green shrink-0"}):r.jsx(io,{className:"w-4 h-4 text-bambu-gray shrink-0"}),r.jsx("input",{type:"checkbox",checked:O,onChange:()=>j(B.id),className:"sr-only"}),r.jsx("span",{className:"w-4 h-4 rounded border border-black/20 shrink-0",style:hot(B.rgba)}),r.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-white",children:fot(B)}),r.jsxs("span",{className:"text-xs font-mono text-bambu-gray shrink-0",children:["#",B.id]})]})},B.id)})})}),r.jsx("div",{className:"px-3 pt-2 pb-2 grid grid-cols-1 sm:grid-cols-2 gap-2 border-t border-bambu-dark-tertiary",children:mot.map(B=>{const O=l===B.value,L=s(`inventory.labels.templates.${B.i18nKey}.label`,B.fallbackLabel),Y=s(`inventory.labels.templates.${B.i18nKey}.hint`,B.fallbackHint);return r.jsxs("button",{disabled:T||l!==null,onClick:()=>R(B.value),title:`${L} — ${Y}`,className:"w-full text-left p-2.5 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-green hover:bg-bambu-green/10 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-bambu-dark-tertiary disabled:hover:bg-bambu-dark transition flex items-center gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium text-white text-sm truncate",children:L}),r.jsx("div",{className:"text-xs text-bambu-gray mt-0.5 truncate",children:Y})]}),O&&r.jsx(pt,{className:"w-4 h-4 animate-spin text-bambu-green shrink-0"})]},B.value)})}),r.jsx("div",{className:"flex justify-end gap-2 px-5 py-2 border-t border-bambu-dark-tertiary",children:r.jsx(De,{variant:"secondary",onClick:e,disabled:l!==null,children:s("common.cancel","Cancel")})})]})]})}function xot(t){const e=t[0];let a=0,n=0,i=0;for(const s of t)a+=s.label_weight,n+=s.weight_used,i+=s.core_weight;return{...e,label_weight:a,weight_used:n,core_weight:i}}function UX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.extra_colors||""}|${t.effect_type||""}|${t.label_weight}`}const Ade="bambuddy-inventory-columns",QN=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"storage_location",label:"Storage Location",visible:!1},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"spool_name",label:"Spool",visible:!1},{id:"cost_per_kg",label:"Cost/kg",visible:!1},{id:"weight_check",label:"Weight Check",visible:!1}];function yot(){try{const t=localStorage.getItem(Ade);if(t){const e=JSON.parse(t),a=new Set(QN.map(o=>o.id)),n=new Set(e.map(o=>o.id)),i=e.filter(o=>a.has(o.id)),s=QN.filter(o=>!n.has(o.id));return[...i,...s]}}catch{}return QN.map(t=>({...t}))}function vot(t){try{localStorage.setItem(Ade,JSON.stringify(t))}catch{}}function lu(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const wot={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function ML(t,e="system"){if(!t)return"-";const a=Ia(t);return a?u3(a,e):"-"}const Sot={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",storage_location:t=>t("inventory.storageLocation"),label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),spool_name:t=>t("inventory.spoolName"),cost_per_kg:t=>t("inventory.costPerKg"),weight_check:t=>t("inventory.weightCheck")},mI={id:({spool:t})=>r.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:ML(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:ML(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?ML(t.last_used,e):"Never"}),rgba:({spool:t})=>r.jsx("div",{className:"flex items-center justify-center",children:r.jsx(w5,{rgba:t.rgba,extraColors:t.extra_colors,effectType:t.effect_type,effectSize:"table",subtype:t.subtype})}),material:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:LT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const a=e[t.id];if(!a)return r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const n=a.printer_name||`Printer ${a.printer_id}`,i=a.ams_id===254||a.ams_id===255,s=!i&&a.ams_id>=128,o=fk(a.ams_id,a.tray_id,s,i);return r.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[n," ",o,a.ams_label?` (${a.ams_label})`:""]})},storage_location:({spool:t})=>t.storage_location?r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-500/20 text-blue-400",children:t.storage_location}):r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}),label_weight:({spool:t})=>r.jsx("span",{className:"text-sm text-white",children:lu(t.label_weight)}),net:({remaining:t})=>r.jsx("span",{className:"text-sm text-white",children:lu(t)}),gross:({spool:t,remaining:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:lu(e+t.core_weight)}),added_full:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?lu(t.weight_used):"-"}),printed_total:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?r.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):r.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?r.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):r.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/20 text-amber-400",children:e("inventory.stock")}),remaining:({remaining:t,pct:e})=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:r.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),r.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),spool_name:({spool:t,catalogMap:e})=>{const a=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return r.jsx("span",{className:"text-sm text-bambu-gray",children:a?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>r.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"}),weight_check:({spool:t,onSyncWeight:e})=>{const a=t.last_scale_weight;if(a==null)return r.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const n=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+n;let s,o;a0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(a)}g Calculated: ${Math.round(i)}g Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(a)}g Calculated: ${Math.round(i)}g diff --git a/static/index.html b/static/index.html index 6e08948d6..614329b53 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +